"""8K leftover contact inspect/plan.

8J concluded leftover_runtime_removal_ready=no. This slice does not delete
compatibility runtime. It exposes operator inspect/plan over cloned repos.
"""
from __future__ import annotations

from collections import Counter
from dataclasses import asdict
from pathlib import Path
from typing import Any

from src.domain.codegen.legacy_contact_generation import (
    CONTACT_SUBMIT_RELATIVE_PATHS,
    LEGACY_CONTACT_GENERATION,
)
from src.domain.codegen.legacy_contact_runtime import (
    LEGACY_CONTACT_RUNTIME,
    REMOVAL_GATE,
    RETAINED_EXECUTION,
    inspect_legacy_contact_runtime,
    leftover_runtime_removable,
    plan_legacy_contact_migration,
)

LEGACY_CONTACT_INSPECT: dict[str, Any] = {
    "slice_id": "8k_legacy_contact_inspect_and_plan",
    "status": "complete",
    "replaces": "8k_legacy_contact_runtime_removal",
    "removal_brief_executed": False,
    "legacy_runtime_removal_ready": False,
    "legacy_runtime_removal_status": "blocked",
    "apply_allowed": False,
    "shadow_compare_only": True,
    "dual_send": False,
    "database_schema_change_required": False,
    "phase_8_status": "open",
    "phase_8_closure_status": "not_accepted",
    "blocking_reason": "8J_legacy_runtime_removal_ready=no",
    "docs": "docs/audits/EMAIL_TEMPLATES_DOMAIN_8K.md",
}

REMOVAL_MATRIX: tuple[dict[str, Any], ...] = (
    {
        "component": "p2hs-contact.mjs",
        "current_purpose": "persist contact_submission; notifyContactOwners; inbox; public-config",
        "supported_dependency": "unknown_live_plus_new_install_shared_helper",
        "status_8j": "compatibility_only",
        "action_8k": "retain",
    },
    {
        "component": "POST /api/contact notification branch",
        "current_purpose": "best-effort admin email.send after leftover submit persist",
        "supported_dependency": "unknown_live",
        "status_8j": "compatibility_only",
        "action_8k": "retain",
    },
    {
        "component": "POST /api/contact route",
        "current_purpose": "leftover public submit (validate, persist, notify)",
        "supported_dependency": "unknown_live",
        "status_8j": "compatibility_only",
        "action_8k": "retain",
    },
    {
        "component": "notifyContactOwners",
        "current_purpose": "Cloud-render contact_capture.admin_notify then email.send",
        "supported_dependency": "unknown_live",
        "status_8j": "compatibility_only",
        "action_8k": "retain",
    },
    {
        "component": "leftover submit generation (existing lock/files)",
        "current_purpose": "redeploy and leftover-fleet reinstall leftover submit",
        "supported_dependency": "existing_projects",
        "status_8j": "compatibility_only",
        "action_8k": "retain",
    },
    {
        "component": "GET /api/contact/inbox",
        "current_purpose": "staff list contact_submission",
        "supported_dependency": "supported_existing_only",
        "status_8j": "supported_existing_only",
        "action_8k": "retain",
    },
    {
        "component": "contact-capture-notify pack",
        "current_purpose": "entity record.created admin + confirmation",
        "supported_dependency": "canonical_entity_path",
        "status_8j": "canonical_for_entity_path",
        "action_8k": "retain",
    },
)

PLATFORM_LEFTOVER_RUNTIME_FILES: tuple[str, ...] = (
    "src/domain/codegen/runtime/p2hs-contact.mjs",
    "src/domain/codegen/runtime/contact-pages-fn.js",
    "src/domain/codegen/runtime/contact-route.ts",
    "src/domain/codegen/runtime/contact-inbox-pages-fn.js",
    "src/domain/codegen/runtime/contact-inbox-route.ts",
)


def assert_removal_precondition_failed() -> None:
    if LEGACY_CONTACT_RUNTIME["legacy_runtime_removal_ready"] is True:
        raise RuntimeError("8J unexpectedly marks leftover runtime removable")
    if leftover_runtime_removable():
        raise RuntimeError("REMOVAL_GATE unexpectedly all true")
    if LEGACY_CONTACT_GENERATION["legacy_runtime_removal_ready"] is True:
        raise RuntimeError("8I unexpectedly marks leftover runtime removable")


def leftover_runtime_files_present(repo_root: str | Path | None = None) -> bool:
    root = Path(repo_root) if repo_root else Path(__file__).resolve().parents[3]
    return all((root / rel).is_file() for rel in PLATFORM_LEFTOVER_RUNTIME_FILES)


def inspect_legacy_contact_report(repo_path: str) -> dict[str, Any]:
    """JSON-serializable inspect + dry-run plan. Never applies."""
    assert_removal_precondition_failed()
    inspection = inspect_legacy_contact_runtime(repo_path)
    plan = plan_legacy_contact_migration(repo_path)
    return {
        "slice_id": LEGACY_CONTACT_INSPECT["slice_id"],
        "repo_path": str(Path(repo_path).resolve()) if repo_path else repo_path,
        "removal_gate_passed": False,
        "legacy_runtime_removal_ready": False,
        "apply_allowed": False,
        "shadow_compare_only": True,
        "send": False,
        "inspection": asdict(inspection),
        "plan": asdict(plan),
        "submit_artifact_paths": list(CONTACT_SUBMIT_RELATIVE_PATHS),
        "retained_execution_ids": [row["id"] for row in RETAINED_EXECUTION],
        "removal_gate": dict(REMOVAL_GATE),
    }


def inspect_legacy_contact_batch(repo_paths: list[str]) -> dict[str, Any]:
    reports = [inspect_legacy_contact_report(path) for path in repo_paths]
    counts = Counter(row["inspection"]["project_class"] for row in reports)
    eligibility = Counter(row["inspection"]["migration_class"] for row in reports)
    return {
        "slice_id": LEGACY_CONTACT_INSPECT["slice_id"],
        "removal_gate_passed": False,
        "apply_allowed": False,
        "repo_count": len(reports),
        "project_class_counts": dict(counts),
        "migration_class_counts": dict(eligibility),
        "fleet_measurement": "supplied_clones_only",
        "platform_live_fleet": "still_unmeasured",
        "reports": reports,
    }
