import secrets
import string
from datetime import datetime, timedelta, timezone
from uuid import uuid4

from jose import JWTError, jwt
from passlib.context import CryptContext

from app.config import settings

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")


def hash_password(password: str) -> str:
    return pwd_context.hash(password)


def verify_password(plain: str, hashed: str) -> bool:
    return pwd_context.verify(plain, hashed)


def create_token(subject: str, role: str, token_type: str = "access") -> tuple[str, str]:
    """生成 JWT，返回 (token, jti)。"""
    if token_type == "access":
        expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    else:
        expires = timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS)

    expire = datetime.now(timezone.utc) + expires
    jti = uuid4().hex
    payload = {
        "sub": str(subject),
        "role": role,
        "type": token_type,
        "exp": expire,
        "jti": jti,
    }
    token = jwt.encode(payload, settings.JWT_SECRET_KEY, algorithm=settings.JWT_ALGORITHM)
    return token, jti


def decode_token(token: str) -> dict:
    try:
        return jwt.decode(token, settings.JWT_SECRET_KEY, algorithms=[settings.JWT_ALGORITHM])
    except JWTError:
        raise


_PWD_ALPHABET = string.ascii_letters + string.digits + "!@#$%^&*"


def generate_password(length: int = 14) -> str:
    """生成强密码：必含字母、数字、符号各一种。"""
    while True:
        pwd = "".join(secrets.choice(_PWD_ALPHABET) for _ in range(length))
        if (
            any(c.isupper() for c in pwd)
            and any(c.islower() for c in pwd)
            and any(c.isdigit() for c in pwd)
            and any(c in "!@#$%^&*" for c in pwd)
        ):
            return pwd
