"""8I generation/deprecation lifecycle for leftover `/api/contact`.

Not a new runtime. New projects generate canonical Forms. Existing projects
keep executing the leftover adapter when it is already installed. Redeploy does
not silent-migrate. Live bulk migration is a later slice.
"""
from __future__ import annotations

import json
from pathlib import Path
from typing import Any

CONTACT_SUBMIT_RELATIVE_PATHS: tuple[str, ...] = (
    "functions/api/contact.js",
    "server/api/contact.post.ts",
)

LEGACY_CONTACT_SUBMIT_CONTEXT_KEY = "legacy_contact_submit"
PLATFORM_LOCK_REL = "p2hs/platform-ports.lock.json"

LEGACY_CONTACT_GENERATION: dict[str, Any] = {
    "slice_id": "8i_legacy_contact_generation_cleanup",
    "status": "complete",
    "new_project_generation": "canonical_only",
    "legacy_generation": "deprecated_for_new_projects",
    "legacy_runtime": "compatibility_only",
    "existing_project_compatibility": "preserved",
    "redeploy_policy": "preserved",
    "silent_migration": False,
    "database_schema_change_required": False,
    "live_project_migration_required": False,
    "legacy_runtime_removal_ready": False,
    "docs": "docs/audits/EMAIL_TEMPLATES_DOMAIN_8I.md",
}

GENERATION_SOURCE_MATRIX: tuple[dict[str, Any], ...] = (
    {
        "source": "catalog_adapter_files / contact_adapter_files",
        "generates_legacy_route": "conditional",
        "generates_legacy_notify": "conditional",
        "used_for_new_projects": False,
        "used_for_upgrades": True,
        "action": "omit_submit_route_unless_repo_already_has_it",
        "classification": "supported_existing_only",
    },
    {
        "source": "p2hs-contact.mjs",
        "generates_legacy_route": False,
        "generates_legacy_notify": True,
        "used_for_new_projects": "inbox_public_config_shared_lib",
        "used_for_upgrades": True,
        "action": "contain_no_new_features",
        "classification": "supported_existing_only",
    },
    {
        "source": "app-recipe.json submit_form",
        "generates_legacy_route": False,
        "generates_legacy_notify": False,
        "used_for_new_projects": True,
        "used_for_upgrades": True,
        "action": "canonical_forms_default",
        "classification": "canonical_new_project",
    },
    {
        "source": "app-recipe.json submit_form_legacy",
        "generates_legacy_route": True,
        "generates_legacy_notify": True,
        "used_for_new_projects": False,
        "used_for_upgrades": True,
        "action": "compatibility_recipe_only",
        "classification": "deprecated_for_generation",
    },
    {
        "source": "p2hs-app-client.js submitContact",
        "generates_legacy_route": False,
        "generates_legacy_notify": False,
        "used_for_new_projects": False,
        "used_for_upgrades": True,
        "action": "keep_helper_do_not_wire_new_ui",
        "classification": "supported_existing_only",
    },
    {
        "source": "forms_codegen.classify_form_intent",
        "generates_legacy_route": "only_explicit_keep_legacy",
        "generates_legacy_notify": False,
        "used_for_new_projects": True,
        "used_for_upgrades": True,
        "action": "public_submission_form_canonical",
        "classification": "canonical_new_project",
    },
    {
        "source": "prompt_wrapper / platform_backend",
        "generates_legacy_route": False,
        "generates_legacy_notify": False,
        "used_for_new_projects": True,
        "used_for_upgrades": True,
        "action": "canonical_guidance",
        "classification": "canonical_new_project",
    },
    {
        "source": "backend_guard leftover contact POST rewrite",
        "generates_legacy_route": False,
        "generates_legacy_notify": False,
        "used_for_new_projects": False,
        "used_for_upgrades": True,
        "action": "rewrite_only_when_legacy_submit_already_installed",
        "classification": "supported_existing_only",
    },
    {
        "source": "Starter Library manifests",
        "generates_legacy_route": False,
        "generates_legacy_notify": False,
        "used_for_new_projects": True,
        "used_for_upgrades": False,
        "action": "no_api_contact_in_starters",
        "classification": "canonical_new_project",
    },
    {
        "source": "App Blocks forms.contact / forms.quote_request",
        "generates_legacy_route": False,
        "generates_legacy_notify": False,
        "used_for_new_projects": True,
        "used_for_upgrades": True,
        "action": "forms_post_submit_template_actions",
        "classification": "canonical_new_project",
    },
    {
        "source": "Feature Pack contact-capture",
        "generates_legacy_route": False,
        "generates_legacy_notify": "entity_record_created",
        "used_for_new_projects": "entity_backed_only",
        "used_for_upgrades": True,
        "action": "not_globally_deprecated",
        "classification": "canonical_new_project",
    },
    {
        "source": "migrate_runtime_primitives leftover fleet",
        "generates_legacy_route": True,
        "generates_legacy_notify": True,
        "used_for_new_projects": False,
        "used_for_upgrades": True,
        "action": "explicit_leftover_onto_platform_contact",
        "classification": "supported_existing_only",
    },
)

ARTIFACT_CLASSIFICATION: dict[str, str] = {
    "POST /api/forms/{form_key}/submissions": "canonical_new_project",
    "Forms post-submit EmailTemplateInvocation": "canonical_new_project",
    "p2hs-app-client.submitGeneratedForm": "canonical_new_project",
    "POST /api/contact": "supported_existing_only",
    "p2hs-contact.notifyContactOwners": "supported_existing_only",
    "p2hs-app-client.submitContact": "supported_existing_only",
    "GET /api/contact/inbox": "supported_existing_only",
    "contact-capture-notify": "canonical_new_project",
    "submitFormEntry": "supported_existing_only",
}

CANONICAL_CONTACT_NL_PROMPTS: tuple[str, ...] = (
    "add a contact form",
    "add a quote request form",
    "send me an email when the form submits",
    "send confirmation to the customer",
    "forms.contact for a new install",
    "build a contact form",
    "quote request",
)

LEGACY_KEEP_NL_PROMPTS: tuple[str, ...] = (
    "keep /api/contact for old apps",
    "legacy /api/contact",
)

REMOVAL_CRITERIA: tuple[str, ...] = (
    "no new projects generate POST /api/contact",
    "explicit migration path exists for remaining live apps",
    "usage can be measured from existing artifacts or telemetry",
    "supported leftover projects migrated or aged out",
    "runtime references and leftover rewrite removed",
)


def repo_has_legacy_contact_submit(repo_path: str | None) -> bool:
    """Derive leftover submit usage from artifacts. No database column."""
    if not repo_path:
        return False
    root = Path(repo_path)
    if not root.is_dir():
        return False
    for rel in CONTACT_SUBMIT_RELATIVE_PATHS:
        if (root / rel).is_file():
            return True
    lock_path = root / PLATFORM_LOCK_REL
    if not lock_path.is_file():
        return False
    try:
        lock = json.loads(lock_path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError, TypeError, UnicodeDecodeError):
        return False
    if not isinstance(lock, dict):
        return False
    if lock.get("legacy_contact_submit") is True:
        return True
    files = lock.get("files") or {}
    if any(rel in files for rel in CONTACT_SUBMIT_RELATIVE_PATHS):
        return True
    routes = lock.get("routes") or []
    return "/api/contact" in routes


def resolve_legacy_contact_submit(
    context: dict | None, repo_path: str | None = None
) -> bool:
    payload = dict(context or {})
    if LEGACY_CONTACT_SUBMIT_CONTEXT_KEY in payload:
        return bool(payload[LEGACY_CONTACT_SUBMIT_CONTEXT_KEY])
    return repo_has_legacy_contact_submit(repo_path)


def duplicate_contact_notify_generated(source: str) -> bool:
    """True when generated UI would own both Forms submit and leftover contact POST."""
    text = source or ""
    uses_forms = "/api/forms/" in text or "submitGeneratedForm" in text
    uses_legacy = "submitContact(" in text or "POST /api/contact" in text
    return uses_forms and uses_legacy
