"""候選審核 queue AI summary Telegram dispatch report catalog record commit gate。

本模組只審核上一關 run receipt 是否足以進入 catalog record commit 收尾；
不讀 approval 或 Telegram token、不呼叫 LLM、不派送 Telegram、不開 DB、
不寫檔、不執行 CLI、不補寫 catalog record、不執行 commit、不更新
review_state、不掛 scheduler。
"""

from services.market_intel.candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_archive_summary import (
    SAFE_APPROVAL_ENV_VAR,
    SAFE_TOKEN_METADATA_KEYS,
    TARGET_COLUMN,
    TARGET_TABLE,
    _as_dict,
    _as_list,
    _contains_forbidden_token_key,
    _has_text,
    _safe_int,
    _safe_text,
    _strip_safe_token_boolean_keys,
)
from services.market_intel.candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_catalog_record_run_receipt import (
    FALSE_RESPONSE_KEYS as REPORT_CATALOG_RECORD_RUN_RECEIPT_FALSE_RESPONSE_KEYS,
)


REQUIRED_RUN_RECEIPT_BOUNDARIES = {
    "do_not_read_approval_token_from_report_catalog_record_run_receipt_api",
    "do_not_read_telegram_token_from_report_catalog_record_run_receipt_api",
    "do_not_call_llm_from_report_catalog_record_run_receipt",
    "do_not_generate_report_from_report_catalog_record_run_receipt_api",
    "do_not_write_report_catalog_record_run_receipt_artifact_from_api",
    "do_not_execute_catalog_record_cli_from_report_catalog_record_run_receipt_api",
    "do_not_write_report_catalog_record_from_report_catalog_record_run_receipt_api",
    "do_not_dispatch_telegram_from_report_catalog_record_run_receipt_api",
    "do_not_open_database_connection_from_report_catalog_record_run_receipt",
    "do_not_update_review_state_from_report_catalog_record_run_receipt",
    "do_not_attach_scheduler_from_report_catalog_record_run_receipt",
    "future_market_intel_report_catalog_record_commit_must_use_separate_gate",
}
FALSE_RESPONSE_KEYS = tuple(
    dict.fromkeys(
        REPORT_CATALOG_RECORD_RUN_RECEIPT_FALSE_RESPONSE_KEYS
        + (
            "telegram_dispatch_report_catalog_record_commit_gate_file_written",
            "report_catalog_record_commit_gate_file_written",
            "catalog_record_commit_gate_file_written",
            "telegram_dispatch_report_catalog_record_commit_file_written",
            "report_catalog_record_commit_file_written",
            "catalog_record_commit_file_written",
            "catalog_record_commit_executed",
            "catalog_record_closeout_gate_file_written",
        )
    )
)


def _run_receipt_summary(telegram_dispatch_report_catalog_record_run_receipt):
    receipt = _as_dict(telegram_dispatch_report_catalog_record_run_receipt)
    writer = _as_dict(
        receipt.get("telegram_dispatch_report_catalog_record_run_receipt_writer")
    )
    smoke = _as_dict(
        receipt.get("telegram_dispatch_report_catalog_record_run_receipt_postwrite_smoke")
    )
    promotion = _as_dict(receipt.get("promotion_gate"))
    sections = _as_list(
        receipt.get("telegram_dispatch_report_catalog_record_run_receipt_sections")
    )
    safe_boundaries = set(str(item) for item in _as_list(receipt.get("safe_boundaries")))
    missing_boundaries = sorted(REQUIRED_RUN_RECEIPT_BOUNDARIES - safe_boundaries)
    blocked_keys = [
        key
        for key in FALSE_RESPONSE_KEYS
        if bool(receipt.get(key))
    ]

    return {
        "provided": bool(receipt),
        "mode": receipt.get("mode"),
        "target_operation": receipt.get("target_operation"),
        "run_receipt_passed": bool(
            receipt.get("telegram_dispatch_report_catalog_record_run_receipt_passed")
            or receipt.get(
                "summary_persistence_telegram_dispatch_report_catalog_record_run_receipt_passed"
            )
            or receipt.get("report_catalog_record_run_receipt_passed")
        ),
        "ready_for_next_manual_phase": bool(receipt.get("ready_for_next_manual_phase")),
        "ready_for_market_intel_report_catalog_record_commit": bool(
            receipt.get("ready_for_market_intel_report_catalog_record_commit")
        ),
        "ready_for_market_intel_report_catalog_record_commit_gate": bool(
            receipt.get("ready_for_market_intel_report_catalog_record_commit_gate")
        ),
        "ready_for_market_intel_report_catalog_record_cli_run": bool(
            receipt.get("ready_for_market_intel_report_catalog_record_cli_run")
        ),
        "statement_count": _safe_int(receipt.get("statement_count")),
        "expected_summary_payload_hash": _safe_text(
            receipt.get("expected_summary_payload_hash"),
            80,
        ),
        "writer_mode": writer.get("mode"),
        "writer_catalog_record_written": bool(writer.get("catalog_record_written")),
        "writer_catalog_record_key": _safe_text(writer.get("catalog_record_key"), 240),
        "writer_target_table": _safe_text(writer.get("target_table"), 120),
        "writer_target_column": _safe_text(writer.get("target_column"), 120),
        "writer_record_family": _safe_text(writer.get("record_family"), 180),
        "writer_statement_count": _safe_int(writer.get("statement_count")),
        "writer_database_write_executed": bool(writer.get("database_write_executed")),
        "writer_database_commit_executed": bool(writer.get("database_commit_executed")),
        "writer_database_rollback_executed": bool(
            writer.get("database_rollback_executed")
        ),
        "writer_hash_match": bool(
            writer.get("summary_payload_hash_matches_expected")
        ),
        "writer_token_key_detected": bool(
            writer.get("approval_or_telegram_token_key_detected")
        ),
        "smoke_mode": smoke.get("mode"),
        "smoke_postwrite_smoke_passed": bool(smoke.get("postwrite_smoke_passed")),
        "smoke_read_only_query_executed": bool(
            smoke.get("read_only_query_executed")
        ),
        "smoke_catalog_record_found": bool(smoke.get("catalog_record_found")),
        "smoke_target_table": _safe_text(smoke.get("target_table"), 120),
        "smoke_target_column": _safe_text(smoke.get("target_column"), 120),
        "smoke_record_family": _safe_text(smoke.get("record_family"), 180),
        "smoke_catalog_record_key": _safe_text(smoke.get("catalog_record_key"), 240),
        "smoke_database_write_executed": bool(smoke.get("database_write_executed")),
        "smoke_database_commit_executed": bool(smoke.get("database_commit_executed")),
        "smoke_hash_match": bool(smoke.get("summary_payload_hash_matches_expected")),
        "smoke_token_key_detected": bool(
            smoke.get("approval_or_telegram_token_key_detected")
        ),
        "promotion_allowed": bool(promotion.get("allowed")),
        "promotion_next_manual_phase": promotion.get("next_manual_phase"),
        "promotion_commit_separate_gate": bool(
            promotion.get("report_catalog_record_commit_requires_separate_gate")
        ),
        "promotion_api_must_not_write_database": bool(
            promotion.get("api_must_not_write_database")
        ),
        "promotion_api_must_not_execute_cli": bool(
            promotion.get("api_must_not_execute_cli")
        ),
        "promotion_api_must_not_write_catalog_record": bool(
            promotion.get("api_must_not_write_catalog_record")
        ),
        "top_level_api_executes_cli": bool(receipt.get("api_executes_cli")),
        "top_level_api_writes_file": bool(receipt.get("api_writes_file")),
        "top_level_api_writes_database": bool(receipt.get("api_writes_database")),
        "top_level_database_write_executed": bool(
            receipt.get("database_write_executed")
        ),
        "top_level_catalog_record_written": bool(receipt.get("catalog_record_written")),
        "top_level_catalog_record_commit_executed": bool(
            receipt.get("catalog_record_commit_executed")
        ),
        "top_level_scheduler_attached": bool(receipt.get("scheduler_attached")),
        "blocked_response_keys_true": blocked_keys,
        "safe_boundaries_complete": not missing_boundaries,
        "missing_safe_boundaries": missing_boundaries,
        "section_keys": sorted(
            str(item.get("key"))
            for item in sections
            if isinstance(item, dict) and item.get("key")
        ),
        "forbidden_token_key_detected": _contains_forbidden_token_key(
            _strip_safe_token_boolean_keys(receipt)
        ),
    }


def _commit_payload(operator_evidence, report_catalog_record_commit):
    operator_evidence = _as_dict(operator_evidence)
    embedded = _as_dict(
        operator_evidence.get("market_intel_report_catalog_record_commit")
        or operator_evidence.get("telegram_dispatch_report_catalog_record_commit")
        or operator_evidence.get("report_catalog_record_commit")
        or operator_evidence.get("catalog_record_commit")
    )
    return _as_dict(report_catalog_record_commit) or embedded


def _operator_summary(operator_evidence, report_catalog_record_commit):
    operator_evidence = _as_dict(operator_evidence)
    commit_payload = _commit_payload(operator_evidence, report_catalog_record_commit)
    return {
        "provided_keys": sorted(operator_evidence.keys()),
        "commit_payload_provided": bool(commit_payload),
        "report_catalog_record_commit_artifact_path": _safe_text(
            operator_evidence.get("report_catalog_record_commit_artifact_path")
            or operator_evidence.get(
                "telegram_dispatch_report_catalog_record_commit_artifact_path"
            )
            or operator_evidence.get(
                "market_intel_report_catalog_record_commit_artifact_path"
            )
            or commit_payload.get("artifact_path")
            or commit_payload.get("commit_artifact_path")
        ),
        "report_catalog_record_run_receipt_artifact_path_recorded": _has_text(
            operator_evidence.get("report_catalog_record_run_receipt_artifact_path")
            or operator_evidence.get(
                "telegram_dispatch_report_catalog_record_run_receipt_artifact_path"
            )
            or commit_payload.get("run_receipt_artifact_path")
        ),
        "catalog_record_writer_output_artifact_path_recorded": _has_text(
            operator_evidence.get("catalog_record_writer_output_artifact_path")
            or operator_evidence.get("report_catalog_record_writer_output_artifact_path")
            or operator_evidence.get("writer_output_json_path")
            or commit_payload.get("writer_output_artifact_path")
        ),
        "catalog_record_postwrite_smoke_artifact_path_recorded": _has_text(
            operator_evidence.get("catalog_record_postwrite_smoke_artifact_path")
            or operator_evidence.get("report_catalog_record_postwrite_smoke_artifact_path")
            or operator_evidence.get("postwrite_smoke_json_path")
            or commit_payload.get("postwrite_smoke_artifact_path")
        ),
        "catalog_record_backup_artifact_path_recorded": _has_text(
            operator_evidence.get("catalog_record_backup_artifact_path")
            or operator_evidence.get("report_catalog_backup_artifact_path")
            or operator_evidence.get("metadata_json_backup_artifact_path")
            or commit_payload.get("backup_artifact_path")
        ),
        "operator_confirmed_report_catalog_record_commit_gate": bool(
            operator_evidence.get("operator_confirmed_report_catalog_record_commit_gate")
            or operator_evidence.get(
                "operator_confirmed_market_intel_report_catalog_record_commit"
            )
            or commit_payload.get("operator_confirmed_report_catalog_record_commit_gate")
        ),
        "operator_confirmed_catalog_record_run_receipt_reviewed": bool(
            operator_evidence.get(
                "operator_confirmed_catalog_record_run_receipt_reviewed"
            )
            or operator_evidence.get(
                "operator_confirmed_report_catalog_record_run_receipt"
            )
            or commit_payload.get("operator_confirmed_catalog_record_run_receipt_reviewed")
        ),
        "operator_confirmed_catalog_record_db_commit_observed": bool(
            operator_evidence.get(
                "operator_confirmed_catalog_record_db_commit_observed"
            )
            or operator_evidence.get(
                "operator_confirmed_database_commit_in_run_receipt"
            )
            or commit_payload.get(
                "operator_confirmed_catalog_record_db_commit_observed"
            )
        ),
        "operator_confirmed_catalog_record_postwrite_smoke_passed": bool(
            operator_evidence.get(
                "operator_confirmed_catalog_record_postwrite_smoke_passed"
            )
            or operator_evidence.get("operator_confirmed_postwrite_smoke_passed")
            or commit_payload.get(
                "operator_confirmed_catalog_record_postwrite_smoke_passed"
            )
        ),
        "operator_confirmed_catalog_record_no_followup_db_write_required": bool(
            operator_evidence.get(
                "operator_confirmed_catalog_record_no_followup_db_write_required"
            )
            or operator_evidence.get("operator_confirmed_no_followup_db_write_required")
            or commit_payload.get(
                "operator_confirmed_catalog_record_no_followup_db_write_required"
            )
        ),
        "operator_confirmed_catalog_record_closeout_requires_separate_gate": bool(
            operator_evidence.get(
                "operator_confirmed_catalog_record_closeout_requires_separate_gate"
            )
            or operator_evidence.get(
                "operator_confirmed_report_catalog_record_closeout_requires_separate_gate"
            )
            or commit_payload.get(
                "operator_confirmed_catalog_record_closeout_requires_separate_gate"
            )
        ),
        "operator_confirmed_no_token_in_report_catalog_record_commit": bool(
            operator_evidence.get(
                "operator_confirmed_no_token_in_report_catalog_record_commit"
            )
            or operator_evidence.get("operator_confirmed_no_token_in_artifacts")
            or commit_payload.get(
                "operator_confirmed_no_token_in_report_catalog_record_commit"
            )
        ),
        "operator_confirmed_no_api_file_write": bool(
            operator_evidence.get("operator_confirmed_no_api_file_write")
            or commit_payload.get("operator_confirmed_no_api_file_write")
        ),
        "operator_confirmed_no_api_cli_execution": bool(
            operator_evidence.get("operator_confirmed_no_api_cli_execution")
            or operator_evidence.get("operator_confirmed_no_api_execute_cli")
            or commit_payload.get("operator_confirmed_no_api_cli_execution")
        ),
        "operator_confirmed_no_api_catalog_record_write": bool(
            operator_evidence.get("operator_confirmed_no_api_catalog_record_write")
            or operator_evidence.get("operator_confirmed_no_api_db_write")
            or commit_payload.get("operator_confirmed_no_api_catalog_record_write")
        ),
        "operator_confirmed_no_api_telegram_dispatch": bool(
            operator_evidence.get("operator_confirmed_no_api_telegram_dispatch")
            or commit_payload.get("operator_confirmed_no_api_telegram_dispatch")
        ),
        "operator_confirmed_no_api_db_write": bool(
            operator_evidence.get("operator_confirmed_no_api_db_write")
            or commit_payload.get("operator_confirmed_no_api_db_write")
        ),
        "operator_confirmed_no_llm_call": bool(
            operator_evidence.get("operator_confirmed_no_llm_call")
            or commit_payload.get("operator_confirmed_no_llm_call")
        ),
        "operator_confirmed_no_scheduler_attach": bool(
            operator_evidence.get("operator_confirmed_no_scheduler_attach")
            or commit_payload.get("operator_confirmed_no_scheduler_attach")
        ),
        "commit_notes_recorded": _has_text(
            operator_evidence.get("report_catalog_record_commit_notes")
            or operator_evidence.get("catalog_record_commit_notes")
            or commit_payload.get("notes")
        ),
        "safe_token_metadata_only": all(
            key in SAFE_TOKEN_METADATA_KEYS or key == "approval_env_var"
            for key in _strip_safe_token_boolean_keys(operator_evidence)
            if "token" in str(key).lower() or str(key).lower() == "approval_env_var"
        )
        and operator_evidence.get("approval_env_var", SAFE_APPROVAL_ENV_VAR)
        == SAFE_APPROVAL_ENV_VAR,
        "forbidden_token_submitted_to_api": _contains_forbidden_token_key(
            operator_evidence
        )
        or _contains_forbidden_token_key(commit_payload),
    }


def _commit_sections(run_receipt, operator):
    return [
        {
            "key": "catalog_record_commit_identity",
            "title": "Catalog record commit identity",
            "facts": [
                f"family={run_receipt['writer_record_family'] or 'missing'}",
                f"record_key={run_receipt['writer_catalog_record_key'] or 'missing'}",
                f"statement_count={run_receipt['writer_statement_count']}",
            ],
        },
        {
            "key": "catalog_record_commit_receipt",
            "title": "Catalog record commit receipt",
            "facts": [
                f"run_receipt_passed={run_receipt['run_receipt_passed']}",
                f"writer_committed={run_receipt['writer_database_commit_executed']}",
                f"smoke_passed={run_receipt['smoke_postwrite_smoke_passed']}",
            ],
        },
        {
            "key": "catalog_record_commit_operator",
            "title": "Catalog record commit operator confirmations",
            "facts": [
                f"commit_gate={operator['operator_confirmed_report_catalog_record_commit_gate']}",
                f"db_commit_observed={operator['operator_confirmed_catalog_record_db_commit_observed']}",
                f"closeout_gate={operator['operator_confirmed_catalog_record_closeout_requires_separate_gate']}",
            ],
        },
        {
            "key": "catalog_record_commit_safety",
            "title": "Catalog record commit safety",
            "facts": [
                "api_cli_executed=false",
                "api_database_write_executed=false",
                "catalog_record_commit_executed=false",
                "scheduler_attached=false",
            ],
        },
    ]


def _commit_gates(run_receipt, operator, apply_real_write):
    return [
        {
            "key": "report_catalog_record_run_receipt_passed",
            "label": "上一關 report catalog record run receipt 已通過",
            "passed": bool(
                run_receipt["provided"]
                and run_receipt["mode"]
                == "candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_catalog_record_run_receipt_preview"
                and run_receipt["run_receipt_passed"]
                and run_receipt["ready_for_market_intel_report_catalog_record_commit"]
                and run_receipt["ready_for_market_intel_report_catalog_record_commit_gate"]
            ),
        },
        {
            "key": "report_catalog_record_run_receipt_writer_committed",
            "label": "外部 CLI writer 已寫入 catalog record 並完成 DB commit",
            "passed": bool(
                run_receipt["writer_catalog_record_written"]
                and run_receipt["writer_target_table"] == TARGET_TABLE
                and run_receipt["writer_target_column"] == TARGET_COLUMN
                and run_receipt["writer_statement_count"] > 0
                and run_receipt["writer_database_write_executed"]
                and run_receipt["writer_database_commit_executed"]
                and not run_receipt["writer_database_rollback_executed"]
                and run_receipt["writer_hash_match"]
            ),
        },
        {
            "key": "report_catalog_record_run_receipt_postwrite_smoke_passed",
            "label": "post-write smoke 以只讀查詢確認 catalog record 存在且 hash 相符",
            "passed": bool(
                run_receipt["smoke_postwrite_smoke_passed"]
                and run_receipt["smoke_read_only_query_executed"]
                and run_receipt["smoke_catalog_record_found"]
                and run_receipt["smoke_target_table"] == TARGET_TABLE
                and run_receipt["smoke_target_column"] == TARGET_COLUMN
                and not run_receipt["smoke_database_write_executed"]
                and not run_receipt["smoke_database_commit_executed"]
                and run_receipt["smoke_hash_match"]
            ),
        },
        {
            "key": "report_catalog_record_commit_promotion_gate",
            "label": "run receipt promotion gate 僅放行到 catalog record commit 且要求獨立 gate",
            "passed": bool(
                run_receipt["promotion_allowed"]
                and run_receipt["promotion_next_manual_phase"]
                == "market_intel_report_catalog_record_commit"
                and run_receipt["promotion_commit_separate_gate"]
                and run_receipt["promotion_api_must_not_write_database"]
                and run_receipt["promotion_api_must_not_execute_cli"]
                and run_receipt["promotion_api_must_not_write_catalog_record"]
            ),
        },
        {
            "key": "report_catalog_record_run_receipt_api_side_effects_blocked",
            "label": "上一關 run receipt top-level API 沒有執行 CLI、寫檔、寫 DB、commit 或掛 scheduler",
            "passed": bool(
                not run_receipt["top_level_api_executes_cli"]
                and not run_receipt["top_level_api_writes_file"]
                and not run_receipt["top_level_api_writes_database"]
                and not run_receipt["top_level_database_write_executed"]
                and not run_receipt["top_level_catalog_record_written"]
                and not run_receipt["top_level_catalog_record_commit_executed"]
                and not run_receipt["top_level_scheduler_attached"]
                and not run_receipt["blocked_response_keys_true"]
            ),
        },
        {
            "key": "report_catalog_record_run_receipt_safe_boundaries_complete",
            "label": "上一關 run receipt safe boundaries 完整且未夾帶 token key",
            "passed": bool(
                run_receipt["safe_boundaries_complete"]
                and not run_receipt["forbidden_token_key_detected"]
                and not run_receipt["writer_token_key_detected"]
                and not run_receipt["smoke_token_key_detected"]
            ),
        },
        {
            "key": "report_catalog_record_commit_operator_confirmed",
            "label": "操作員確認 commit gate、run receipt、DB commit、post-write smoke、備份與 closeout separate gate",
            "passed": bool(
                operator["report_catalog_record_commit_artifact_path"]
                and operator[
                    "report_catalog_record_run_receipt_artifact_path_recorded"
                ]
                and operator["catalog_record_writer_output_artifact_path_recorded"]
                and operator["catalog_record_postwrite_smoke_artifact_path_recorded"]
                and operator["catalog_record_backup_artifact_path_recorded"]
                and operator["operator_confirmed_report_catalog_record_commit_gate"]
                and operator["operator_confirmed_catalog_record_run_receipt_reviewed"]
                and operator["operator_confirmed_catalog_record_db_commit_observed"]
                and operator[
                    "operator_confirmed_catalog_record_postwrite_smoke_passed"
                ]
                and operator[
                    "operator_confirmed_catalog_record_no_followup_db_write_required"
                ]
                and operator[
                    "operator_confirmed_catalog_record_closeout_requires_separate_gate"
                ]
            ),
        },
        {
            "key": "report_catalog_record_commit_runtime_boundaries_confirmed",
            "label": "操作員確認本 API 不寫檔、不執行 CLI、不寫 DB、不派送 Telegram、不呼叫 LLM、不掛 scheduler",
            "passed": bool(
                operator["operator_confirmed_no_token_in_report_catalog_record_commit"]
                and operator["operator_confirmed_no_api_file_write"]
                and operator["operator_confirmed_no_api_cli_execution"]
                and operator["operator_confirmed_no_api_catalog_record_write"]
                and operator["operator_confirmed_no_api_telegram_dispatch"]
                and operator["operator_confirmed_no_api_db_write"]
                and operator["operator_confirmed_no_llm_call"]
                and operator["operator_confirmed_no_scheduler_attach"]
            ),
        },
        {
            "key": "report_catalog_record_commit_no_token_submitted_to_api",
            "label": "commit gate payload 不得包含 approval 或 Telegram token key",
            "passed": not operator["forbidden_token_submitted_to_api"],
        },
        {
            "key": "report_catalog_record_commit_apply_real_write_not_requested_from_api",
            "label": "API/UI report catalog record commit gate 不接受 apply_real_write",
            "passed": not apply_real_write,
        },
    ]


def build_candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_catalog_record_commit(
    *,
    telegram_dispatch_report_catalog_record_run_receipt,
    report_catalog_record_commit=None,
    operator_evidence=None,
    execute_requested=False,
    apply_real_write=False,
):
    """建立 Telegram dispatch report catalog record commit gate；不執行副作用。"""
    run_receipt = _run_receipt_summary(
        telegram_dispatch_report_catalog_record_run_receipt
    )
    operator = _operator_summary(operator_evidence, report_catalog_record_commit)
    sections = _commit_sections(run_receipt, operator)
    gates = _commit_gates(run_receipt, operator, bool(apply_real_write))
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    commit_passed = bool(not blocked_reasons)

    return {
        "mode": "candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_catalog_record_commit_preview",
        "target_table": TARGET_TABLE,
        "target_column": TARGET_COLUMN,
        "target_json_path": [
            "market_intel_ai_summary",
            "telegram_dispatch_report_catalog_record_commit",
        ],
        "target_operation": "review_manual_market_intel_report_catalog_record_commit",
        "execute_requested": bool(execute_requested),
        "apply_real_write_requested": bool(apply_real_write),
        "report_catalog_record_commit_reviewed": True,
        "telegram_dispatch_report_catalog_record_commit_passed": commit_passed,
        "summary_persistence_telegram_dispatch_report_catalog_record_commit_passed": commit_passed,
        "report_catalog_record_commit_passed": commit_passed,
        "ready_for_next_manual_phase": commit_passed,
        "ready_for_market_intel_report_catalog_record_closeout": commit_passed,
        "ready_for_market_intel_report_catalog_record_commit": False,
        "ready_for_market_intel_report_catalog_record_cli_run": False,
        "ready_for_cli_operator_run": False,
        "ready_for_real_write": False,
        "ready_for_report_generation": False,
        "ready_for_telegram_dispatch": False,
        "ready_for_api_database_write": False,
        "ready_for_scheduler_attach": False,
        "ready_for_llm_call": False,
        "api_executes_cli": False,
        "api_executes_llm": False,
        "api_dispatches_telegram": False,
        "api_reads_approval_token": False,
        "api_writes_file": False,
        "api_writes_database": False,
        "api_updates_review_state": False,
        **{key: False for key in FALSE_RESPONSE_KEYS},
        "statement_count": run_receipt["writer_statement_count"]
        or run_receipt["statement_count"],
        "expected_summary_payload_hash": run_receipt[
            "expected_summary_payload_hash"
        ],
        "blocked_reasons": blocked_reasons,
        "gates": gates,
        "telegram_dispatch_report_catalog_record_run_receipt": run_receipt,
        "telegram_dispatch_report_catalog_record_commit_sections": sections,
        "operator_telegram_dispatch_report_catalog_record_commit": operator,
        "promotion_gate": {
            "allowed": commit_passed,
            "next_manual_phase": "market_intel_report_catalog_record_closeout",
            "requires_real_db_write": False,
            "requires_cli_run": False,
            "requires_scheduler_attach": False,
            "requires_operator_approval": True,
            "requires_postwrite_smoke": False,
            "api_must_not_generate_report": True,
            "api_must_not_write_file": True,
            "api_must_not_execute_cli": True,
            "api_must_not_write_catalog_record": True,
            "api_must_not_write_database": True,
            "api_must_not_dispatch_telegram": True,
            "api_must_not_commit_catalog_record": True,
            "report_catalog_record_closeout_requires_separate_gate": True,
        },
        "next_operator_steps": [
            "保存 report catalog record commit gate artifact path",
            "人工確認 run receipt 內的 DB commit 與 post-write smoke 已成立",
            "只在 commit gate 通過後進入 report catalog record closeout gate",
            "不得從 API/UI 補寫 catalog record、重跑 CLI、commit 或掛 scheduler",
        ],
        "safe_boundaries": [
            "do_not_read_approval_token_from_report_catalog_record_commit_api",
            "do_not_read_telegram_token_from_report_catalog_record_commit_api",
            "do_not_call_llm_from_report_catalog_record_commit",
            "do_not_generate_report_from_report_catalog_record_commit_api",
            "do_not_write_report_catalog_record_commit_artifact_from_api",
            "do_not_execute_catalog_record_cli_from_report_catalog_record_commit_api",
            "do_not_write_report_catalog_record_from_report_catalog_record_commit_api",
            "do_not_commit_catalog_record_from_report_catalog_record_commit_api",
            "do_not_dispatch_telegram_from_report_catalog_record_commit_api",
            "do_not_open_database_connection_from_report_catalog_record_commit",
            "do_not_update_review_state_from_report_catalog_record_commit",
            "do_not_attach_scheduler_from_report_catalog_record_commit",
            "future_market_intel_report_catalog_record_closeout_must_use_separate_gate",
            "report_catalog_record_commit_preview_only",
            "no_remove_orphans",
            "no_momo_db_lifecycle_change",
        ],
    }
