"""Phase 10D4 — Core transport fidelity for domain-event runtime mappings.

Proves catalog PackEvent → runtime_domain_event_payload → stamp_composition
→ entity.schema.domain_events. Does not change ontology or producer kinds.
"""

from src.domain.connectors.crm_events import REJECTED_CRM_EVENT_TYPES
from src.domain.feature_packs.events import (
    COMPOSITION_ONLY_EVENT_IDS,
    catalog_event_index,
    resolve_canonical_event_id,
    runtime_domain_event_payload,
)
from src.domain.feature_packs.normalize import load_pack_contract, stamp_composition


def _stamp(slug: str, entity_key: str, fields: list[dict]) -> dict:
    stamped = stamp_composition(
        slug,
        {"requires": [], "entities": [{"entity_key": entity_key, "schema": {"fields": fields}}]},
    )
    return stamped["entities"][0]["schema"]


def _ids(schema: dict) -> list[str]:
    return [item["id"] for item in schema.get("domain_events") or []]


def _by_id(schema: dict, event_id: str) -> dict:
    return next(item for item in schema["domain_events"] if item["id"] == event_id)


def test_10d4_contact_submitted_is_the_only_transported_contact_event():
    schema = _stamp(
        "contact-capture",
        "contact_submission",
        [
            {"key": "email", "type": "text"},
            {"key": "name", "type": "text"},
            {"key": "notify_attempts", "type": "number"},
        ],
    )
    assert _ids(schema) == ["contact.submitted"]
    payload = _by_id(schema, "contact.submitted")
    assert payload["producer"] == {"kind": "record.created", "entity": "contact_submission"}
    assert {item["id"]: item["kind"] for item in payload["aliases"]} == {
        "forms.contact.submitted": "composition",
        "form.submitted": "transport",
    }
    contract = load_pack_contract("contact-capture", {})
    none_ids = [item.id for item in contract.events if item.producer is None]
    assert "contact.notification_sent" in none_ids
    assert "contact.submitted" not in none_ids
    for event in contract.events:
        if event.producer is None:
            assert runtime_domain_event_payload(event) is None


def test_10d4_lead_lifecycle_stamps_explicit_won_to_state():
    schema = _stamp(
        "lead-lifecycle",
        "lead",
        [
            {
                "key": "status",
                "type": "select",
                "options": ["new", "contacted", "qualified", "won", "lost"],
            }
        ],
    )
    assert _ids(schema) == [
        "lead.created",
        "lead.status_changed",
        "lead.won",
        "lead.lost",
    ]
    won = _by_id(schema, "lead.won")
    assert won["producer"] == {
        "kind": "workflow.transition",
        "entity": "lead",
        "field": "status",
        "to_state": "won",
    }
    changed = _by_id(schema, "lead.status_changed")
    assert "to_state" not in changed["producer"]
    assert changed["aliases"] == [
        {"id": "crm.lead.status_changed", "kind": "composition"}
    ]
    created = _by_id(schema, "lead.created")
    assert created["aliases"] == [{"id": "crm.lead.created", "kind": "composition"}]


def test_10d4_case_resolved_uses_case_record_entity():
    schema = _stamp(
        "case-lifecycle",
        "case_record",
        [
            {
                "key": "status",
                "type": "select",
                "options": ["open", "in_review", "waiting", "resolved", "closed"],
            }
        ],
    )
    assert "case.resolved" in _ids(schema)
    resolved = _by_id(schema, "case.resolved")
    assert resolved["producer"]["entity"] == "case_record"
    assert resolved["producer"]["to_state"] == "resolved"
    assert resolved["id"] == "case.resolved"


def test_10d4_approval_approved_stamps_to_state():
    schema = _stamp(
        "approval-workflow",
        "approval_request",
        [
            {
                "key": "status",
                "type": "select",
                "options": ["pending", "approved", "rejected", "escalated"],
            },
            {"key": "approver_role", "type": "text"},
            {"key": "requested_by", "type": "text"},
        ],
    )
    approved = _by_id(schema, "approval.approved")
    assert approved["producer"]["kind"] == "workflow.transition"
    assert approved["producer"]["to_state"] == "approved"


def test_10d4_ticket_assigned_is_field_changed_on_support_ticket():
    schema = _stamp(
        "support-inbox",
        "support_ticket",
        [
            {
                "key": "status",
                "type": "select",
                "options": ["open", "pending", "resolved", "closed"],
            },
            {"key": "assigned_to", "type": "text"},
        ],
    )
    assigned = _by_id(schema, "ticket.assigned")
    assert assigned["producer"] == {
        "kind": "field.changed",
        "entity": "support_ticket",
        "field": "assigned_to",
    }
    assert "ticket.created" in _ids(schema)
    assert "ticket.status_changed" in _ids(schema)


def test_10d4_quote_request_and_producer_none_are_not_transported():
    quote = _stamp(
        "contact-capture",
        "quote_request",
        [{"key": "email", "type": "text"}],
    )
    assert "domain_events" not in quote
    messaging = stamp_composition(
        "messaging",
        {
            "requires": [],
            "entities": [
                {
                    "entity_key": "conversation_membership",
                    "schema": {"fields": [{"key": "role", "type": "text"}]},
                },
                {
                    "entity_key": "message",
                    "schema": {"fields": [{"key": "body", "type": "text"}]},
                },
            ],
        },
    )
    by_key = {item["entity_key"]: item["schema"] for item in messaging["entities"]}
    assert "domain_events" not in by_key["conversation_membership"]
    assert _ids(by_key["message"]) == ["message.sent"]
    contract = load_pack_contract("messaging", {})
    conversation = next(item for item in contract.events if item.id == "conversation.created")
    assert conversation.producer is None
    assert runtime_domain_event_payload(conversation) is None
    assert "forms.quote_request.submitted" in COMPOSITION_ONLY_EVENT_IDS


def test_10d4_crm_lead_created_alias_does_not_expand_inbound_types():
    index = catalog_event_index(
        [
            load_pack_contract("lead-lifecycle", {}),
            load_pack_contract("crm-pipeline", {}),
        ]
    )
    assert resolve_canonical_event_id("crm.lead.created", index) == "lead.created"
    assert "crm.lead.created" in REJECTED_CRM_EVENT_TYPES
    assert resolve_canonical_event_id("crm.contact.created", index) is None
    pipeline = load_pack_contract("crm-pipeline", {})
    assert all(runtime_domain_event_payload(item) is None for item in pipeline.events)
