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

本模組只審核上一關 catalog record commit gate 是否足以收尾；
不讀 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_commit import (
    FALSE_RESPONSE_KEYS as REPORT_CATALOG_RECORD_COMMIT_FALSE_RESPONSE_KEYS,
)


REQUIRED_COMMIT_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",
}
FALSE_RESPONSE_KEYS = tuple(
    dict.fromkeys(
        REPORT_CATALOG_RECORD_COMMIT_FALSE_RESPONSE_KEYS
        + (
            "telegram_dispatch_report_catalog_record_closeout_gate_file_written",
            "report_catalog_record_closeout_gate_file_written",
            "catalog_record_closeout_gate_file_written",
            "telegram_dispatch_report_catalog_record_closeout_file_written",
            "report_catalog_record_closeout_file_written",
            "catalog_record_closeout_file_written",
            "catalog_record_closeout_executed",
            "catalog_record_archive_gate_file_written",
        )
    )
)


def _commit_summary(telegram_dispatch_report_catalog_record_commit):
    commit = _as_dict(telegram_dispatch_report_catalog_record_commit)
    run_receipt = _as_dict(
        commit.get("telegram_dispatch_report_catalog_record_run_receipt")
    )
    operator = _as_dict(
        commit.get("operator_telegram_dispatch_report_catalog_record_commit")
    )
    promotion = _as_dict(commit.get("promotion_gate"))
    sections = _as_list(
        commit.get("telegram_dispatch_report_catalog_record_commit_sections")
    )
    safe_boundaries = set(str(item) for item in _as_list(commit.get("safe_boundaries")))
    missing_boundaries = sorted(REQUIRED_COMMIT_BOUNDARIES - safe_boundaries)
    blocked_keys = [key for key in FALSE_RESPONSE_KEYS if bool(commit.get(key))]

    return {
        "provided": bool(commit),
        "mode": commit.get("mode"),
        "target_operation": commit.get("target_operation"),
        "commit_passed": bool(
            commit.get("telegram_dispatch_report_catalog_record_commit_passed")
            or commit.get(
                "summary_persistence_telegram_dispatch_report_catalog_record_commit_passed"
            )
            or commit.get("report_catalog_record_commit_passed")
        ),
        "ready_for_next_manual_phase": bool(commit.get("ready_for_next_manual_phase")),
        "ready_for_market_intel_report_catalog_record_closeout": bool(
            commit.get("ready_for_market_intel_report_catalog_record_closeout")
        ),
        "ready_for_market_intel_report_catalog_record_commit": bool(
            commit.get("ready_for_market_intel_report_catalog_record_commit")
        ),
        "ready_for_market_intel_report_catalog_record_cli_run": bool(
            commit.get("ready_for_market_intel_report_catalog_record_cli_run")
        ),
        "statement_count": _safe_int(commit.get("statement_count")),
        "expected_summary_payload_hash": _safe_text(
            commit.get("expected_summary_payload_hash"),
            80,
        ),
        "run_receipt_mode": run_receipt.get("mode"),
        "run_receipt_passed": bool(run_receipt.get("run_receipt_passed")),
        "writer_catalog_record_key": _safe_text(
            run_receipt.get("writer_catalog_record_key"),
            240,
        ),
        "writer_target_table": _safe_text(run_receipt.get("writer_target_table"), 120),
        "writer_target_column": _safe_text(
            run_receipt.get("writer_target_column"),
            120,
        ),
        "writer_record_family": _safe_text(
            run_receipt.get("writer_record_family"),
            180,
        ),
        "writer_statement_count": _safe_int(
            run_receipt.get("writer_statement_count")
        ),
        "writer_database_commit_executed": bool(
            run_receipt.get("writer_database_commit_executed")
        ),
        "writer_hash_match": bool(run_receipt.get("writer_hash_match")),
        "smoke_postwrite_smoke_passed": bool(
            run_receipt.get("smoke_postwrite_smoke_passed")
        ),
        "smoke_read_only_query_executed": bool(
            run_receipt.get("smoke_read_only_query_executed")
        ),
        "smoke_hash_match": bool(run_receipt.get("smoke_hash_match")),
        "operator_commit_gate": bool(
            operator.get("operator_confirmed_report_catalog_record_commit_gate")
        ),
        "operator_run_receipt_reviewed": bool(
            operator.get("operator_confirmed_catalog_record_run_receipt_reviewed")
        ),
        "operator_db_commit_observed": bool(
            operator.get("operator_confirmed_catalog_record_db_commit_observed")
        ),
        "operator_postwrite_smoke_passed": bool(
            operator.get("operator_confirmed_catalog_record_postwrite_smoke_passed")
        ),
        "operator_no_followup_db_write_required": bool(
            operator.get(
                "operator_confirmed_catalog_record_no_followup_db_write_required"
            )
        ),
        "operator_closeout_requires_separate_gate": bool(
            operator.get(
                "operator_confirmed_catalog_record_closeout_requires_separate_gate"
            )
        ),
        "promotion_allowed": bool(promotion.get("allowed")),
        "promotion_next_manual_phase": promotion.get("next_manual_phase"),
        "promotion_closeout_separate_gate": bool(
            promotion.get("report_catalog_record_closeout_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")
        ),
        "promotion_api_must_not_commit_catalog_record": bool(
            promotion.get("api_must_not_commit_catalog_record")
        ),
        "promotion_api_must_not_dispatch_telegram": bool(
            promotion.get("api_must_not_dispatch_telegram")
        ),
        "top_level_api_executes_cli": bool(commit.get("api_executes_cli")),
        "top_level_api_writes_file": bool(commit.get("api_writes_file")),
        "top_level_api_writes_database": bool(commit.get("api_writes_database")),
        "top_level_api_dispatches_telegram": bool(
            commit.get("api_dispatches_telegram")
        ),
        "top_level_database_write_executed": bool(
            commit.get("database_write_executed")
        ),
        "top_level_catalog_record_written": bool(commit.get("catalog_record_written")),
        "top_level_catalog_record_commit_executed": bool(
            commit.get("catalog_record_commit_executed")
        ),
        "top_level_scheduler_attached": bool(commit.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(commit)
        ),
    }


def _closeout_payload(operator_evidence, report_catalog_record_closeout):
    operator_evidence = _as_dict(operator_evidence)
    embedded = _as_dict(
        operator_evidence.get("market_intel_report_catalog_record_closeout")
        or operator_evidence.get("telegram_dispatch_report_catalog_record_closeout")
        or operator_evidence.get("report_catalog_record_closeout")
        or operator_evidence.get("catalog_record_closeout")
    )
    return _as_dict(report_catalog_record_closeout) or embedded


def _operator_summary(operator_evidence, report_catalog_record_closeout):
    operator_evidence = _as_dict(operator_evidence)
    closeout_payload = _closeout_payload(
        operator_evidence,
        report_catalog_record_closeout,
    )
    return {
        "provided_keys": sorted(operator_evidence.keys()),
        "closeout_payload_provided": bool(closeout_payload),
        "report_catalog_record_closeout_artifact_path": _safe_text(
            operator_evidence.get("report_catalog_record_closeout_artifact_path")
            or operator_evidence.get(
                "telegram_dispatch_report_catalog_record_closeout_artifact_path"
            )
            or operator_evidence.get(
                "market_intel_report_catalog_record_closeout_artifact_path"
            )
            or closeout_payload.get("artifact_path")
            or closeout_payload.get("closeout_artifact_path")
        ),
        "report_catalog_record_commit_artifact_path_recorded": _has_text(
            operator_evidence.get("report_catalog_record_commit_artifact_path")
            or operator_evidence.get(
                "telegram_dispatch_report_catalog_record_commit_artifact_path"
            )
            or closeout_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 closeout_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 closeout_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 closeout_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 closeout_payload.get("backup_artifact_path")
        ),
        "operator_confirmed_report_catalog_record_closeout_gate": bool(
            operator_evidence.get("operator_confirmed_report_catalog_record_closeout_gate")
            or operator_evidence.get(
                "operator_confirmed_market_intel_report_catalog_record_closeout"
            )
            or closeout_payload.get(
                "operator_confirmed_report_catalog_record_closeout_gate"
            )
        ),
        "operator_confirmed_report_catalog_record_commit_reviewed": bool(
            operator_evidence.get(
                "operator_confirmed_report_catalog_record_commit_reviewed"
            )
            or operator_evidence.get(
                "operator_confirmed_catalog_record_commit_reviewed"
            )
            or closeout_payload.get(
                "operator_confirmed_report_catalog_record_commit_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 closeout_payload.get(
                "operator_confirmed_catalog_record_db_commit_observed"
            )
        ),
        "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 closeout_payload.get(
                "operator_confirmed_catalog_record_no_followup_db_write_required"
            )
        ),
        "operator_confirmed_catalog_record_closeout_summary_ready": bool(
            operator_evidence.get(
                "operator_confirmed_catalog_record_closeout_summary_ready"
            )
            or operator_evidence.get(
                "operator_confirmed_report_catalog_record_closeout_summary_ready"
            )
            or closeout_payload.get(
                "operator_confirmed_catalog_record_closeout_summary_ready"
            )
        ),
        "operator_confirmed_catalog_record_archive_requires_separate_gate": bool(
            operator_evidence.get(
                "operator_confirmed_catalog_record_archive_requires_separate_gate"
            )
            or operator_evidence.get(
                "operator_confirmed_report_catalog_record_archive_requires_separate_gate"
            )
            or closeout_payload.get(
                "operator_confirmed_catalog_record_archive_requires_separate_gate"
            )
        ),
        "operator_confirmed_no_token_in_report_catalog_record_closeout": bool(
            operator_evidence.get(
                "operator_confirmed_no_token_in_report_catalog_record_closeout"
            )
            or operator_evidence.get("operator_confirmed_no_token_in_artifacts")
            or closeout_payload.get(
                "operator_confirmed_no_token_in_report_catalog_record_closeout"
            )
        ),
        "operator_confirmed_no_api_file_write": bool(
            operator_evidence.get("operator_confirmed_no_api_file_write")
            or closeout_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 closeout_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 closeout_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 closeout_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 closeout_payload.get("operator_confirmed_no_api_db_write")
        ),
        "operator_confirmed_no_llm_call": bool(
            operator_evidence.get("operator_confirmed_no_llm_call")
            or closeout_payload.get("operator_confirmed_no_llm_call")
        ),
        "operator_confirmed_no_scheduler_attach": bool(
            operator_evidence.get("operator_confirmed_no_scheduler_attach")
            or closeout_payload.get("operator_confirmed_no_scheduler_attach")
        ),
        "closeout_notes_recorded": _has_text(
            operator_evidence.get("report_catalog_record_closeout_notes")
            or operator_evidence.get("catalog_record_closeout_notes")
            or closeout_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(closeout_payload),
    }


def _closeout_sections(commit, operator):
    return [
        {
            "key": "catalog_record_closeout_identity",
            "title": "Catalog record closeout identity",
            "facts": [
                f"family={commit['writer_record_family'] or 'missing'}",
                f"record_key={commit['writer_catalog_record_key'] or 'missing'}",
                f"statement_count={commit['writer_statement_count']}",
            ],
        },
        {
            "key": "catalog_record_closeout_commit",
            "title": "Catalog record closeout commit review",
            "facts": [
                f"commit_passed={commit['commit_passed']}",
                f"writer_committed={commit['writer_database_commit_executed']}",
                f"smoke_passed={commit['smoke_postwrite_smoke_passed']}",
            ],
        },
        {
            "key": "catalog_record_closeout_operator",
            "title": "Catalog record closeout operator confirmations",
            "facts": [
                f"closeout_gate={operator['operator_confirmed_report_catalog_record_closeout_gate']}",
                f"commit_reviewed={operator['operator_confirmed_report_catalog_record_commit_reviewed']}",
                f"archive_gate={operator['operator_confirmed_catalog_record_archive_requires_separate_gate']}",
            ],
        },
        {
            "key": "catalog_record_closeout_safety",
            "title": "Catalog record closeout safety",
            "facts": [
                "api_cli_executed=false",
                "api_database_write_executed=false",
                "catalog_record_closeout_executed=false",
                "scheduler_attached=false",
            ],
        },
    ]


def _closeout_gates(commit, operator, apply_real_write):
    return [
        {
            "key": "report_catalog_record_commit_passed",
            "label": "上一關 report catalog record commit gate 已通過",
            "passed": bool(
                commit["provided"]
                and commit["mode"]
                == "candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_catalog_record_commit_preview"
                and commit["commit_passed"]
                and commit["ready_for_next_manual_phase"]
                and commit["ready_for_market_intel_report_catalog_record_closeout"]
            ),
        },
        {
            "key": "report_catalog_record_commit_catalog_record_evidence_retained",
            "label": "commit payload 保留 catalog record identity、DB commit 與 post-write smoke 證據",
            "passed": bool(
                commit["writer_catalog_record_key"]
                and commit["writer_target_table"] == TARGET_TABLE
                and commit["writer_target_column"] == TARGET_COLUMN
                and commit["writer_statement_count"] > 0
                and commit["writer_database_commit_executed"]
                and commit["writer_hash_match"]
                and commit["smoke_read_only_query_executed"]
                and commit["smoke_postwrite_smoke_passed"]
                and commit["smoke_hash_match"]
            ),
        },
        {
            "key": "report_catalog_record_commit_operator_evidence_retained",
            "label": "commit payload 保留操作員 commit、run receipt、DB commit、post-write smoke 與 closeout separate gate 確認",
            "passed": bool(
                commit["operator_commit_gate"]
                and commit["operator_run_receipt_reviewed"]
                and commit["operator_db_commit_observed"]
                and commit["operator_postwrite_smoke_passed"]
                and commit["operator_no_followup_db_write_required"]
                and commit["operator_closeout_requires_separate_gate"]
            ),
        },
        {
            "key": "report_catalog_record_commit_promotion_gate",
            "label": "commit promotion gate 僅放行到 catalog record closeout 且要求獨立 gate",
            "passed": bool(
                commit["promotion_allowed"]
                and commit["promotion_next_manual_phase"]
                == "market_intel_report_catalog_record_closeout"
                and commit["promotion_closeout_separate_gate"]
                and commit["promotion_api_must_not_write_database"]
                and commit["promotion_api_must_not_execute_cli"]
                and commit["promotion_api_must_not_write_catalog_record"]
                and commit["promotion_api_must_not_commit_catalog_record"]
                and commit["promotion_api_must_not_dispatch_telegram"]
            ),
        },
        {
            "key": "report_catalog_record_commit_api_side_effects_blocked",
            "label": "上一關 commit top-level API 沒有執行 CLI、寫檔、寫 DB、commit、派 Telegram 或掛 scheduler",
            "passed": bool(
                not commit["top_level_api_executes_cli"]
                and not commit["top_level_api_writes_file"]
                and not commit["top_level_api_writes_database"]
                and not commit["top_level_api_dispatches_telegram"]
                and not commit["top_level_database_write_executed"]
                and not commit["top_level_catalog_record_written"]
                and not commit["top_level_catalog_record_commit_executed"]
                and not commit["top_level_scheduler_attached"]
                and not commit["blocked_response_keys_true"]
            ),
        },
        {
            "key": "report_catalog_record_commit_safe_boundaries_complete",
            "label": "上一關 commit safe boundaries 完整且未夾帶 token key",
            "passed": bool(
                commit["safe_boundaries_complete"]
                and not commit["forbidden_token_key_detected"]
            ),
        },
        {
            "key": "report_catalog_record_closeout_operator_confirmed",
            "label": "操作員確認 closeout gate、commit artifact、run receipt、備份與 archive separate gate",
            "passed": bool(
                operator["report_catalog_record_closeout_artifact_path"]
                and operator["report_catalog_record_commit_artifact_path_recorded"]
                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_closeout_gate"]
                and operator[
                    "operator_confirmed_report_catalog_record_commit_reviewed"
                ]
                and operator["operator_confirmed_catalog_record_db_commit_observed"]
                and operator[
                    "operator_confirmed_catalog_record_no_followup_db_write_required"
                ]
                and operator[
                    "operator_confirmed_catalog_record_closeout_summary_ready"
                ]
                and operator[
                    "operator_confirmed_catalog_record_archive_requires_separate_gate"
                ]
            ),
        },
        {
            "key": "report_catalog_record_closeout_runtime_boundaries_confirmed",
            "label": "操作員確認本 API 不寫檔、不執行 CLI、不寫 DB、不派送 Telegram、不呼叫 LLM、不掛 scheduler",
            "passed": bool(
                operator[
                    "operator_confirmed_no_token_in_report_catalog_record_closeout"
                ]
                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_closeout_no_token_submitted_to_api",
            "label": "closeout gate payload 不得包含 approval 或 Telegram token key",
            "passed": not operator["forbidden_token_submitted_to_api"],
        },
        {
            "key": "report_catalog_record_closeout_apply_real_write_not_requested_from_api",
            "label": "API/UI report catalog record closeout gate 不接受 apply_real_write",
            "passed": not apply_real_write,
        },
    ]


def build_candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_catalog_record_closeout(
    *,
    telegram_dispatch_report_catalog_record_commit,
    report_catalog_record_closeout=None,
    operator_evidence=None,
    execute_requested=False,
    apply_real_write=False,
):
    """建立 Telegram dispatch report catalog record closeout gate；不執行副作用。"""
    commit = _commit_summary(telegram_dispatch_report_catalog_record_commit)
    operator = _operator_summary(operator_evidence, report_catalog_record_closeout)
    sections = _closeout_sections(commit, operator)
    gates = _closeout_gates(commit, operator, bool(apply_real_write))
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    closeout_passed = bool(not blocked_reasons)

    return {
        "mode": "candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_catalog_record_closeout_preview",
        "target_table": TARGET_TABLE,
        "target_column": TARGET_COLUMN,
        "target_json_path": [
            "market_intel_ai_summary",
            "telegram_dispatch_report_catalog_record_closeout",
        ],
        "target_operation": "review_manual_market_intel_report_catalog_record_closeout",
        "execute_requested": bool(execute_requested),
        "apply_real_write_requested": bool(apply_real_write),
        "report_catalog_record_closeout_reviewed": True,
        "telegram_dispatch_report_catalog_record_closeout_passed": closeout_passed,
        "summary_persistence_telegram_dispatch_report_catalog_record_closeout_passed": closeout_passed,
        "report_catalog_record_closeout_passed": closeout_passed,
        "ready_for_next_manual_phase": closeout_passed,
        "ready_for_market_intel_report_catalog_record_archive": closeout_passed,
        "ready_for_market_intel_report_catalog_record_closeout": False,
        "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": commit["writer_statement_count"]
        or commit["statement_count"],
        "expected_summary_payload_hash": commit["expected_summary_payload_hash"],
        "blocked_reasons": blocked_reasons,
        "gates": gates,
        "telegram_dispatch_report_catalog_record_commit": commit,
        "telegram_dispatch_report_catalog_record_closeout_sections": sections,
        "operator_telegram_dispatch_report_catalog_record_closeout": operator,
        "promotion_gate": {
            "allowed": closeout_passed,
            "next_manual_phase": "market_intel_report_catalog_record_archive",
            "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_archive_requires_separate_gate": True,
        },
        "next_operator_steps": [
            "保存 report catalog record closeout gate artifact path",
            "人工確認 commit gate 與 run receipt 證據已封存",
            "只在 closeout gate 通過後進入 report catalog record archive gate",
            "不得從 API/UI 補寫 catalog record、重跑 CLI、commit、派送 Telegram 或掛 scheduler",
        ],
        "safe_boundaries": [
            "do_not_read_approval_token_from_report_catalog_record_closeout_api",
            "do_not_read_telegram_token_from_report_catalog_record_closeout_api",
            "do_not_call_llm_from_report_catalog_record_closeout",
            "do_not_generate_report_from_report_catalog_record_closeout_api",
            "do_not_write_report_catalog_record_closeout_artifact_from_api",
            "do_not_execute_catalog_record_cli_from_report_catalog_record_closeout_api",
            "do_not_write_report_catalog_record_from_report_catalog_record_closeout_api",
            "do_not_commit_catalog_record_from_report_catalog_record_closeout_api",
            "do_not_dispatch_telegram_from_report_catalog_record_closeout_api",
            "do_not_open_database_connection_from_report_catalog_record_closeout",
            "do_not_update_review_state_from_report_catalog_record_closeout",
            "do_not_attach_scheduler_from_report_catalog_record_closeout",
            "future_market_intel_report_catalog_record_archive_must_use_separate_gate",
            "report_catalog_record_closeout_preview_only",
            "no_remove_orphans",
            "no_momo_db_lifecycle_change",
        ],
    }
