from __future__ import annotations

import re
from fastapi import APIRouter, HTTPException, Header
from pydantic import BaseModel

from prompt_auto_lab.api.models import User
from prompt_auto_lab.api.services import user_service

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


class LoginRequest(BaseModel):
    username: str


class LoginResponse(BaseModel):
    user: User
    message: str


def validate_username(username: str) -> bool:
    """Validate username format: alphanumeric, underscore, hyphen, 3-30 chars."""
    if not username or len(username) < 3 or len(username) > 30:
        return False
    return bool(re.match(r'^[a-zA-Z0-9_-]+$', username))


@router.post("/login", response_model=LoginResponse)
async def login(request: LoginRequest) -> LoginResponse:
    """
    Login or register with username.
    Creates user if doesn't exist, updates last_login if exists.
    """
    username = request.username.strip().lower()

    if not validate_username(username):
        raise HTTPException(
            status_code=400,
            detail="Invalid username. Use 3-30 alphanumeric characters, underscores, or hyphens."
        )

    user = user_service.login_user(username)
    return LoginResponse(user=user, message="Login successful")


@router.get("/me", response_model=User)
async def get_current_user(x_user_id: str = Header(None)) -> User:
    """Get current user from X-User-Id header."""
    if not x_user_id:
        raise HTTPException(status_code=401, detail="X-User-Id header required")

    user = user_service.get_user(x_user_id)
    if user is None:
        raise HTTPException(status_code=401, detail="User not found")

    return user


@router.post("/logout")
async def logout(x_user_id: str = Header(None)) -> dict[str, str]:
    """Logout - placeholder for any server-side cleanup."""
    return {"status": "ok", "message": "Logged out"}
