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

本模組只在 catalog record archive 通過後整理長期查閱摘要；不讀 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_catalog_record_archive import (
    FALSE_RESPONSE_KEYS as REPORT_CATALOG_RECORD_ARCHIVE_FALSE_RESPONSE_KEYS,
    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,
)


REQUIRED_ARCHIVE_BOUNDARIES = {
    "do_not_read_approval_token_from_report_catalog_record_archive_api",
    "do_not_read_telegram_token_from_report_catalog_record_archive_api",
    "do_not_call_llm_from_report_catalog_record_archive",
    "do_not_generate_report_from_report_catalog_record_archive_api",
    "do_not_write_report_catalog_record_archive_artifact_from_api",
    "do_not_execute_catalog_record_cli_from_report_catalog_record_archive_api",
    "do_not_write_report_catalog_record_from_report_catalog_record_archive_api",
    "do_not_commit_catalog_record_from_report_catalog_record_archive_api",
    "do_not_dispatch_telegram_from_report_catalog_record_archive_api",
    "do_not_open_database_connection_from_report_catalog_record_archive",
    "do_not_update_review_state_from_report_catalog_record_archive",
    "do_not_attach_scheduler_from_report_catalog_record_archive",
    "future_market_intel_report_catalog_record_archive_summary_must_use_separate_gate",
}
FALSE_RESPONSE_KEYS = tuple(
    dict.fromkeys(
        REPORT_CATALOG_RECORD_ARCHIVE_FALSE_RESPONSE_KEYS
        + (
            "telegram_dispatch_report_catalog_record_archive_summary_gate_file_written",
            "report_catalog_record_archive_summary_gate_file_written",
            "catalog_record_archive_summary_gate_file_written",
            "telegram_dispatch_report_catalog_record_archive_summary_file_written",
            "report_catalog_record_archive_summary_file_written",
            "catalog_record_archive_summary_file_written",
            "catalog_record_archive_summary_record_written",
            "catalog_record_archive_summary_executed",
            "catalog_record_final_closeout_gate_file_written",
        )
    )
)


def _archive_summary(telegram_dispatch_report_catalog_record_archive):
    archive = _as_dict(telegram_dispatch_report_catalog_record_archive)
    closeout = _as_dict(archive.get("telegram_dispatch_report_catalog_record_closeout"))
    operator = _as_dict(
        archive.get("operator_telegram_dispatch_report_catalog_record_archive")
    )
    promotion = _as_dict(archive.get("promotion_gate"))
    safe_boundaries = set(str(item) for item in _as_list(archive.get("safe_boundaries")))
    missing_boundaries = sorted(REQUIRED_ARCHIVE_BOUNDARIES - safe_boundaries)
    blocked_keys = [key for key in FALSE_RESPONSE_KEYS if bool(archive.get(key))]

    return {
        "provided": bool(archive),
        "mode": archive.get("mode"),
        "target_operation": archive.get("target_operation"),
        "archive_passed": bool(
            archive.get("telegram_dispatch_report_catalog_record_archive_passed")
            or archive.get(
                "summary_persistence_telegram_dispatch_report_catalog_record_archive_passed"
            )
            or archive.get("report_catalog_record_archive_passed")
        ),
        "ready_for_next_manual_phase": bool(archive.get("ready_for_next_manual_phase")),
        "ready_for_market_intel_report_catalog_record_archive_summary": bool(
            archive.get("ready_for_market_intel_report_catalog_record_archive_summary")
        ),
        "ready_for_market_intel_report_catalog_record_archive": bool(
            archive.get("ready_for_market_intel_report_catalog_record_archive")
        ),
        "statement_count": _safe_int(archive.get("statement_count")),
        "expected_summary_payload_hash": _safe_text(
            archive.get("expected_summary_payload_hash")
            or closeout.get("expected_summary_payload_hash"),
            80,
        ),
        "writer_record_family": _safe_text(closeout.get("writer_record_family"), 80),
        "writer_catalog_record_key": _safe_text(
            closeout.get("writer_catalog_record_key"), 160
        ),
        "writer_target_table": closeout.get("writer_target_table"),
        "writer_target_column": closeout.get("writer_target_column"),
        "writer_statement_count": _safe_int(closeout.get("writer_statement_count")),
        "writer_database_commit_executed": bool(
            closeout.get("writer_database_commit_executed")
        ),
        "writer_hash_match": bool(closeout.get("writer_hash_match")),
        "smoke_read_only_query_executed": bool(
            closeout.get("smoke_read_only_query_executed")
        ),
        "smoke_postwrite_smoke_passed": bool(
            closeout.get("smoke_postwrite_smoke_passed")
        ),
        "smoke_hash_match": bool(closeout.get("smoke_hash_match")),
        "closeout_passed": bool(closeout.get("closeout_passed")),
        "closeout_artifact_path_recorded": bool(
            closeout.get("operator_closeout_artifact_path")
        ),
        "commit_artifact_path_recorded": bool(
            closeout.get("operator_commit_artifact_path_recorded")
        ),
        "run_receipt_artifact_path_recorded": bool(
            closeout.get("operator_run_receipt_artifact_path_recorded")
        ),
        "writer_output_artifact_path_recorded": bool(
            closeout.get("operator_writer_output_artifact_path_recorded")
        ),
        "postwrite_smoke_artifact_path_recorded": bool(
            closeout.get("operator_postwrite_smoke_artifact_path_recorded")
        ),
        "backup_artifact_path_recorded": bool(
            closeout.get("operator_backup_artifact_path_recorded")
        ),
        "archive_artifact_path": operator.get("report_catalog_record_archive_artifact_path"),
        "archive_closeout_artifact_path_recorded": bool(
            operator.get("report_catalog_record_closeout_artifact_path_recorded")
        ),
        "archive_commit_artifact_path_recorded": bool(
            operator.get("report_catalog_record_commit_artifact_path_recorded")
        ),
        "archive_run_receipt_artifact_path_recorded": bool(
            operator.get("report_catalog_record_run_receipt_artifact_path_recorded")
        ),
        "archive_writer_output_artifact_path_recorded": bool(
            operator.get("catalog_record_writer_output_artifact_path_recorded")
        ),
        "archive_postwrite_smoke_artifact_path_recorded": bool(
            operator.get("catalog_record_postwrite_smoke_artifact_path_recorded")
        ),
        "archive_backup_artifact_path_recorded": bool(
            operator.get("catalog_record_backup_artifact_path_recorded")
        ),
        "operator_confirmed_archive_gate": bool(
            operator.get("operator_confirmed_report_catalog_record_archive_gate")
        ),
        "operator_confirmed_closeout_reviewed": bool(
            operator.get("operator_confirmed_report_catalog_record_closeout_reviewed")
        ),
        "operator_confirmed_db_commit_observed": bool(
            operator.get("operator_confirmed_catalog_record_db_commit_observed")
        ),
        "operator_confirmed_no_followup_db_write_required": bool(
            operator.get(
                "operator_confirmed_catalog_record_no_followup_db_write_required"
            )
        ),
        "operator_confirmed_archive_manifest_reviewed": bool(
            operator.get("operator_confirmed_catalog_record_archive_manifest_reviewed")
        ),
        "operator_confirmed_archive_retention_policy_recorded": bool(
            operator.get(
                "operator_confirmed_catalog_record_archive_retention_policy_recorded"
            )
        ),
        "operator_confirmed_archive_summary_requires_separate_gate": bool(
            operator.get(
                "operator_confirmed_catalog_record_archive_summary_requires_separate_gate"
            )
        ),
        "promotion_allowed": bool(promotion.get("allowed")),
        "promotion_next_manual_phase": promotion.get("next_manual_phase"),
        "promotion_archive_summary_separate_gate": bool(
            promotion.get("report_catalog_record_archive_summary_requires_separate_gate")
        ),
        "promotion_api_must_not_generate_report": bool(
            promotion.get("api_must_not_generate_report")
        ),
        "promotion_api_must_not_write_file": bool(
            promotion.get("api_must_not_write_file")
        ),
        "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_write_database": bool(
            promotion.get("api_must_not_write_database")
        ),
        "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")
        ),
        "safe_boundaries_complete": not missing_boundaries,
        "missing_safe_boundaries": missing_boundaries,
        "forbidden_token_key_detected": _contains_forbidden_token_key(
            _strip_safe_token_boolean_keys(archive)
        ),
        "blocked_response_keys_true": blocked_keys,
        **{key: bool(archive.get(key)) for key in FALSE_RESPONSE_KEYS},
    }


def _operator_summary(operator_evidence, report_catalog_record_archive_summary=None):
    operator_evidence = _as_dict(operator_evidence)
    summary_payload = _as_dict(report_catalog_record_archive_summary)
    return {
        "provided_keys": sorted(operator_evidence.keys()),
        "report_catalog_record_archive_summary_artifact_path": _safe_text(
            operator_evidence.get("report_catalog_record_archive_summary_artifact_path")
            or operator_evidence.get(
                "telegram_dispatch_report_catalog_record_archive_summary_artifact_path"
            )
            or operator_evidence.get(
                "market_intel_report_catalog_record_archive_summary_artifact_path"
            )
            or summary_payload.get("report_catalog_record_archive_summary_artifact_path"),
            300,
        ),
        "report_catalog_record_archive_artifact_path_recorded": _has_text(
            operator_evidence.get("report_catalog_record_archive_artifact_path")
            or summary_payload.get("report_catalog_record_archive_artifact_path")
        ),
        "report_catalog_record_closeout_artifact_path_recorded": _has_text(
            operator_evidence.get("report_catalog_record_closeout_artifact_path")
            or summary_payload.get("report_catalog_record_closeout_artifact_path")
        ),
        "report_catalog_record_commit_artifact_path_recorded": _has_text(
            operator_evidence.get("report_catalog_record_commit_artifact_path")
            or summary_payload.get("report_catalog_record_commit_artifact_path")
        ),
        "report_catalog_record_run_receipt_artifact_path_recorded": _has_text(
            operator_evidence.get("report_catalog_record_run_receipt_artifact_path")
            or summary_payload.get("report_catalog_record_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("writer_output_json_path")
            or summary_payload.get("catalog_record_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("postwrite_smoke_json_path")
            or summary_payload.get("catalog_record_postwrite_smoke_artifact_path")
        ),
        "catalog_record_backup_artifact_path_recorded": _has_text(
            operator_evidence.get("catalog_record_backup_artifact_path")
            or operator_evidence.get("backup_artifact_path")
            or summary_payload.get("catalog_record_backup_artifact_path")
        ),
        "operator_confirmed_report_catalog_record_archive_summary_gate": bool(
            operator_evidence.get(
                "operator_confirmed_report_catalog_record_archive_summary_gate"
            )
            or operator_evidence.get(
                "operator_confirmed_market_intel_report_catalog_record_archive_summary"
            )
            or summary_payload.get(
                "operator_confirmed_report_catalog_record_archive_summary_gate"
            )
        ),
        "operator_confirmed_report_catalog_record_archive_reviewed": bool(
            operator_evidence.get(
                "operator_confirmed_report_catalog_record_archive_reviewed"
            )
            or operator_evidence.get(
                "operator_confirmed_catalog_record_archive_reviewed"
            )
            or summary_payload.get(
                "operator_confirmed_report_catalog_record_archive_reviewed"
            )
        ),
        "operator_confirmed_catalog_record_traceability_reviewed": bool(
            operator_evidence.get(
                "operator_confirmed_catalog_record_traceability_reviewed"
            )
            or operator_evidence.get(
                "operator_confirmed_report_catalog_record_traceability_reviewed"
            )
            or summary_payload.get(
                "operator_confirmed_catalog_record_traceability_reviewed"
            )
        ),
        "operator_confirmed_catalog_record_archive_summary_read_only": bool(
            operator_evidence.get(
                "operator_confirmed_catalog_record_archive_summary_read_only"
            )
            or operator_evidence.get("operator_confirmed_summary_is_read_only")
            or summary_payload.get(
                "operator_confirmed_catalog_record_archive_summary_read_only"
            )
        ),
        "operator_confirmed_catalog_record_final_closeout_requires_separate_gate": bool(
            operator_evidence.get(
                "operator_confirmed_catalog_record_final_closeout_requires_separate_gate"
            )
            or operator_evidence.get(
                "operator_confirmed_report_catalog_record_final_closeout_requires_separate_gate"
            )
            or summary_payload.get(
                "operator_confirmed_catalog_record_final_closeout_requires_separate_gate"
            )
        ),
        "operator_confirmed_no_token_in_report_catalog_record_archive_summary": bool(
            operator_evidence.get(
                "operator_confirmed_no_token_in_report_catalog_record_archive_summary"
            )
            or operator_evidence.get("operator_confirmed_no_token_in_artifacts")
            or summary_payload.get(
                "operator_confirmed_no_token_in_report_catalog_record_archive_summary"
            )
        ),
        "operator_confirmed_no_api_report_generation": bool(
            operator_evidence.get("operator_confirmed_no_api_report_generation")
            or operator_evidence.get("operator_confirmed_no_api_report_write")
            or summary_payload.get("operator_confirmed_no_api_report_generation")
        ),
        "operator_confirmed_no_api_file_write": bool(
            operator_evidence.get("operator_confirmed_no_api_file_write")
            or summary_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 summary_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 summary_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 summary_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 summary_payload.get("operator_confirmed_no_api_db_write")
        ),
        "operator_confirmed_no_llm_call": bool(
            operator_evidence.get("operator_confirmed_no_llm_call")
            or summary_payload.get("operator_confirmed_no_llm_call")
        ),
        "operator_confirmed_no_scheduler_attach": bool(
            operator_evidence.get("operator_confirmed_no_scheduler_attach")
            or summary_payload.get("operator_confirmed_no_scheduler_attach")
        ),
        "archive_summary_notes_recorded": _has_text(
            operator_evidence.get("report_catalog_record_archive_summary_notes")
            or operator_evidence.get("catalog_record_archive_summary_notes")
            or summary_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(summary_payload),
    }


def _summary_sections(archive, operator):
    artifact_count = sum(
        1
        for key in (
            "archive_artifact_path",
            "archive_closeout_artifact_path_recorded",
            "archive_commit_artifact_path_recorded",
            "archive_run_receipt_artifact_path_recorded",
            "archive_writer_output_artifact_path_recorded",
            "archive_postwrite_smoke_artifact_path_recorded",
            "archive_backup_artifact_path_recorded",
        )
        if archive[key]
    )
    return [
        {
            "key": "catalog_record_archive_summary_identity",
            "title": "Catalog record archive summary identity",
            "facts": [
                f"family={archive['writer_record_family'] or 'missing'}",
                f"record_key={archive['writer_catalog_record_key'] or 'missing'}",
                f"statement_count={archive['writer_statement_count']}",
            ],
        },
        {
            "key": "catalog_record_archive_summary_traceability",
            "title": "Catalog record archive summary traceability",
            "facts": [
                f"artifact_path_count={artifact_count}",
                f"archive_passed={archive['archive_passed']}",
                f"summary_path={operator['report_catalog_record_archive_summary_artifact_path'] or 'missing'}",
            ],
        },
        {
            "key": "catalog_record_archive_summary_integrity",
            "title": "Catalog record archive summary integrity",
            "facts": [
                f"db_commit={archive['writer_database_commit_executed']}",
                f"smoke_passed={archive['smoke_postwrite_smoke_passed']}",
                f"manifest_reviewed={archive['operator_confirmed_archive_manifest_reviewed']}",
                f"retention_recorded={archive['operator_confirmed_archive_retention_policy_recorded']}",
            ],
        },
        {
            "key": "catalog_record_archive_summary_safety",
            "title": "Catalog record archive summary safety",
            "facts": [
                "report_generated=false",
                "api_cli_executed=false",
                "api_database_write_executed=false",
                "catalog_record_archive_summary_executed=false",
                "scheduler_attached=false",
            ],
        },
    ]


def _summary_gates(archive, operator, apply_real_write):
    return [
        {
            "key": "report_catalog_record_archive_passed",
            "label": "上一關 report catalog record archive gate 已通過",
            "passed": bool(
                archive["provided"]
                and archive["mode"]
                == "candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_catalog_record_archive_preview"
                and archive["archive_passed"]
                and archive["ready_for_next_manual_phase"]
                and archive["ready_for_market_intel_report_catalog_record_archive_summary"]
                and not archive["ready_for_market_intel_report_catalog_record_archive"]
            ),
        },
        {
            "key": "report_catalog_record_archive_catalog_record_evidence_retained",
            "label": "archive payload 保留 catalog record identity、DB commit 與 post-write smoke 證據",
            "passed": bool(
                archive["writer_catalog_record_key"]
                and archive["writer_target_table"] == TARGET_TABLE
                and archive["writer_target_column"] == TARGET_COLUMN
                and archive["writer_statement_count"] > 0
                and archive["writer_database_commit_executed"]
                and archive["writer_hash_match"]
                and archive["smoke_read_only_query_executed"]
                and archive["smoke_postwrite_smoke_passed"]
                and archive["smoke_hash_match"]
            ),
        },
        {
            "key": "report_catalog_record_archive_artifacts_verified",
            "label": "archive payload 保留 closeout、commit、run receipt、writer output、post-write smoke、backup 與 archive artifact trace",
            "passed": bool(
                archive["closeout_passed"]
                and archive["closeout_artifact_path_recorded"]
                and archive["commit_artifact_path_recorded"]
                and archive["run_receipt_artifact_path_recorded"]
                and archive["writer_output_artifact_path_recorded"]
                and archive["postwrite_smoke_artifact_path_recorded"]
                and archive["backup_artifact_path_recorded"]
                and archive["archive_artifact_path"]
                and archive["archive_closeout_artifact_path_recorded"]
                and archive["archive_commit_artifact_path_recorded"]
                and archive["archive_run_receipt_artifact_path_recorded"]
                and archive["archive_writer_output_artifact_path_recorded"]
                and archive["archive_postwrite_smoke_artifact_path_recorded"]
                and archive["archive_backup_artifact_path_recorded"]
            ),
        },
        {
            "key": "report_catalog_record_archive_operator_evidence_retained",
            "label": "archive payload 保留操作員 archive、manifest、retention policy 與 archive summary separate gate 確認",
            "passed": bool(
                archive["operator_confirmed_archive_gate"]
                and archive["operator_confirmed_closeout_reviewed"]
                and archive["operator_confirmed_db_commit_observed"]
                and archive["operator_confirmed_no_followup_db_write_required"]
                and archive["operator_confirmed_archive_manifest_reviewed"]
                and archive["operator_confirmed_archive_retention_policy_recorded"]
                and archive["operator_confirmed_archive_summary_requires_separate_gate"]
            ),
        },
        {
            "key": "report_catalog_record_archive_promotion_gate",
            "label": "archive promotion gate 僅放行到 catalog record archive summary 且要求獨立 gate",
            "passed": bool(
                archive["promotion_allowed"]
                and archive["promotion_next_manual_phase"]
                == "market_intel_report_catalog_record_archive_summary"
                and archive["promotion_archive_summary_separate_gate"]
                and archive["promotion_api_must_not_generate_report"]
                and archive["promotion_api_must_not_write_file"]
                and archive["promotion_api_must_not_execute_cli"]
                and archive["promotion_api_must_not_write_catalog_record"]
                and archive["promotion_api_must_not_write_database"]
                and archive["promotion_api_must_not_commit_catalog_record"]
                and archive["promotion_api_must_not_dispatch_telegram"]
            ),
        },
        {
            "key": "report_catalog_record_archive_api_side_effects_blocked",
            "label": "上一關 archive top-level API 沒有執行 CLI、寫檔、寫 DB、commit、派 Telegram 或掛 scheduler",
            "passed": bool(
                not archive["api_executes_cli"]
                and not archive["api_writes_file"]
                and not archive["api_writes_database"]
                and not archive["api_dispatches_telegram"]
                and not archive["database_write_executed"]
                and not archive["catalog_record_archive_executed"]
                and not archive["scheduler_attached"]
                and not archive["blocked_response_keys_true"]
            ),
        },
        {
            "key": "report_catalog_record_archive_safe_boundaries_complete",
            "label": "上一關 archive safe boundaries 完整且未夾帶 token key",
            "passed": bool(
                archive["safe_boundaries_complete"]
                and not archive["forbidden_token_key_detected"]
            ),
        },
        {
            "key": "report_catalog_record_archive_summary_operator_confirmed",
            "label": "操作員確認 archive summary gate、完整 traceability、read-only summary 與 final closeout separate gate",
            "passed": bool(
                operator["report_catalog_record_archive_summary_artifact_path"]
                and operator["report_catalog_record_archive_artifact_path_recorded"]
                and operator["report_catalog_record_closeout_artifact_path_recorded"]
                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_archive_summary_gate"
                ]
                and operator[
                    "operator_confirmed_report_catalog_record_archive_reviewed"
                ]
                and operator["operator_confirmed_catalog_record_traceability_reviewed"]
                and operator[
                    "operator_confirmed_catalog_record_archive_summary_read_only"
                ]
                and operator[
                    "operator_confirmed_catalog_record_final_closeout_requires_separate_gate"
                ]
            ),
        },
        {
            "key": "report_catalog_record_archive_summary_runtime_boundaries_confirmed",
            "label": "操作員確認本 API 不產報表、不寫檔、不執行 CLI、不寫 DB、不派 Telegram、不呼叫 LLM、不掛 scheduler",
            "passed": bool(
                operator[
                    "operator_confirmed_no_token_in_report_catalog_record_archive_summary"
                ]
                and operator["operator_confirmed_no_api_report_generation"]
                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_archive_summary_no_token_submitted_to_api",
            "label": "archive summary gate payload 不得包含 approval 或 Telegram token key",
            "passed": not operator["forbidden_token_submitted_to_api"],
        },
        {
            "key": "report_catalog_record_archive_summary_apply_real_write_not_requested_from_api",
            "label": "API/UI report catalog record archive summary gate 不接受 apply_real_write",
            "passed": not apply_real_write,
        },
    ]


def build_candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_catalog_record_archive_summary(
    *,
    telegram_dispatch_report_catalog_record_archive,
    report_catalog_record_archive_summary=None,
    operator_evidence=None,
    execute_requested=False,
    apply_real_write=False,
):
    """建立 Telegram dispatch report catalog record archive summary gate；不執行副作用。"""
    archive = _archive_summary(telegram_dispatch_report_catalog_record_archive)
    operator = _operator_summary(operator_evidence, report_catalog_record_archive_summary)
    sections = _summary_sections(archive, operator)
    gates = _summary_gates(archive, operator, bool(apply_real_write))
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    summary_passed = bool(not blocked_reasons)

    return {
        "mode": "candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_catalog_record_archive_summary_preview",
        "target_table": TARGET_TABLE,
        "target_column": TARGET_COLUMN,
        "target_json_path": [
            "market_intel_ai_summary",
            "telegram_dispatch_report_catalog_record_archive_summary",
        ],
        "target_operation": "summarize_manual_market_intel_report_catalog_record_archive",
        "execute_requested": bool(execute_requested),
        "apply_real_write_requested": bool(apply_real_write),
        "report_catalog_record_archive_summary_reviewed": True,
        "telegram_dispatch_report_catalog_record_archive_summary_passed": summary_passed,
        "summary_persistence_telegram_dispatch_report_catalog_record_archive_summary_passed": summary_passed,
        "report_catalog_record_archive_summary_passed": summary_passed,
        "ready_for_next_manual_phase": summary_passed,
        "ready_for_market_intel_report_catalog_record_final_closeout": summary_passed,
        "ready_for_market_intel_report_catalog_record_archive_summary": False,
        "ready_for_market_intel_report_catalog_record_archive": False,
        "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": archive["writer_statement_count"] or archive["statement_count"],
        "expected_summary_payload_hash": archive["expected_summary_payload_hash"],
        "blocked_reasons": blocked_reasons,
        "gates": gates,
        "telegram_dispatch_report_catalog_record_archive": archive,
        "telegram_dispatch_report_catalog_record_archive_summary_sections": sections,
        "operator_telegram_dispatch_report_catalog_record_archive_summary": operator,
        "promotion_gate": {
            "allowed": summary_passed,
            "next_manual_phase": "market_intel_report_catalog_record_final_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_final_closeout_requires_separate_gate": True,
        },
        "next_operator_steps": [
            "保存 report catalog record archive summary artifact path",
            "確認 archive summary 只整理 catalog record identity、traceability、integrity 與 runtime safety",
            "只在 archive summary gate 通過後進入 report catalog record final closeout gate",
            "不得從 API/UI 產報表、寫檔、補寫 catalog record、commit、派送 Telegram 或掛 scheduler",
        ],
        "safe_boundaries": [
            "do_not_read_approval_token_from_report_catalog_record_archive_summary_api",
            "do_not_read_telegram_token_from_report_catalog_record_archive_summary_api",
            "do_not_call_llm_from_report_catalog_record_archive_summary",
            "do_not_generate_report_from_report_catalog_record_archive_summary_api",
            "do_not_write_report_catalog_record_archive_summary_artifact_from_api",
            "do_not_execute_catalog_record_cli_from_report_catalog_record_archive_summary_api",
            "do_not_write_report_catalog_record_from_report_catalog_record_archive_summary_api",
            "do_not_commit_catalog_record_from_report_catalog_record_archive_summary_api",
            "do_not_dispatch_telegram_from_report_catalog_record_archive_summary_api",
            "do_not_open_database_connection_from_report_catalog_record_archive_summary",
            "do_not_update_review_state_from_report_catalog_record_archive_summary",
            "do_not_attach_scheduler_from_report_catalog_record_archive_summary",
            "future_market_intel_report_catalog_record_final_closeout_must_use_separate_gate",
            "report_catalog_record_archive_summary_preview_only",
            "no_remove_orphans",
            "no_momo_db_lifecycle_change",
        ],
    }
