from typing import Any

from fastapi import APIRouter, Header, HTTPException, Query
from pydantic import BaseModel, Field

from config import settings
from services.license_service import (
    activate_license,
    deactivate_local_license,
    license_status,
    mint_license,
    validate_license,
)
from services.paychek_account import login_with_email_password

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


class ActivateBody(BaseModel):
    license_key: str = Field(..., min_length=8, max_length=64)


class MintBody(BaseModel):
    note: str = "manual"
    max_activations: int = Field(default=1, ge=1, le=5)


class AccountLoginBody(BaseModel):
    email: str = Field(..., min_length=3, max_length=200)
    password: str = Field(..., min_length=1, max_length=200)


def _check_admin_secret(
    secret_query: str | None,
    secret_header: str | None,
) -> None:
    provided = secret_query or secret_header
    if not provided or provided != settings.webhook_secret:
        raise HTTPException(status_code=401, detail="Invalid admin secret")


@router.get("/status")
def get_license_status() -> dict[str, Any]:
    return validate_license(online=True)


@router.post("/activate")
def post_activate(body: ActivateBody) -> dict[str, Any]:
    try:
        return activate_license(body.license_key)
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc


@router.post("/validate")
def post_validate() -> dict[str, Any]:
    return validate_license(online=True)


@router.post("/deactivate")
def post_deactivate() -> dict[str, Any]:
    """Clear local license binding (shows activation screen again)."""
    return deactivate_local_license()


@router.post("/account/login")
def post_account_login(body: AccountLoginBody) -> dict[str, Any]:
    """Legacy Firebase password login (optional; UI uses code-only activate)."""
    try:
        login_with_email_password(body.email, body.password)
        return license_status()
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc


@router.post("/account/logout")
def post_account_logout() -> dict[str, Any]:
    """Clear local session (bound key) — same as deactivate."""
    return deactivate_local_license()


@router.post("/mint")
def post_mint(
    body: MintBody | None = None,
    secret: str | None = Query(default=None),
    x_webhook_secret: str | None = Header(default=None, alias="X-Webhook-Secret"),
) -> dict[str, Any]:
    """Issue a new license key (protected — use webhook secret)."""
    _check_admin_secret(secret, x_webhook_secret)
    payload = body or MintBody()
    entry = mint_license(note=payload.note, max_activations=payload.max_activations)
    return {"ok": True, "license_key": entry["key"], "license": entry}
