"""complyform-backup-verify — weekly Firestore export verification.

Trigger: Weekly Cloud Scheduler.

Lists the most recent Firestore export in the DR bucket, verifies it exists,
is non-empty, and within 50% of the previous export size.  Emails pass/fail
to ``alerts@complyform.dev``.

Contract: uses ADC for GCS access.  Always returns 200.
"""

from __future__ import annotations

import logging
from typing import Any

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

_log = logging.getLogger(__name__)

_DR_BUCKET = "complyform-dr-exports"
_EXPORT_PREFIX = "firestore-exports/"


@cloud_function_wrapper("complyform-backup-verify")
async def backup_verify(request: Any) -> dict[str, Any]:
    """Verify latest Firestore export exists in DR bucket."""
    from google.cloud import storage

    client = storage.Client(project="complyform-prod")
    bucket = client.bucket(_DR_BUCKET)

    # List blobs under the export prefix, sorted by time
    blobs = list(bucket.list_blobs(prefix=_EXPORT_PREFIX))
    if not blobs:
        await send_alert_email(
            subject="[ComplyForm] Backup Verify FAILED — no exports found",
            body=(
                f"No Firestore exports found in gs://{_DR_BUCKET}/{_EXPORT_PREFIX}\n\n"
                "Action: check Firestore scheduled export configuration."
            ),
        )
        log_action(customer_id=None, action="backup_verify_fail", error="no_exports")
        return {"status": "fail", "reason": "no_exports"}

    # Sort by creation time (most recent last)
    blobs.sort(key=lambda b: b.time_created or "")
    latest = blobs[-1]
    latest_size = latest.size or 0

    if latest_size == 0:
        await send_alert_email(
            subject="[ComplyForm] Backup Verify FAILED — empty export",
            body=f"Latest export {latest.name} has 0 bytes.",
        )
        log_action(
            customer_id=None,
            action="backup_verify_fail",
            error="empty_export",
            blob=latest.name,
        )
        return {"status": "fail", "reason": "empty_export", "blob": latest.name}

    # Compare with previous export size
    warning = None
    if len(blobs) >= 2:
        previous = blobs[-2]
        previous_size = previous.size or 1
        ratio = latest_size / previous_size
        if ratio < 0.5:
            warning = (
                f"Size anomaly: latest={latest_size} bytes, "
                f"previous={previous_size} bytes (ratio={ratio:.2f})"
            )
            await send_alert_email(
                subject="[ComplyForm] Backup Verify WARNING — size anomaly",
                body=(
                    f"Latest export: {latest.name} ({latest_size:,} bytes)\n"
                    f"Previous export: {previous.name} ({previous_size:,} bytes)\n"
                    f"Ratio: {ratio:.2f} (threshold: 0.50)\n\n"
                    "The latest export is significantly smaller than the previous one."
                ),
            )

    # Record result in Firestore for DR test reference
    db = get_db()
    await (
        db.collection("founder_metrics")
        .document("backup_verify")
        .set(
            {
                "latest_blob": latest.name,
                "latest_size": latest_size,
                "blob_count": len(blobs),
                "warning": warning,
                "status": "warn" if warning else "pass",
            }
        )
    )

    if not warning:
        await send_alert_email(
            subject="[ComplyForm] Backup Verify PASSED",
            body=(
                f"Latest export: {latest.name} ({latest_size:,} bytes)\n"
                f"Total exports: {len(blobs)}\n\nAll checks passed."
            ),
        )

    log_action(
        customer_id=None,
        action="backup_verify_pass",
        blob=latest.name,
        size=latest_size,
        warning=warning,
    )
    return {
        "status": "warn" if warning else "pass",
        "blob": latest.name,
        "size": latest_size,
    }


entry_point = backup_verify
