"""市場情報 MCP runtime promotion gate preview。

本模組只把操作員貼上的 MCP 啟用證據與 runtime smoke 收據合併審核；
不打 health、不開 DB、不保存 payload、不抓外站、不掛 scheduler。
"""

from services.market_intel.mcp_activation_evidence import (
    build_mcp_activation_evidence_preview,
)
from services.market_intel.mcp_runtime_smoke_receipt import (
    build_mcp_runtime_smoke_receipt_preview,
)


def _sample_promotion_package():
    return {
        "activation_evidence": build_mcp_activation_evidence_preview()[
            "sample_evidence_template"
        ],
        "runtime_receipt": build_mcp_runtime_smoke_receipt_preview()[
            "sample_receipt_template"
        ],
    }


def _none_executed(payload, keys):
    return all(not payload.get(key) for key in keys)


def build_mcp_runtime_promotion_preview(
    *,
    activation_evidence=None,
    runtime_receipt=None,
    phase=None,
):
    """審核 MCP runtime promotion package；不執行任何 runtime 動作。"""
    activation_evidence = activation_evidence or {}
    runtime_receipt = runtime_receipt or {}
    activation_payload_received = bool(activation_evidence)
    receipt_payload_received = bool(runtime_receipt)
    payload_received = activation_payload_received or receipt_payload_received

    activation_review = build_mcp_activation_evidence_preview(
        evidence=activation_evidence,
        phase=phase,
    )
    receipt_review = build_mcp_runtime_smoke_receipt_preview(
        receipt=runtime_receipt,
        phase=phase,
    )
    side_effect_free = bool(
        _none_executed(
            activation_review,
            (
                "api_executes_health_check",
                "api_executes_docker",
                "api_executes_ssh",
                "api_opens_database_connection",
                "api_writes_database",
                "api_uses_external_network",
                "database_session_created",
                "database_write_executed",
                "database_commit_executed",
                "external_network_executed",
                "scheduler_attached",
                "writes_executed",
                "would_write_database",
            ),
        )
        and _none_executed(
            receipt_review,
            (
                "api_executes_health_check",
                "api_executes_docker",
                "api_executes_ssh",
                "api_opens_database_connection",
                "api_writes_database",
                "api_uses_external_network",
                "database_session_created",
                "database_write_executed",
                "database_commit_executed",
                "external_network_executed",
                "scheduler_attached",
                "writes_executed",
                "would_write_database",
            ),
        )
    )

    gates = [
        {
            "key": "activation_evidence_payload_received",
            "passed": activation_payload_received,
            "label": "已提供 MCP activation evidence payload",
        },
        {
            "key": "activation_evidence_accepted",
            "passed": activation_review["activation_evidence_accepted"],
            "label": "MCP 啟用證據已通過",
        },
        {
            "key": "runtime_receipt_payload_received",
            "passed": receipt_payload_received,
            "label": "已提供 runtime smoke receipt payload",
        },
        {
            "key": "runtime_smoke_receipt_accepted",
            "passed": receipt_review["runtime_smoke_receipt_accepted"],
            "label": "runtime smoke 收據已通過",
        },
        {
            "key": "external_runtime_complete_by_receipts",
            "passed": bool(
                activation_review["external_mcp_runtime_evidence_complete"]
                and receipt_review["external_mcp_runtime_receipt_complete"]
            ),
            "label": "外部 MCP runtime 可由 evidence + receipt 共同驗收",
        },
        {
            "key": "internal_runtime_complete_by_receipts",
            "passed": bool(
                activation_review["internal_mcp_runtime_evidence_complete"]
                and receipt_review["internal_mcp_runtime_receipt_complete"]
            ),
            "label": "內部 MCP telemetry / contract 可由 evidence + receipt 共同驗收",
        },
        {
            "key": "completion_runtime_gap_closed_by_receipts",
            "passed": bool(
                activation_review["ready_for_runtime_promotion"]
                and receipt_review["ready_for_completion_runtime_promotion"]
            ),
            "label": "completion audit 的 runtime 缺口可由本 promotion package 補齊",
        },
        {
            "key": "manual_fetch_gate_ready_for_review",
            "passed": bool(
                activation_review["ready_for_fetch_gate_review"]
                and receipt_review["ready_for_manual_fetch_gate_review"]
            ),
            "label": "可進入人工 fetch gate review，但不可自動打開 fetch",
        },
        {
            "key": "promotion_payload_not_persisted",
            "passed": bool(
                not activation_review["payload_persisted"]
                and not activation_review["evidence_persisted"]
                and not receipt_review["payload_persisted"]
                and not receipt_review["receipt_persisted"]
            ),
            "label": "promotion package 與子 payload 均未保存",
        },
        {
            "key": "promotion_review_side_effect_free",
            "passed": side_effect_free,
            "label": "本審核不打 health、不開 DB、不抓外站、不掛 scheduler",
        },
    ]
    blocked_reasons = [
        gate["key"] for gate in gates
        if not gate["passed"]
    ]
    accepted = payload_received and not blocked_reasons

    return {
        "mode": (
            "mcp_runtime_promotion_review"
            if payload_received
            else "mcp_runtime_promotion_preview"
        ),
        "phase": phase,
        "promotion_payload_received": payload_received,
        "activation_evidence_payload_received": activation_payload_received,
        "runtime_receipt_payload_received": receipt_payload_received,
        "runtime_promotion_accepted": accepted,
        "ready_for_completion_runtime_promotion": accepted,
        "ready_for_manual_fetch_gate_review": accepted,
        "fetch_gate_still_requires_separate_review": True,
        "external_mcp_runtime_promoted_by_receipts": accepted,
        "internal_mcp_runtime_promoted_by_receipts": accepted,
        "gate_count": len(gates),
        "passed_gate_count": sum(1 for gate in gates if gate["passed"]),
        "blocked_reasons": blocked_reasons,
        "gates": gates,
        "activation_summary": {
            "accepted": activation_review["activation_evidence_accepted"],
            "passed_gate_count": activation_review["passed_gate_count"],
            "gate_count": activation_review["gate_count"],
            "blocked_reasons": activation_review["blocked_reasons"],
        },
        "runtime_receipt_summary": {
            "accepted": receipt_review["runtime_smoke_receipt_accepted"],
            "passed_gate_count": receipt_review["passed_gate_count"],
            "gate_count": receipt_review["gate_count"],
            "blocked_reasons": receipt_review["blocked_reasons"],
            "server_summary": receipt_review["server_summary"],
            "telemetry_summary": receipt_review["telemetry_summary"],
        },
        "mcp_activation_evidence": activation_review,
        "mcp_runtime_smoke_receipt": receipt_review,
        "sample_promotion_package": _sample_promotion_package(),
        "next_operator_steps": [
            "若 promotion 通過，回到 MCP 完整度稽核標記 runtime 缺口可由人工收據補齊",
            "人工 fetch gate 仍須另行審核，且只能針對公開頁面與限速策略",
            "正式 fetch / DB write / scheduler attach 仍需各自獨立 gate，不得由本 API 執行",
        ],
        "payload_persisted": False,
        "promotion_persisted": False,
        "api_executes_health_check": False,
        "api_executes_docker": False,
        "api_executes_ssh": False,
        "api_opens_database_connection": False,
        "api_writes_database": False,
        "api_uses_external_network": False,
        "database_session_created": False,
        "database_write_executed": False,
        "database_commit_executed": False,
        "external_network_executed": False,
        "scheduler_attached": False,
        "writes_executed": False,
        "would_write_database": False,
    }
