"""Comply Vanta merge, billing (checkout, webhook), license, and health endpoints."""
from __future__ import annotations

from typing import Optional

from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel

from comply.scan_state import get_scan

router = APIRouter()


# -- Vanta merge endpoint ------------------------------------------------------


@router.get("/vanta/merge/{scan_id}")
def merge_vanta(scan_id: str):
    """Merge Vanta evidence with a Comply scan for combined compliance view."""
    from comply.adapters.registry import get_adapter
    from comply.adapters.vanta_adapter import merge_vanta_report

    # Get Comply scan
    scan = get_scan(scan_id)
    if scan is None:
        raise HTTPException(404, "Scan not found")
    if scan.status != "complete" or scan.report is None:
        raise HTTPException(400, "Scan is not complete")

    # Get Vanta adapter
    adapter = get_adapter("vanta")
    if adapter is None:
        raise HTTPException(400, "Vanta adapter not configured. Add vanta config to ~/.comply/config.yaml")

    records = adapter.fetch_records(limit=1000)
    merged = merge_vanta_report(scan.report.copy(), records)
    return merged


# -- Billing endpoints ---------------------------------------------------------


class CheckoutRequest(BaseModel):
    tier: str = "pro"
    billing_period: str = "monthly"
    email: Optional[str] = None
    success_url: Optional[str] = None
    cancel_url: Optional[str] = None


@router.post("/billing/checkout")
def create_checkout(req: CheckoutRequest):
    """Create a Stripe Checkout session."""
    try:
        from comply.billing import create_checkout_session
        result = create_checkout_session(
            tier=req.tier,
            billing_period=req.billing_period,
            success_url=req.success_url or "",
            cancel_url=req.cancel_url or "",
            customer_email=req.email,
        )
        return result
    except RuntimeError as exc:
        raise HTTPException(500, str(exc))
    except ValueError as exc:
        raise HTTPException(400, str(exc))


@router.post("/billing/webhook")
async def stripe_webhook(request: Request):
    """Handle Stripe webhook events."""
    payload = await request.body()
    sig = request.headers.get("stripe-signature", "")
    try:
        from comply.billing import handle_webhook
        result = handle_webhook(payload, sig)
        return result
    except Exception as exc:
        raise HTTPException(400, str(exc))


# -- License endpoints ---------------------------------------------------------


class ActivateRequest(BaseModel):
    license_key: str


@router.post("/license/activate")
def activate_license_route(req: ActivateRequest):
    """Activate a Pro or Enterprise license key."""
    from comply.licensing import activate_license
    result = activate_license(req.license_key)
    if not result["ok"]:
        raise HTTPException(400, result["message"])
    return result


@router.post("/license/deactivate")
def deactivate_license_route():
    """Deactivate the current license and revert to free tier."""
    from comply.licensing import deactivate_license
    return deactivate_license()


@router.get("/license")
def get_license_route():
    """Get current license status."""
    from comply.licensing import get_license_status
    return get_license_status()


# -- Health endpoint -----------------------------------------------------------


@router.get("/health")
def health():
    from comply import __version__
    from comply.store import _get_conn
    db_ok = True
    try:
        _get_conn().execute("SELECT 1").fetchone()
    except Exception:
        db_ok = False
    return {"status": "ok", "service": "comply", "version": __version__, "db": db_ok}
