"""
Authentication routes: login, logout, me.
"""

from __future__ import annotations

from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel

from pycharter.api.dependencies.auth import (
    ACCESS_TOKEN_EXPIRE_SECONDS,
    create_access_token,
    get_current_user,
    verify_initial_credentials,
)
from pycharter.config import (
    get_auth_initial_credentials,
    get_auth_jwt_secret,
    is_auth_disabled,
)

router = APIRouter(tags=["Auth"])


class LoginRequest(BaseModel):
    username: str
    password: str


class LoginResponse(BaseModel):
    access_token: str
    token_type: str = "bearer"
    expires_in: int = ACCESS_TOKEN_EXPIRE_SECONDS


class UserResponse(BaseModel):
    username: str
    auth_disabled: bool = False


@router.post(
    "/auth/login",
    response_model=LoginResponse,
    status_code=status.HTTP_200_OK,
    summary="Login",
    description="Exchange username and password for an access token. Uses initial credentials (env or pycharter.cfg) when configured.",
)
def login(request: LoginRequest) -> LoginResponse:
    if is_auth_disabled():
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail="Authentication is disabled",
        )
    creds = get_auth_initial_credentials()
    if not creds:
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail="Authentication not configured (set initial credentials or auth service)",
        )
    if not get_auth_jwt_secret():
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail="JWT secret not configured (set PYCHARTER_AUTH_JWT_SECRET or auth.jwt_secret)",
        )
    if not verify_initial_credentials(request.username, request.password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid username or password",
        )
    token = create_access_token(request.username)
    return LoginResponse(
        access_token=token,
        token_type="bearer",
        expires_in=ACCESS_TOKEN_EXPIRE_SECONDS,
    )


@router.post(
    "/auth/logout",
    status_code=status.HTTP_200_OK,
    summary="Logout",
    description="Client should discard the token. Server-side invalidation can be added later.",
)
def logout() -> dict:
    return {"message": "OK"}


@router.get(
    "/auth/me",
    response_model=UserResponse,
    status_code=status.HTTP_200_OK,
    summary="Current user",
    description="Return the current user from the Bearer token. Protected.",
)
def me(current_user: dict = Depends(get_current_user)) -> UserResponse:
    return UserResponse(
        username=current_user["username"],
        auth_disabled=current_user.get("auth_disabled", False),
    )
