from __future__ import annotations

import secrets
from datetime import datetime, timedelta, timezone

from fastapi import HTTPException, status
from jose import JWTError, jwt

from epochler.config import get_settings


def verify_password(plain: str) -> bool:
    settings = get_settings()
    return secrets.compare_digest(plain.encode(), settings.epochler_password.encode())


def create_token() -> str:
    settings = get_settings()
    expire = datetime.now(timezone.utc) + timedelta(minutes=settings.jwt_expire_minutes)
    return jwt.encode(
        {"sub": "epochler_user", "exp": expire},
        settings.epochler_secret_key,
        algorithm=settings.jwt_algorithm,
    )


def validate_token(token: str) -> bool:
    settings = get_settings()
    try:
        payload = jwt.decode(
            token, settings.epochler_secret_key, algorithms=[settings.jwt_algorithm]
        )
        return payload.get("sub") == "epochler_user"
    except JWTError:
        return False


def require_token(token: str) -> None:
    if not validate_token(token):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid or expired token"
        )
