"""complyform-dormancy-detection — weekly project dormancy marking.

Trigger: Weekly Cloud Scheduler (Sunday 06:00 UTC).

Marks Agency/Enterprise projects dormant after 90 days of inactivity.
Dormant projects are excluded from the usage reconciler's active count.
Enterprise Unlimited is exempt (no overage, dormancy has no billing effect).

Contract: per-customer error isolation.
"""

from __future__ import annotations

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

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

_log = logging.getLogger(__name__)

_DORMANCY_DAYS = 90
_DORMANCY_TIERS: frozenset[str] = frozenset(["agency", "enterprise"])


@cloud_function_wrapper("complyform-dormancy-detection")
async def dormancy_detection(request: Any) -> dict[str, Any]:
    """Mark Agency/Enterprise projects dormant after 90 days inactive."""
    db = get_db()
    now = datetime.now(UTC)
    cutoff = (now - timedelta(days=_DORMANCY_DAYS)).isoformat()
    stats: dict[str, int] = {"customers_checked": 0, "projects_marked_dormant": 0}

    query = db.collection("customers").where("status", "==", "active")
    async for doc in query.stream():
        customer_id = doc.id
        try:
            data = doc.to_dict() or {}
            tier = data.get("tier", "")
            if tier not in _DORMANCY_TIERS:
                continue

            stats["customers_checked"] += 1
            dormant_count = await _detect_dormant_projects(db, customer_id, cutoff, now)
            if dormant_count > 0:
                stats["projects_marked_dormant"] += dormant_count
                log_action(
                    customer_id,
                    "dormancy_detected",
                    record_count=dormant_count,
                )
        except Exception as exc:
            log_action(customer_id, "dormancy_detection", error=str(exc))
            _log.exception("Dormancy detection error for %s", customer_id)

    return stats


async def _detect_dormant_projects(
    db: Any,
    customer_id: str,
    cutoff: str,
    now: datetime,
) -> int:
    """Find and mark dormant projects. Returns count of newly dormant projects."""
    projects_ref = (
        db.collection("customers")
        .document(customer_id)
        .collection("projects")
        .where("status", "==", "active")
        .where("last_scan", "<", cutoff)
    )
    count = 0
    async for proj_doc in projects_ref.stream():
        await proj_doc.reference.update(
            {
                "status": "dormant",
                "dormant_since": now.isoformat(),
            }
        )
        count += 1
    return count


entry_point = dormancy_detection
