"""License validation and resend endpoints.

- ``POST /v1/license/validate`` — validate key hash, return tier + profile URL
- ``POST /v1/license/resend``   — regenerate and email a new license key
"""

from __future__ import annotations

import logging
from datetime import UTC, datetime

from fastapi import APIRouter
from fastapi.responses import JSONResponse
from pydantic import BaseModel, ConfigDict

_log = logging.getLogger(__name__)

router = APIRouter(prefix="/v1/license")

_GCS_PROFILES_BUCKET = "complyform-prod-profiles"
_BUNDLE_BLOB = "bundle.tar.gz"
_SIGNED_URL_EXPIRY_MINUTES = 15


# ---------------------------------------------------------------------------
# Request / response models
# ---------------------------------------------------------------------------


class ValidateRequest(BaseModel):
    model_config = ConfigDict(strict=True)
    key_hash: str


class ResendRequest(BaseModel):
    model_config = ConfigDict(strict=True)
    email: str


# ---------------------------------------------------------------------------
# POST /v1/license/validate
# ---------------------------------------------------------------------------


@router.post("/validate")
async def validate_license(body: ValidateRequest) -> JSONResponse:
    """Validate a license key hash and return tier info + profile URL."""
    from backend.shared.firestore import get_license_key

    key_doc = await get_license_key(body.key_hash)
    if key_doc is None:
        return JSONResponse({"error": "invalid_key"}, status_code=401)

    if key_doc.get("status") == "revoked":
        return JSONResponse({"error": "revoked"}, status_code=401)

    expires_at = key_doc.get("expires_at", "")
    if expires_at:
        try:
            exp = datetime.fromisoformat(expires_at)
            if exp < datetime.now(UTC):
                return JSONResponse({"error": "expired"}, status_code=401)
        except ValueError, TypeError:
            pass

    # Generate signed GCS URL for profile bundle
    profile_url = _generate_signed_url()

    return JSONResponse(
        {
            "tier": key_doc.get("tier", "community"),
            "expiry": expires_at,
            "profile_url": profile_url,
            "manifest": {},
            "features": key_doc.get("features", []),
        }
    )


def _generate_signed_url() -> str:
    """Generate a signed GCS URL for the profile bundle."""
    try:
        from datetime import timedelta

        from google.cloud import storage

        client = storage.Client(project="complyform-prod")
        bucket = client.bucket(_GCS_PROFILES_BUCKET)
        blob = bucket.blob(_BUNDLE_BLOB)
        return blob.generate_signed_url(
            expiration=timedelta(minutes=_SIGNED_URL_EXPIRY_MINUTES),
            method="GET",
        )
    except Exception:
        _log.exception("Failed to generate signed profile URL")
        return ""


# ---------------------------------------------------------------------------
# POST /v1/license/resend
# ---------------------------------------------------------------------------


@router.post("/resend")
async def resend_license(body: ResendRequest) -> JSONResponse:
    """Regenerate license key and send to email.

    Always returns the same response regardless of whether the email
    matches an active subscription (prevents email enumeration).
    """
    from backend.billing.email_sender import send_template_email
    from backend.billing.license_generator import generate_license_key
    from backend.shared.firestore import (
        create_license_key,
        delete_license_key,
        find_license_key_by_customer,
        get_customer_by_email,
        update_customer,
    )

    uniform_response = JSONResponse(
        {
            "status": "ok",
            "message": (
                "If an active subscription exists for this email,"
                " a license key has been sent."
            ),
        }
    )

    result = await get_customer_by_email(body.email)
    if result is None:
        return uniform_response

    customer_id, customer_data = result

    # Find current active license key
    lk = await find_license_key_by_customer(customer_id)
    if lk is None:
        return uniform_response

    old_key_hash, old_key_data = lk

    # Generate new key
    new_key, new_key_hash = generate_license_key()

    # Replace: delete old, create new
    await delete_license_key(old_key_hash)
    now_iso = datetime.now(UTC).isoformat()
    await create_license_key(
        new_key_hash,
        {
            "customer_id": customer_id,
            "tier": old_key_data.get("tier", "community"),
            "frameworks": old_key_data.get("frameworks", []),
            "features": old_key_data.get("features", []),
            "status": "active",
            "created_at": now_iso,
            "expires_at": old_key_data.get("expires_at"),
        },
    )
    await update_customer(customer_id, {"license_key_hash": new_key_hash})

    tier = customer_data.get("tier", "community")
    activation_cmd = f"complyform config activate {new_key}"

    await send_template_email(
        to=body.email,
        template_alias="license-key-resend",
        template_model={
            "license_key": new_key,
            "tier": tier,
            "activation_command": activation_cmd,
        },
    )

    return uniform_response
