import os
from datetime import datetime, timedelta, timezone
from passlib.context import CryptContext
import jwt

# Load from config via environment
SECRET_KEY = os.getenv("JWT_SECRET", "CuCu-Note-Secret-Key-123")
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24  # 1 day for access token
REFRESH_TOKEN_EXPIRE_DAYS = 30  # 30 days for refresh token

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

def verify_password(plain_password: str, hashed_password: str) -> bool:
    # bcrypt truncates at 72 bytes — must truncate consistently before verify
    return pwd_context.verify(plain_password.encode("utf-8")[:72], hashed_password)

def get_password_hash(password: str) -> str:
    # bcrypt has a 72-byte limit — truncate to avoid ValueError
    return pwd_context.hash(password.encode("utf-8")[:72])

def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str:
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.now(timezone.utc) + expires_delta
    else:
        expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt

def create_refresh_token(data: dict) -> tuple[str, datetime]:
    to_encode = data.copy()
    expire = datetime.now(timezone.utc) + timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS)
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt, expire

def decode_token(token: str) -> dict | None:
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        return payload
    except jwt.PyJWTError:
        return None
