from datetime import datetime, timedelta
from typing import Optional

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

from app.config import settings

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


MAX_PASSWORD_BYTES = 72


def _truncate_password(password: str) -> str:
    """
    Truncate password to bcrypt's 72‑byte limit.

    bcrypt only uses the first 72 bytes of the password. Very long passwords
    can cause passlib/bcrypt to raise a ValueError, so we defensively
    truncate here in a UTF‑8 safe way and use the same logic for both
    hashing and verification.
    """
    if password is None:
        return ""

    password_bytes = password.encode("utf-8")
    if len(password_bytes) <= MAX_PASSWORD_BYTES:
        return password

    truncated_bytes = password_bytes[:MAX_PASSWORD_BYTES]
    # Decode back to string; ignore partial multi‑byte chars at the boundary
    return truncated_bytes.decode("utf-8", errors="ignore")


def get_password_hash(password: str) -> str:
    """Hash a password using bcrypt, enforcing the 72‑byte limit."""
    safe_password = _truncate_password(password)
    return pwd_context.hash(safe_password)


def verify_password(plain_password: str, hashed_password: str) -> bool:
    """
    Verify a password against its hash, enforcing the 72‑byte limit.

    This must use the same truncation logic as get_password_hash so that
    hashes remain consistent.
    """
    safe_password = _truncate_password(plain_password)
    return pwd_context.verify(safe_password, hashed_password)


def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
    """Create a JWT access token."""
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + timedelta(minutes=settings.access_token_expire_minutes)
    to_encode.update({"exp": expire, "type": "access"})
    encoded_jwt = jwt.encode(to_encode, settings.secret_key, algorithm=settings.algorithm)
    return encoded_jwt


def create_refresh_token(data: dict) -> str:
    """Create a JWT refresh token."""
    to_encode = data.copy()
    expire = datetime.utcnow() + timedelta(days=settings.refresh_token_expire_days)
    to_encode.update({"exp": expire, "type": "refresh"})
    encoded_jwt = jwt.encode(to_encode, settings.secret_key, algorithm=settings.algorithm)
    return encoded_jwt


def verify_token(token: str, token_type: str = "access") -> Optional[dict]:
    """Verify and decode a JWT token."""
    try:
        payload = jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm])
        if payload.get("type") != token_type:
            return None
        return payload
    except JWTError:
        return None
