"""Auth routes: login, me. Stateless JWT."""
from datetime import datetime, timezone
from typing import Optional

from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field
from sqlalchemy import select
from sqlalchemy.orm import Session

from core.auth import create_access_token, get_current_user, verify_password
from db.models import User
from db.session import get_session

router = APIRouter(prefix="/api/auth", tags=["auth"])


class LoginIn(BaseModel):
    username: str = Field(min_length=1)
    password: str = Field(min_length=1)


def _days_remaining(expiry_iso: Optional[str]) -> Optional[int]:
    if not expiry_iso:
        return None
    try:
        dt = datetime.fromisoformat(expiry_iso)
        if dt.tzinfo is None:
            dt = dt.replace(tzinfo=timezone.utc)
        total = int((dt - datetime.now(timezone.utc)).total_seconds())
        if total <= 0:
            return 0
        return max(1, (total + 86399) // 86400)
    except Exception:
        return None


def shape_user(user: dict) -> dict:
    """Remove sensitive fields + add computed fields."""
    data = {k: v for k, v in user.items() if k != "password_hash"}
    data["days_remaining"] = _days_remaining(user.get("expiry_at"))
    data["is_expired"] = (
        data["days_remaining"] == 0 if data["days_remaining"] is not None else False
    )
    return data


@router.post("/login")
def login(body: LoginIn, db: Session = Depends(get_session)):
    username = body.username.strip().lower()
    user = db.scalar(select(User).where(User.username == username))
    if not user or not verify_password(body.password, user.password_hash):
        raise HTTPException(status_code=401, detail="Invalid username or password")
    token = create_access_token(user.id, user.username, user.role)
    return {"access_token": token, "token_type": "bearer", "user": shape_user(user.as_dict())}


@router.get("/me")
def me(current: dict = Depends(get_current_user), db: Session = Depends(get_session)):
    # Re-fetch for freshness (expiry may have changed server-side)
    user = db.scalar(select(User).where(User.id == current["id"]))
    if not user:
        raise HTTPException(status_code=401, detail="User not found")
    return shape_user(user.as_dict())
