"""
用户数据模型
"""

from dataclasses import dataclass, asdict
from datetime import datetime
from typing import Optional, Dict, Any
import uuid
import hashlib
import json


@dataclass
class User:
    """用户数据模型"""
    id: str
    username: str
    email: str
    password_hash: str
    display_name: str
    avatar_url: Optional[str] = None
    is_active: bool = True
    created_at: str = ""
    updated_at: str = ""
    last_login: Optional[str] = None
    
    def __post_init__(self):
        if not self.created_at:
            self.created_at = datetime.now().isoformat()
        if not self.updated_at:
            self.updated_at = datetime.now().isoformat()
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        return asdict(self)
    
    def to_safe_dict(self) -> Dict[str, Any]:
        """转换为安全字典（不包含密码）"""
        data = self.to_dict()
        data.pop('password_hash', None)
        return data
    
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'User':
        """从字典创建用户对象"""
        return cls(**data)
    
    def update_last_login(self):
        """更新最后登录时间"""
        self.last_login = datetime.now().isoformat()
        self.updated_at = datetime.now().isoformat()


@dataclass
class LoginRequest:
    """登录请求数据"""
    username_or_email: str
    password: str


@dataclass
class RegisterRequest:
    """注册请求数据"""
    username: str
    email: str
    password: str
    display_name: Optional[str] = None
    
    def __post_init__(self):
        if not self.display_name:
            self.display_name = self.username


@dataclass
class AuthResponse:
    """认证响应数据"""
    success: bool
    message: str
    user: Optional[Dict[str, Any]] = None
    token: Optional[str] = None
    expires_at: Optional[str] = None


def hash_password(password: str) -> str:
    """密码哈希"""
    return hashlib.sha256(password.encode()).hexdigest()


def verify_password(password: str, password_hash: str) -> bool:
    """验证密码"""
    return hash_password(password) == password_hash


def generate_user_id() -> str:
    """生成用户ID"""
    return str(uuid.uuid4())
