"""complyform-arr-monitor — daily ARR snapshot + SOC 2 readiness alert.

Trigger: Daily Cloud Scheduler (09:00 UTC).

Queries Paddle API for active subscriptions, computes MRR/ARR by tier, and
writes to ``founder_metrics/latest``.  When MRR reaches $8,333 ($100K ARR),
sends a one-time SOC 2 readiness alert email.

Contract: Paddle failure logs and returns 200.
"""

from __future__ import annotations

import logging
from datetime import UTC, datetime
from typing import Any

import httpx

from backend.ops._shared import cloud_function_wrapper, log_action, send_alert_email
from backend.shared.firestore import get_db
from backend.shared.tier_config import TIER_CONFIG

_log = logging.getLogger(__name__)

_PADDLE_API_BASE = "https://api.paddle.com"
_SOC2_MRR_THRESHOLD = 8_333.0  # $100K ARR ÷ 12


_TIER_ANNUAL_PRICES: dict[str, int] = {
    tier: int(cfg["price_annual"])  # type: ignore[arg-type]
    for tier, cfg in TIER_CONFIG.items()
    if isinstance(cfg.get("price_annual"), int) and int(cfg["price_annual"]) > 0  # type: ignore[arg-type]
}


async def _get_paddle_api_key() -> str:
    """Retrieve Paddle API key from Secret Manager."""
    from google.cloud import secretmanager

    client = secretmanager.SecretManagerServiceClient()
    name = "projects/complyform-prod/secrets/paddle-api-key/versions/latest"
    response = client.access_secret_version(request={"name": name})
    return response.payload.data.decode("utf-8")


def _resolve_tier(sub: dict[str, Any]) -> str:
    """Resolve tier from subscription custom_data or price IDs."""
    custom_data = sub.get("custom_data") or {}
    tier = custom_data.get("tier")
    if tier and isinstance(tier, str):
        return tier
    items = sub.get("items", [])
    for item in items:
        price = item.get("price", {})
        price_id = price.get("id", "")
        if "pro" in price_id:
            return "pro"
        if "team" in price_id:
            return "team"
        if "agency" in price_id:
            return "agency"
        if "enterprise_unlimited" in price_id:
            return "enterprise_unlimited"
        if "enterprise" in price_id:
            return "enterprise"
    return "unknown"


@cloud_function_wrapper("complyform-arr-monitor")
async def arr_monitor(request: Any) -> dict[str, Any]:
    """Daily ARR snapshot + SOC 2 readiness threshold alert."""
    paddle_key = await _get_paddle_api_key()
    headers = {
        "Authorization": f"Bearer {paddle_key}",
        "Content-Type": "application/json",
    }

    subs: list[dict[str, Any]] = []
    url = f"{_PADDLE_API_BASE}/subscriptions?status=active&per_page=200"
    async with httpx.AsyncClient(timeout=30.0) as client:
        while url:
            resp = await client.get(url, headers=headers)
            resp.raise_for_status()
            body = resp.json()
            subs.extend(body.get("data", []))
            url = body.get("meta", {}).get("pagination", {}).get("next", "")

    # Compute MRR by tier
    tier_counts: dict[str, int] = {}
    mrr = 0.0
    for sub in subs:
        tier = _resolve_tier(sub)
        tier_counts[tier] = tier_counts.get(tier, 0) + 1
        annual = _TIER_ANNUAL_PRICES.get(tier, 0)
        mrr += annual / 12

    arr = mrr * 12

    snapshot = {
        "mrr": round(mrr, 2),
        "arr": round(arr, 2),
        "tier_counts": tier_counts,
        "total_subscriptions": len(subs),
        "updated_at": datetime.now(UTC).isoformat(),
    }

    db = get_db()

    # Check if SOC 2 alert already sent
    latest_doc = await db.collection("founder_metrics").document("latest").get()
    soc2_already_sent = False
    if latest_doc.exists:
        prev = latest_doc.to_dict() or {}
        soc2_already_sent = prev.get("soc2_alert_sent", False)

    # SOC 2 readiness alert at $100K ARR
    if mrr >= _SOC2_MRR_THRESHOLD and not soc2_already_sent:
        snapshot["soc2_alert_sent"] = True
        await send_alert_email(
            subject="[ComplyForm] SOC 2 Readiness: $100K ARR threshold reached",
            body=(
                f"MRR has reached ${mrr:,.2f} (ARR ${arr:,.2f}).\n\n"
                "This triggers the SOC 2 readiness milestone.\n"
                "Review the SOC 2 preparation checklist and begin auditor selection."
            ),
        )
        log_action(
            customer_id=None,
            action="soc2_readiness_alert_sent",
            mrr=mrr,
            arr=arr,
        )
    elif soc2_already_sent:
        snapshot["soc2_alert_sent"] = True

    # Write to latest
    await db.collection("founder_metrics").document("latest").set(snapshot)

    log_action(
        customer_id=None,
        action="arr_snapshot_written",
        mrr=mrr,
        arr=arr,
        total_subscriptions=len(subs),
    )
    return {"mrr": round(mrr, 2), "arr": round(arr, 2)}


entry_point = arr_monitor
