"""
Authentication module for Google Alerts Reporter Web App
"""
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from passlib.context import CryptContext
import secrets
from .config import settings

# Password hashing context
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

# HTTP Basic Auth
security = HTTPBasic()


def verify_password(plain_password: str, hashed_password: str) -> bool:
    """Verify a plain password against hashed password."""
    return pwd_context.verify(plain_password, hashed_password)


def get_password_hash(password: str) -> str:
    """Hash a password."""
    return pwd_context.hash(password)


def authenticate_user(username: str, password: str) -> bool:
    """
    Authenticate user credentials.

    Args:
        username: Username
        password: Plain password

    Returns:
        True if authenticated, False otherwise
    """
    # Simple authentication (can be extended to database)
    if username != settings.admin_username:
        return False

    # For security, hash the password from .env in production
    # Here we compare directly (in production, store hashed passwords)
    return password == settings.admin_password


async def get_current_user(credentials: HTTPBasicCredentials = Depends(security)) -> str:
    """
    Dependency to get current authenticated user.

    Args:
        credentials: HTTP Basic credentials

    Returns:
        Username if authenticated

    Raises:
        HTTPException: If authentication fails
    """
    # Timing attack protection
    correct_username = secrets.compare_digest(
        credentials.username.encode("utf-8"),
        settings.admin_username.encode("utf-8")
    )
    correct_password = secrets.compare_digest(
        credentials.password.encode("utf-8"),
        settings.admin_password.encode("utf-8")
    )

    if not (correct_username and correct_password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Credenciais inválidas",
            headers={"WWW-Authenticate": "Basic"},
        )

    return credentials.username
