"""8H contact notification ownership. Orchestration only — Cloud still renders.

Forms-backed submissions do not write ``contact_submission``, so the pack
``contact-capture-notify`` function does not run on that path. Entity-backed
``/api/contact`` remains pack-owned; generated ``notifyContactOwners`` is a
compatibility admin send sharing the pack idempotency key.
"""
from __future__ import annotations

from collections.abc import Mapping
from typing import Any

from src.domain.codegen.email_template_consumption import (
    CONTACT_CAPTURE_ADMIN_NOTIFY,
    CONTACT_CAPTURE_CONFIRMATION,
)
from src.domain.forms.actions import FormPostSubmitAction
from src.domain.forms.email_template import email_send_template_action

ADMIN_TEMPLATE_KEY = "contact_capture.admin_notify"
CONFIRMATION_TEMPLATE_KEY = "contact_capture.confirmation"
PACK_NOTIFY_SLUG = "contact-capture-notify"
LEGACY_ADMIN_IDEMPOTENCY_PREFIX = "contact-notify:"
LEGACY_CONFIRM_IDEMPOTENCY_PREFIX = "contact-confirm:"

CONTACT_NOTIFICATION_OWNERSHIP: dict[str, Any] = {
    "slice_id": "8h_contact_notification_path_convergence",
    "status": "complete",
    "new_project_owner": "forms_post_submit",
    "forms_writes_contact_submission": False,
    "pack_notify_on_forms_persist": False,
    "legacy_generation": "deprecated_for_new_projects",
    "legacy_runtime": "compatibility_only",
    "pack_entity_owner": "contact-capture-notify",
    "renderer": "cloud",
    "delivery": "email.send",
    "fallback_on_forms": False,
    "legacy_admin_fallback": "caller_resilience",
    "project_migration_required": False,
    "docs": "docs/audits/EMAIL_TEMPLATES_DOMAIN_8H.md",
}

CONTACT_NOTIFICATION_TOPOLOGIES: dict[str, dict[str, Any]] = {
    "forms_backed_contact": {
        "submit": "POST /api/forms/{form_key}/submissions",
        "admin_owner": "forms_post_submit",
        "confirmation_owner": "forms_post_submit",
        "rendering": "canonical_cloud",
        "delivery": "email.send",
        "status": "canonical",
        "pack_notify": False,
        "legacy_adapter": False,
    },
    "forms_backed_quote": {
        "submit": "POST /api/forms/{form_key}/submissions",
        "admin_owner": "forms_post_submit",
        "confirmation_owner": "forms_post_submit",
        "rendering": "canonical_cloud",
        "delivery": "email.send",
        "status": "canonical",
        "pack_notify": False,
        "legacy_adapter": False,
        "template_keys": (ADMIN_TEMPLATE_KEY, CONFIRMATION_TEMPLATE_KEY),
    },
    "entity_backed_contact_capture": {
        "submit": "record.created contact_submission",
        "admin_owner": "contact-capture-notify",
        "confirmation_owner": "contact-capture-notify",
        "rendering": "canonical_cloud",
        "delivery": "email.send",
        "status": "supported",
        "pack_notify": True,
        "legacy_adapter": False,
    },
    "legacy_api_contact": {
        "submit": "POST /api/contact",
        "admin_owner": "contact-capture-notify",
        "admin_compatibility": "p2hs-contact.notifyContactOwners",
        "confirmation_owner": "contact-capture-notify",
        "rendering": "canonical_cloud",
        "delivery": "email.send",
        "status": "compatibility_only",
        "generation": "deprecated_for_new_projects",
        "admin_dedupe": f"{LEGACY_ADMIN_IDEMPOTENCY_PREFIX}{{record_id}}",
        "pack_notify": True,
        "legacy_adapter": True,
    },
}


def _truthy(config: Mapping[str, Any], key: str) -> bool:
    return config.get(key) in {True, "true", "1", 1}


def expected_forms_email_send_count(config: Mapping[str, Any]) -> int:
    count = 0
    if str(config.get("notify_to_email") or "").strip():
        count += 1
    if _truthy(config, "send_confirmation_email"):
        count += 1
    return count


def forms_contact_notification_actions(
    config: Mapping[str, Any],
) -> tuple[FormPostSubmitAction, ...]:
    """Explicit Forms orchestration. Omitting an action is how send is suppressed."""
    actions: list[FormPostSubmitAction] = []
    notify_to = str(config.get("notify_to_email") or "").strip()
    if notify_to:
        actions.append(
            email_send_template_action(
                key="owner_notify",
                invocation=CONTACT_CAPTURE_ADMIN_NOTIFY,
                mapping={"reply_to": "email"},
                constants={"to": notify_to.split(",")[0].strip()},
                optional=True,
            )
        )
    if _truthy(config, "send_confirmation_email"):
        actions.append(
            email_send_template_action(
                key="send_confirmation",
                invocation=CONTACT_CAPTURE_CONFIRMATION,
                mapping={"to": "email"},
                optional=True,
            )
        )
    return tuple(actions)
