"""候選審核 queue AI summary Telegram dispatch report catalog record run receipt。

本模組只審核外部 CLI 回貼的 catalog record 寫入 receipt 與 post-write
smoke；不讀 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_readiness import (
    FALSE_RESPONSE_KEYS as REPORT_CATALOG_RECORD_RUN_READINESS_FALSE_RESPONSE_KEYS,
)


EXPECTED_RECEIPT_MODES = {
    "market_intel_report_catalog_record_run_receipt",
    "manual_market_intel_report_catalog_record_run_receipt",
    "market_intel_report_catalog_record_cli_run_receipt",
    "catalog_record_writer_cli_receipt",
}
EXPECTED_SMOKE_MODES = {
    "market_intel_report_catalog_record_postwrite_smoke_read_only",
    "catalog_record_postwrite_smoke_read_only",
    "report_catalog_record_postwrite_smoke_read_only",
}
REQUIRED_RUN_READINESS_BOUNDARIES = {
    "do_not_read_approval_token_from_report_catalog_record_run_readiness_api",
    "do_not_read_telegram_token_from_report_catalog_record_run_readiness_api",
    "do_not_call_llm_from_report_catalog_record_run_readiness",
    "do_not_generate_report_from_report_catalog_record_run_readiness_api",
    "do_not_write_report_catalog_record_run_readiness_artifact_from_api",
    "do_not_execute_catalog_record_cli_from_report_catalog_record_run_readiness_api",
    "do_not_write_report_catalog_record_from_report_catalog_record_run_readiness_api",
    "do_not_dispatch_telegram_from_report_catalog_record_run_readiness_api",
    "do_not_open_database_connection_from_report_catalog_record_run_readiness",
    "do_not_update_review_state_from_report_catalog_record_run_readiness",
    "do_not_attach_scheduler_from_report_catalog_record_run_readiness",
    "future_market_intel_report_catalog_record_run_receipt_must_use_separate_gate",
}
FALSE_RESPONSE_KEYS = tuple(
    dict.fromkeys(
        REPORT_CATALOG_RECORD_RUN_READINESS_FALSE_RESPONSE_KEYS
        + (
            "telegram_dispatch_report_catalog_record_run_receipt_gate_file_written",
            "report_catalog_record_run_receipt_gate_file_written",
            "catalog_record_run_receipt_gate_file_written",
            "catalog_record_run_receipt_executed",
            "catalog_record_commit_gate_file_written",
            "catalog_record_commit_executed",
        )
    )
)


def _safe_bool(value):
    return bool(value)


def _hash_matches_expected(expected_hash, observed_hash):
    return bool(expected_hash and observed_hash and str(expected_hash) == str(observed_hash))


def _readiness_summary(telegram_dispatch_report_catalog_record_run_readiness):
    readiness = _as_dict(telegram_dispatch_report_catalog_record_run_readiness)
    manifest = _as_dict(readiness.get("catalog_record_run_readiness_manifest"))
    command = _as_dict(manifest.get("manual_cli_run_command"))
    boundaries = _as_dict(manifest.get("execution_boundaries"))
    source_artifacts = _as_dict(manifest.get("source_artifacts"))
    run_package = _as_dict(readiness.get("telegram_dispatch_report_catalog_record_run_package"))
    promotion = _as_dict(readiness.get("promotion_gate"))
    sections = _as_list(
        readiness.get("telegram_dispatch_report_catalog_record_run_readiness_sections")
    )
    safe_boundaries = set(str(item) for item in _as_list(readiness.get("safe_boundaries")))
    missing_boundaries = sorted(REQUIRED_RUN_READINESS_BOUNDARIES - safe_boundaries)
    section_keys = sorted(
        str(item.get("key"))
        for item in sections
        if isinstance(item, dict) and item.get("key")
    )

    return {
        "provided": bool(readiness),
        "mode": readiness.get("mode"),
        "target_operation": readiness.get("target_operation"),
        "run_readiness_passed": bool(
            readiness.get("telegram_dispatch_report_catalog_record_run_readiness_passed")
            or readiness.get(
                "summary_persistence_telegram_dispatch_report_catalog_record_run_readiness_passed"
            )
            or readiness.get("report_catalog_record_run_readiness_passed")
        ),
        "ready_for_next_manual_phase": bool(readiness.get("ready_for_next_manual_phase")),
        "ready_for_cli_operator_run": bool(readiness.get("ready_for_cli_operator_run")),
        "ready_for_market_intel_report_catalog_record_cli_operator_run": bool(
            readiness.get("ready_for_market_intel_report_catalog_record_cli_operator_run")
        ),
        "ready_for_market_intel_report_catalog_record_run_receipt": bool(
            readiness.get("ready_for_market_intel_report_catalog_record_run_receipt")
        ),
        "ready_for_market_intel_report_catalog_record_cli_run": bool(
            readiness.get("ready_for_market_intel_report_catalog_record_cli_run")
        ),
        "ready_for_market_intel_report_catalog_record_commit": bool(
            readiness.get("ready_for_market_intel_report_catalog_record_commit")
        ),
        "statement_count": _safe_int(readiness.get("statement_count")),
        "expected_summary_payload_hash": _safe_text(
            readiness.get("expected_summary_payload_hash")
            or manifest.get("expected_summary_payload_hash"),
            80,
        ),
        "manifest_version": manifest.get("manifest_version"),
        "source_mode": manifest.get("source_mode"),
        "source_operation": manifest.get("source_operation"),
        "target_table": manifest.get("target_table"),
        "target_column": manifest.get("target_column"),
        "record_family": manifest.get("record_family"),
        "report_output_hash": manifest.get("report_output_hash"),
        "manifest_statement_count": _safe_int(manifest.get("statement_count")),
        "source_record_write_gate": bool(source_artifacts.get("record_write_gate")),
        "source_write_preflight": bool(source_artifacts.get("write_preflight")),
        "source_report_output": bool(source_artifacts.get("report_output")),
        "source_backup": bool(source_artifacts.get("backup")),
        "source_dry_run": bool(source_artifacts.get("dry_run")),
        "command_script_path": command.get("script_path"),
        "command_dry_run": command.get("dry_run_command"),
        "command_executed_by_api": bool(command.get("executed_by_api")),
        "command_writes_catalog_record": bool(command.get("writes_catalog_record")),
        "command_approval_env_var": command.get("requires_approval_env_var"),
        "api_writes_file": bool(boundaries.get("api_writes_file")),
        "api_executes_cli": bool(boundaries.get("api_executes_cli")),
        "api_writes_catalog_record": bool(boundaries.get("api_writes_catalog_record")),
        "api_writes_database": bool(boundaries.get("api_writes_database")),
        "api_dispatches_telegram": bool(boundaries.get("api_dispatches_telegram")),
        "api_calls_llm": bool(boundaries.get("api_calls_llm")),
        "api_attaches_scheduler": bool(boundaries.get("api_attaches_scheduler")),
        "run_package_mode": run_package.get("mode"),
        "run_package_passed": bool(run_package.get("catalog_record_run_package_passed")),
        "run_package_record_family": run_package.get("record_family"),
        "run_package_report_output_hash": run_package.get("report_output_hash"),
        "run_package_expected_hash": run_package.get("expected_summary_payload_hash"),
        "promotion_allowed": bool(promotion.get("allowed")),
        "promotion_next_manual_phase": promotion.get("next_manual_phase"),
        "promotion_requires_real_db_write": bool(promotion.get("requires_real_db_write")),
        "promotion_requires_cli_run": bool(promotion.get("requires_cli_run")),
        "promotion_requires_postwrite_smoke": bool(
            promotion.get("requires_postwrite_smoke")
        ),
        "promotion_receipt_separate_gate": bool(
            promotion.get("report_catalog_record_run_receipt_requires_separate_gate")
        ),
        "promotion_commit_separate_gate": bool(
            promotion.get("report_catalog_record_commit_requires_separate_gate")
        ),
        "safe_boundaries_complete": not missing_boundaries,
        "missing_safe_boundaries": missing_boundaries,
        "section_keys": section_keys,
        "section_count": len(section_keys),
        "forbidden_token_key_detected": _contains_forbidden_token_key(
            _strip_safe_token_boolean_keys(readiness)
        ),
        "blocked_count": len(_as_list(readiness.get("blocked_reasons"))),
        **{key: bool(readiness.get(key)) for key in FALSE_RESPONSE_KEYS},
    }


def _receipt_payload(operator_evidence, catalog_record_run_receipt):
    operator_evidence = _as_dict(operator_evidence)
    embedded = _as_dict(
        operator_evidence.get("market_intel_report_catalog_record_run_receipt")
        or operator_evidence.get("telegram_dispatch_report_catalog_record_run_receipt")
        or operator_evidence.get("report_catalog_record_run_receipt")
        or operator_evidence.get("catalog_record_run_receipt")
    )
    return _as_dict(catalog_record_run_receipt) or embedded


def _writer_summary(receipt_payload, readiness):
    receipt = _as_dict(receipt_payload)
    writer = _as_dict(
        receipt.get("writer_output")
        or receipt.get("catalog_record_writer_output")
        or receipt.get("execution_result")
    )
    source = writer or receipt
    target_table = source.get("target_table") or receipt.get("target_table")
    target_column = source.get("target_column") or receipt.get("target_column")
    record_family = (
        source.get("record_family")
        or source.get("target_report_family")
        or receipt.get("record_family")
        or receipt.get("target_report_family")
    )
    observed_summary_hash = (
        source.get("expected_summary_payload_hash")
        or source.get("summary_payload_hash")
        or receipt.get("expected_summary_payload_hash")
        or receipt.get("summary_payload_hash")
    )
    observed_report_hash = (
        source.get("report_output_hash")
        or source.get("report_hash")
        or receipt.get("report_output_hash")
        or receipt.get("report_hash")
    )
    return {
        "provided": bool(source),
        "mode": source.get("mode") or receipt.get("mode"),
        "exit_code": source.get("exit_code"),
        "catalog_record_cli_executed": bool(
            source.get("catalog_record_cli_executed")
            or source.get("catalog_record_writer_cli_executed")
            or source.get("cli_executed")
            or source.get("writes_executed")
        ),
        "catalog_record_written": bool(
            source.get("catalog_record_written")
            or source.get("report_catalog_record_written")
            or source.get("record_written")
        ),
        "target_table": _safe_text(target_table, 120),
        "target_column": _safe_text(target_column, 120),
        "record_family": _safe_text(record_family, 180),
        "catalog_record_key": _safe_text(
            source.get("catalog_record_key")
            or source.get("record_key")
            or receipt.get("catalog_record_key")
            or receipt.get("record_key"),
            240,
        ),
        "statement_count": _safe_int(
            source.get("statement_count")
            or source.get("affected_statement_count")
            or receipt.get("statement_count")
        ),
        "affected_count": _safe_int(
            source.get("affected_count")
            or source.get("updated_count")
            or source.get("inserted_count")
            or receipt.get("affected_count")
        ),
        "database_connection_opened": bool(source.get("database_connection_opened")),
        "explicit_transaction_opened": bool(source.get("explicit_transaction_opened")),
        "database_write_executed": bool(source.get("database_write_executed")),
        "database_commit_executed": bool(source.get("database_commit_executed")),
        "database_rollback_executed": bool(source.get("database_rollback_executed")),
        "executed_by_api": bool(source.get("executed_by_api") or source.get("api_executed")),
        "api_writes_file": bool(source.get("api_writes_file")),
        "api_executes_cli": bool(source.get("api_executes_cli")),
        "api_writes_database": bool(source.get("api_writes_database")),
        "api_dispatches_telegram": bool(source.get("api_dispatches_telegram")),
        "api_calls_llm": bool(source.get("api_calls_llm")),
        "telegram_dispatched": bool(source.get("telegram_dispatched")),
        "llm_call_executed": bool(source.get("llm_call_executed")),
        "external_network_executed": bool(source.get("external_network_executed")),
        "scheduler_attached": bool(source.get("scheduler_attached")),
        "review_state_update_executed": bool(source.get("review_state_update_executed")),
        "expected_summary_payload_hash": readiness["expected_summary_payload_hash"],
        "observed_summary_payload_hash": _safe_text(observed_summary_hash, 80),
        "summary_payload_hash_matches_expected": _hash_matches_expected(
            readiness["expected_summary_payload_hash"],
            observed_summary_hash,
        ),
        "expected_report_output_hash": readiness["report_output_hash"],
        "observed_report_output_hash": _safe_text(observed_report_hash, 120),
        "report_output_hash_matches_expected": _hash_matches_expected(
            readiness["report_output_hash"],
            observed_report_hash,
        ),
        "approval_or_telegram_token_key_detected": _contains_forbidden_token_key(
            _strip_safe_token_boolean_keys(source)
        )
        or _contains_forbidden_token_key(_strip_safe_token_boolean_keys(receipt)),
    }


def _smoke_summary(receipt_payload, readiness):
    receipt = _as_dict(receipt_payload)
    smoke = _as_dict(
        receipt.get("postwrite_smoke_result")
        or receipt.get("catalog_record_postwrite_smoke")
        or receipt.get("postwrite_smoke")
    )
    source = smoke
    found_key = (
        source.get("catalog_record_key")
        or source.get("record_key")
        or source.get("found_catalog_record_key")
        or source.get("found_record_key")
    )
    observed_hash = (
        source.get("expected_summary_payload_hash")
        or source.get("summary_payload_hash")
        or source.get("metadata_json_summary_payload_hash")
    )
    return {
        "provided": bool(source),
        "mode": source.get("mode"),
        "postwrite_smoke_passed": bool(
            source.get("postwrite_smoke_passed")
            or source.get("catalog_record_postwrite_smoke_passed")
        ),
        "read_only_query_executed": bool(source.get("read_only_query_executed")),
        "catalog_record_found": bool(
            source.get("catalog_record_found")
            or source.get("record_found")
            or source.get("found")
        ),
        "target_table": _safe_text(source.get("target_table"), 120),
        "target_column": _safe_text(source.get("target_column"), 120),
        "record_family": _safe_text(
            source.get("record_family") or source.get("target_report_family"),
            180,
        ),
        "catalog_record_key": _safe_text(found_key, 240),
        "database_connection_opened": bool(source.get("database_connection_opened")),
        "database_write_executed": bool(source.get("database_write_executed")),
        "database_commit_executed": bool(source.get("database_commit_executed")),
        "database_rollback_executed": bool(source.get("database_rollback_executed")),
        "external_network_executed": bool(source.get("external_network_executed")),
        "scheduler_attached": bool(source.get("scheduler_attached")),
        "expected_summary_payload_hash": readiness["expected_summary_payload_hash"],
        "observed_summary_payload_hash": _safe_text(observed_hash, 80),
        "summary_payload_hash_matches_expected": _hash_matches_expected(
            readiness["expected_summary_payload_hash"],
            observed_hash,
        ),
        "approval_or_telegram_token_key_detected": _contains_forbidden_token_key(
            _strip_safe_token_boolean_keys(source)
        ),
    }


def _operator_summary(operator_evidence):
    operator_evidence = _as_dict(operator_evidence)
    return {
        "provided_keys": sorted(operator_evidence.keys()),
        "report_catalog_record_run_receipt_artifact_path": _safe_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 operator_evidence.get(
                "market_intel_report_catalog_record_run_receipt_artifact_path"
            )
        ),
        "report_catalog_record_run_readiness_artifact_path_recorded": _has_text(
            operator_evidence.get("report_catalog_record_run_readiness_artifact_path")
            or operator_evidence.get(
                "telegram_dispatch_report_catalog_record_run_readiness_artifact_path"
            )
        ),
        "report_catalog_record_run_package_artifact_path_recorded": _has_text(
            operator_evidence.get("report_catalog_record_run_package_artifact_path")
            or operator_evidence.get(
                "telegram_dispatch_report_catalog_record_run_package_artifact_path"
            )
        ),
        "catalog_record_payload_manifest_path_recorded": _has_text(
            operator_evidence.get("catalog_record_payload_manifest_path")
            or operator_evidence.get("report_catalog_record_payload_manifest_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")
        ),
        "catalog_record_write_dry_run_artifact_path_recorded": _has_text(
            operator_evidence.get("catalog_record_write_dry_run_artifact_path")
            or operator_evidence.get("report_catalog_record_dry_run_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")
        ),
        "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")
        ),
        "catalog_record_cli_command_recorded": _has_text(
            operator_evidence.get("catalog_record_cli_command")
            or operator_evidence.get("report_catalog_record_cli_command")
        ),
        "operator_confirmed_report_catalog_record_run_receipt": bool(
            operator_evidence.get("operator_confirmed_report_catalog_record_run_receipt")
            or operator_evidence.get(
                "operator_confirmed_market_intel_report_catalog_record_run_receipt"
            )
        ),
        "operator_confirmed_catalog_record_run_readiness_reviewed": bool(
            operator_evidence.get(
                "operator_confirmed_catalog_record_run_readiness_reviewed"
            )
            or operator_evidence.get(
                "operator_confirmed_report_catalog_record_run_readiness_reviewed"
            )
        ),
        "operator_confirmed_catalog_record_cli_output_reviewed": bool(
            operator_evidence.get("operator_confirmed_catalog_record_cli_output_reviewed")
            or operator_evidence.get("operator_confirmed_writer_output_reviewed")
        ),
        "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")
        ),
        "operator_confirmed_catalog_record_backup_available": bool(
            operator_evidence.get("operator_confirmed_catalog_record_backup_available")
            or operator_evidence.get("operator_confirmed_catalog_record_backup_required")
        ),
        "operator_confirmed_catalog_record_commit_requires_separate_gate": bool(
            operator_evidence.get(
                "operator_confirmed_report_catalog_record_commit_requires_separate_gate"
            )
            or operator_evidence.get(
                "operator_confirmed_catalog_record_commit_requires_separate_gate"
            )
        ),
        "operator_confirmed_no_token_in_report_catalog_record_run_receipt": bool(
            operator_evidence.get(
                "operator_confirmed_no_token_in_report_catalog_record_run_receipt"
            )
            or operator_evidence.get("operator_confirmed_no_token_in_artifacts")
        ),
        "operator_confirmed_no_api_file_write": bool(
            operator_evidence.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")
        ),
        "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")
        ),
        "operator_confirmed_no_api_telegram_dispatch": bool(
            operator_evidence.get("operator_confirmed_no_api_telegram_dispatch")
        ),
        "operator_confirmed_no_api_db_write": bool(
            operator_evidence.get("operator_confirmed_no_api_db_write")
        ),
        "operator_confirmed_no_llm_call": bool(
            operator_evidence.get("operator_confirmed_no_llm_call")
        ),
        "operator_confirmed_no_scheduler_attach": bool(
            operator_evidence.get("operator_confirmed_no_scheduler_attach")
        ),
        "catalog_record_run_receipt_notes_recorded": _has_text(
            operator_evidence.get("report_catalog_record_run_receipt_notes")
            or operator_evidence.get("catalog_record_run_receipt_notes")
        ),
        "safe_token_metadata_only": all(
            key in SAFE_TOKEN_METADATA_KEYS or key == "approval_env_var"
            for key in 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
        ),
    }


def _run_receipt_sections(readiness, writer, smoke, operator):
    return [
        {
            "key": "catalog_record_run_receipt_identity",
            "title": "Catalog record run receipt identity",
            "facts": [
                f"family={readiness['record_family'] or 'missing'}",
                f"writer_mode={writer['mode'] or 'missing'}",
                f"statement_count={writer['statement_count']}",
            ],
        },
        {
            "key": "catalog_record_run_receipt_cli_result",
            "title": "Catalog record CLI result",
            "facts": [
                f"cli_executed={writer['catalog_record_cli_executed']}",
                f"record_written={writer['catalog_record_written']}",
                f"committed={writer['database_commit_executed']}",
            ],
        },
        {
            "key": "catalog_record_run_receipt_postwrite_smoke",
            "title": "Catalog record post-write smoke",
            "facts": [
                f"smoke_mode={smoke['mode'] or 'missing'}",
                f"record_found={smoke['catalog_record_found']}",
                f"hash_match={smoke['summary_payload_hash_matches_expected']}",
            ],
        },
        {
            "key": "catalog_record_run_receipt_safety",
            "title": "Catalog record run receipt safety",
            "facts": [
                f"receipt_path={bool(operator['report_catalog_record_run_receipt_artifact_path'])}",
                "api_cli_executed=false",
                "api_database_write_executed=false",
                "scheduler_attached=false",
            ],
        },
    ]


def _run_receipt_gates(readiness, writer, smoke, operator, apply_real_write):
    required_sections = {
        "catalog_record_run_readiness_identity",
        "catalog_record_run_readiness_artifacts",
        "catalog_record_run_readiness_command",
        "catalog_record_run_readiness_safety",
    }
    section_keys = set(readiness["section_keys"])
    return [
        {
            "key": "report_catalog_record_run_readiness_preview_provided",
            "label": "必須提供上一階段 report catalog record run readiness preview",
            "passed": bool(
                readiness["provided"]
                and readiness["mode"]
                == "candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_catalog_record_run_readiness_preview"
            ),
        },
        {
            "key": "report_catalog_record_run_readiness_passed",
            "label": "report catalog record run readiness gate 必須已通過",
            "passed": readiness["run_readiness_passed"],
        },
        {
            "key": "report_catalog_record_run_readiness_ready_for_receipt",
            "label": "run readiness 只能放行到 catalog record run receipt",
            "passed": bool(
                readiness["ready_for_next_manual_phase"]
                and readiness["ready_for_cli_operator_run"]
                and readiness[
                    "ready_for_market_intel_report_catalog_record_cli_operator_run"
                ]
                and readiness["ready_for_market_intel_report_catalog_record_run_receipt"]
                and not readiness["ready_for_market_intel_report_catalog_record_cli_run"]
                and not readiness["ready_for_market_intel_report_catalog_record_commit"]
                and readiness["promotion_allowed"]
                and readiness["promotion_next_manual_phase"]
                == "market_intel_report_catalog_record_run_receipt"
                and readiness["promotion_requires_real_db_write"]
                and readiness["promotion_requires_cli_run"]
                and readiness["promotion_requires_postwrite_smoke"]
                and readiness["promotion_receipt_separate_gate"]
                and readiness["promotion_commit_separate_gate"]
            ),
        },
        {
            "key": "catalog_record_run_readiness_manifest_complete",
            "label": "run readiness manifest 必須保留 target、record family、hash、source artifacts 與 CLI command",
            "passed": bool(
                readiness["manifest_version"]
                == "market_intel_report_catalog_record_run_readiness_v1"
                and readiness["target_table"] == TARGET_TABLE
                and readiness["target_column"] == TARGET_COLUMN
                and readiness["record_family"]
                and readiness["report_output_hash"]
                and readiness["expected_summary_payload_hash"]
                and readiness["statement_count"] > 0
                and readiness["manifest_statement_count"] == readiness["statement_count"]
                and readiness["source_record_write_gate"]
                and readiness["source_write_preflight"]
                and readiness["source_report_output"]
                and readiness["source_backup"]
                and readiness["source_dry_run"]
                and readiness["command_script_path"]
                == "scripts/market_intel/write_report_catalog_record.py"
                and readiness["command_dry_run"]
                and not readiness["command_executed_by_api"]
                and readiness["command_writes_catalog_record"]
                and readiness["command_approval_env_var"] == SAFE_APPROVAL_ENV_VAR
            ),
        },
        {
            "key": "catalog_record_run_readiness_sections_complete",
            "label": "run readiness sections 必須完整",
            "passed": required_sections.issubset(section_keys),
        },
        {
            "key": "report_catalog_record_run_readiness_runtime_boundaries_clear",
            "label": "run readiness payload 不得顯示 API 寫檔、DB、Telegram、LLM、CLI 或 scheduler 副作用",
            "passed": bool(
                all(not readiness[key] for key in FALSE_RESPONSE_KEYS)
                and not readiness["api_writes_file"]
                and not readiness["api_executes_cli"]
                and not readiness["api_writes_catalog_record"]
                and not readiness["api_writes_database"]
                and not readiness["api_dispatches_telegram"]
                and not readiness["api_calls_llm"]
                and not readiness["api_attaches_scheduler"]
            ),
        },
        {
            "key": "report_catalog_record_run_readiness_safe_boundaries_complete",
            "label": "run readiness 必須保留 run receipt separate gate 與 runtime 安全邊界",
            "passed": readiness["safe_boundaries_complete"],
        },
        {
            "key": "catalog_record_run_receipt_writer_output_provided",
            "label": "操作員需貼回 catalog record CLI writer output",
            "passed": writer["provided"],
        },
        {
            "key": "catalog_record_run_receipt_writer_committed",
            "label": "writer output 必須顯示 CLI 已寫入 catalog record 並 commit",
            "passed": bool(
                writer["mode"] in EXPECTED_RECEIPT_MODES
                and writer["catalog_record_cli_executed"]
                and writer["catalog_record_written"]
                and writer["target_table"] == TARGET_TABLE
                and writer["target_column"] == TARGET_COLUMN
                and writer["record_family"] == readiness["record_family"]
                and writer["statement_count"] == readiness["statement_count"]
                and writer["statement_count"] > 0
                and writer["database_connection_opened"]
                and writer["database_write_executed"]
                and writer["database_commit_executed"]
                and not writer["database_rollback_executed"]
                and writer["summary_payload_hash_matches_expected"]
                and writer["report_output_hash_matches_expected"]
            ),
        },
        {
            "key": "catalog_record_run_receipt_writer_runtime_boundaries",
            "label": "writer output 不得顯示 API 執行、Telegram、LLM、scheduler 或 review_state 副作用",
            "passed": bool(
                not writer["executed_by_api"]
                and not writer["api_writes_file"]
                and not writer["api_executes_cli"]
                and not writer["api_writes_database"]
                and not writer["api_dispatches_telegram"]
                and not writer["api_calls_llm"]
                and not writer["telegram_dispatched"]
                and not writer["llm_call_executed"]
                and not writer["external_network_executed"]
                and not writer["scheduler_attached"]
                and not writer["review_state_update_executed"]
            ),
        },
        {
            "key": "catalog_record_run_receipt_postwrite_smoke_provided",
            "label": "操作員需貼回 catalog record post-write smoke 結果",
            "passed": smoke["provided"],
        },
        {
            "key": "catalog_record_run_receipt_postwrite_smoke_passed",
            "label": "post-write smoke 必須是只讀查詢、找到 catalog record，且 hash 符合",
            "passed": bool(
                smoke["mode"] in EXPECTED_SMOKE_MODES
                and smoke["postwrite_smoke_passed"]
                and smoke["read_only_query_executed"]
                and smoke["catalog_record_found"]
                and smoke["target_table"] == TARGET_TABLE
                and smoke["target_column"] == TARGET_COLUMN
                and smoke["record_family"] == readiness["record_family"]
                and smoke["summary_payload_hash_matches_expected"]
            ),
        },
        {
            "key": "catalog_record_run_receipt_postwrite_smoke_no_db_write",
            "label": "post-write smoke 不得寫 DB、commit、rollback、連外或掛 scheduler",
            "passed": bool(
                not smoke["database_write_executed"]
                and not smoke["database_commit_executed"]
                and not smoke["database_rollback_executed"]
                and not smoke["external_network_executed"]
                and not smoke["scheduler_attached"]
            ),
        },
        {
            "key": "operator_confirmed_report_catalog_record_run_receipt",
            "label": "操作員確認 receipt、readiness、writer output、backup、CLI、postwrite smoke 與 commit separate gate",
            "passed": bool(
                operator["report_catalog_record_run_receipt_artifact_path"]
                and operator["report_catalog_record_run_readiness_artifact_path_recorded"]
                and operator["report_catalog_record_run_package_artifact_path_recorded"]
                and operator["catalog_record_payload_manifest_path_recorded"]
                and operator["catalog_record_backup_artifact_path_recorded"]
                and operator["catalog_record_write_dry_run_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_cli_command_recorded"]
                and operator["operator_confirmed_report_catalog_record_run_receipt"]
                and operator["operator_confirmed_catalog_record_run_readiness_reviewed"]
                and operator["operator_confirmed_catalog_record_cli_output_reviewed"]
                and operator["operator_confirmed_catalog_record_postwrite_smoke_passed"]
                and operator["operator_confirmed_catalog_record_backup_available"]
                and operator["operator_confirmed_catalog_record_commit_requires_separate_gate"]
            ),
        },
        {
            "key": "operator_confirmed_report_catalog_record_run_receipt_runtime_boundaries",
            "label": "操作員確認本 API 不寫檔、不執行 CLI、不寫 DB、不派送 Telegram、不呼叫 LLM、不掛 scheduler",
            "passed": bool(
                operator[
                    "operator_confirmed_no_token_in_report_catalog_record_run_receipt"
                ]
                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_run_receipt_no_token_submitted_to_api",
            "label": "catalog record run receipt payload 不得包含 approval 或 Telegram token key",
            "passed": bool(
                not operator["forbidden_token_submitted_to_api"]
                and not readiness["forbidden_token_key_detected"]
                and not writer["approval_or_telegram_token_key_detected"]
                and not smoke["approval_or_telegram_token_key_detected"]
            ),
        },
        {
            "key": "report_catalog_record_run_receipt_apply_real_write_not_requested_from_api",
            "label": "API/UI report catalog record run receipt 不接受 apply_real_write",
            "passed": not apply_real_write,
        },
    ]


def build_candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_catalog_record_run_receipt(
    *,
    telegram_dispatch_report_catalog_record_run_readiness,
    catalog_record_run_receipt=None,
    operator_evidence=None,
    execute_requested=False,
    apply_real_write=False,
):
    """建立 Telegram dispatch report catalog record run receipt；不執行副作用。"""
    readiness = _readiness_summary(telegram_dispatch_report_catalog_record_run_readiness)
    receipt_payload = _receipt_payload(operator_evidence, catalog_record_run_receipt)
    writer = _writer_summary(receipt_payload, readiness)
    smoke = _smoke_summary(receipt_payload, readiness)
    operator = _operator_summary(operator_evidence)
    sections = _run_receipt_sections(readiness, writer, smoke, operator)
    gates = _run_receipt_gates(readiness, writer, smoke, operator, bool(apply_real_write))
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    receipt_passed = bool(not blocked_reasons)

    return {
        "mode": "candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_catalog_record_run_receipt_preview",
        "target_table": TARGET_TABLE,
        "target_column": TARGET_COLUMN,
        "target_json_path": [
            "market_intel_ai_summary",
            "telegram_dispatch_report_catalog_record_run_receipt",
        ],
        "target_operation": "review_manual_market_intel_report_catalog_record_run_receipt",
        "execute_requested": bool(execute_requested),
        "apply_real_write_requested": bool(apply_real_write),
        "report_catalog_record_run_receipt_reviewed": True,
        "telegram_dispatch_report_catalog_record_run_receipt_passed": receipt_passed,
        "summary_persistence_telegram_dispatch_report_catalog_record_run_receipt_passed": receipt_passed,
        "report_catalog_record_run_receipt_passed": receipt_passed,
        "ready_for_next_manual_phase": receipt_passed,
        "ready_for_market_intel_report_catalog_record_commit": receipt_passed,
        "ready_for_market_intel_report_catalog_record_commit_gate": receipt_passed,
        "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": readiness["statement_count"],
        "expected_summary_payload_hash": readiness["expected_summary_payload_hash"],
        "blocked_reasons": blocked_reasons,
        "gates": gates,
        "telegram_dispatch_report_catalog_record_run_readiness": readiness,
        "telegram_dispatch_report_catalog_record_run_receipt_writer": writer,
        "telegram_dispatch_report_catalog_record_run_receipt_postwrite_smoke": smoke,
        "telegram_dispatch_report_catalog_record_run_receipt_sections": sections,
        "operator_telegram_dispatch_report_catalog_record_run_receipt": operator,
        "promotion_gate": {
            "allowed": receipt_passed,
            "next_manual_phase": "market_intel_report_catalog_record_commit",
            "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,
            "report_catalog_record_commit_requires_separate_gate": True,
        },
        "next_operator_steps": [
            "保存 report catalog record run receipt artifact path",
            "人工確認 CLI writer output、catalog record key、hash 與 post-write smoke",
            "只在 run receipt 通過後進入 report catalog record commit gate",
            "不得從 API/UI 補寫 catalog record、重跑 CLI、commit 或掛 scheduler",
        ],
        "safe_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",
            "report_catalog_record_run_receipt_preview_only",
            "no_remove_orphans",
            "no_momo_db_lifecycle_change",
        ],
    }
