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

本模組只檢查 report catalog record 寫入前的 operator gate 與 traceability；
不讀 approval 或 Telegram token、不呼叫 LLM、不補產報表、不派送 Telegram、
不開 DB、不寫檔、不寫 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_write_preflight import (
    FALSE_RESPONSE_KEYS as REPORT_CATALOG_WRITE_PREFLIGHT_FALSE_RESPONSE_KEYS,
)


REQUIRED_CATALOG_WRITE_PREFLIGHT_BOUNDARIES = {
    "do_not_read_approval_token_from_report_catalog_write_preflight_api",
    "do_not_read_telegram_token_from_report_catalog_write_preflight_api",
    "do_not_call_llm_from_report_catalog_write_preflight",
    "do_not_generate_report_from_report_catalog_write_preflight_api",
    "do_not_write_report_catalog_write_preflight_artifact_from_api",
    "do_not_write_report_catalog_record_from_api",
    "do_not_dispatch_telegram_from_report_catalog_write_preflight_api",
    "do_not_open_database_connection_from_report_catalog_write_preflight",
    "do_not_update_review_state_from_report_catalog_write_preflight",
    "do_not_attach_scheduler_from_report_catalog_write_preflight",
    "future_market_intel_report_catalog_record_write_must_use_separate_gate",
}
FALSE_RESPONSE_KEYS = tuple(
    dict.fromkeys(
        REPORT_CATALOG_WRITE_PREFLIGHT_FALSE_RESPONSE_KEYS
        + (
            "telegram_dispatch_report_catalog_record_write_gate_file_written",
            "report_catalog_record_write_gate_file_written",
            "catalog_record_write_gate_file_written",
            "telegram_dispatch_report_catalog_record_run_package_file_written",
            "report_catalog_record_run_package_file_written",
            "catalog_record_run_package_file_written",
            "catalog_record_write_receipt_file_written",
            "catalog_record_postwrite_smoke_executed",
            "catalog_record_commit_executed",
        )
    )
)


def _catalog_record_write_preflight(telegram_dispatch_report_catalog_write_preflight):
    preflight = _as_dict(telegram_dispatch_report_catalog_write_preflight)
    index = _as_dict(preflight.get("telegram_dispatch_report_catalog_index"))
    operator_preflight = _as_dict(
        preflight.get("operator_telegram_dispatch_report_catalog_write_preflight")
    )
    promotion = _as_dict(preflight.get("promotion_gate"))
    sections = _as_list(
        preflight.get("telegram_dispatch_report_catalog_write_preflight_sections")
    )
    safe_boundaries = set(str(item) for item in _as_list(preflight.get("safe_boundaries")))
    missing_boundaries = sorted(
        REQUIRED_CATALOG_WRITE_PREFLIGHT_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(preflight),
        "mode": preflight.get("mode"),
        "target_operation": preflight.get("target_operation"),
        "catalog_write_preflight_passed": bool(
            preflight.get("telegram_dispatch_report_catalog_write_preflight_passed")
            or preflight.get(
                "summary_persistence_telegram_dispatch_report_catalog_write_preflight_passed"
            )
            or preflight.get("report_catalog_write_preflight_passed")
        ),
        "ready_for_next_manual_phase": bool(preflight.get("ready_for_next_manual_phase")),
        "ready_for_market_intel_report_catalog_record_write": bool(
            preflight.get("ready_for_market_intel_report_catalog_record_write")
        ),
        "ready_for_market_intel_report_catalog_record_commit": bool(
            preflight.get("ready_for_market_intel_report_catalog_record_commit")
        ),
        "statement_count": _safe_int(preflight.get("statement_count")),
        "expected_summary_payload_hash": _safe_text(
            preflight.get("expected_summary_payload_hash"),
            80,
        ),
        "target_report_family": index.get("target_report_family"),
        "language": index.get("language"),
        "report_output_artifact_path": index.get("report_output_artifact_path"),
        "report_output_hash": index.get("report_output_hash"),
        "report_catalog_index_artifact_path": index.get(
            "report_catalog_index_artifact_path"
        ),
        "catalog_record_key_recorded": bool(
            operator_preflight.get("catalog_record_key_recorded")
            or index.get("catalog_record_key_recorded")
        ),
        "catalog_family_recorded": bool(
            operator_preflight.get("catalog_family_recorded")
            or index.get("catalog_family_recorded")
        ),
        "catalog_index_key_recorded": bool(
            operator_preflight.get("catalog_index_key_recorded")
            or index.get("catalog_index_key_recorded")
        ),
        "catalog_record_schema_recorded": bool(
            operator_preflight.get("catalog_record_schema_recorded")
        ),
        "report_catalog_write_preflight_artifact_path": operator_preflight.get(
            "report_catalog_write_preflight_artifact_path"
        ),
        "report_catalog_index_artifact_path_recorded": bool(
            operator_preflight.get("report_catalog_index_artifact_path_recorded")
        ),
        "report_catalog_handoff_artifact_path_recorded": bool(
            operator_preflight.get("report_catalog_handoff_artifact_path_recorded")
        ),
        "report_output_artifact_path_recorded": bool(
            operator_preflight.get("report_output_artifact_path_recorded")
        ),
        "operator_confirmed_report_catalog_write_preflight": bool(
            operator_preflight.get("operator_confirmed_report_catalog_write_preflight")
        ),
        "operator_confirmed_catalog_write_preflight_is_read_only": bool(
            operator_preflight.get("operator_confirmed_catalog_write_preflight_is_read_only")
        ),
        "operator_confirmed_report_catalog_index_reviewed": bool(
            operator_preflight.get("operator_confirmed_report_catalog_index_reviewed")
        ),
        "operator_confirmed_catalog_record_schema_reviewed": bool(
            operator_preflight.get("operator_confirmed_catalog_record_schema_reviewed")
        ),
        "operator_confirmed_report_catalog_record_write_requires_separate_gate": bool(
            operator_preflight.get(
                "operator_confirmed_report_catalog_record_write_requires_separate_gate"
            )
        ),
        "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_record_write_separate_gate": bool(
            promotion.get("report_catalog_record_write_requires_separate_gate")
        ),
        "promotion_record_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(preflight)
        ),
        "blocked_count": len(_as_list(preflight.get("blocked_reasons"))),
        **{key: bool(preflight.get(key)) for key in FALSE_RESPONSE_KEYS},
    }


def _operator_summary(operator_evidence):
    operator_evidence = _as_dict(operator_evidence)
    return {
        "provided_keys": sorted(operator_evidence.keys()),
        "report_catalog_record_write_artifact_path": _safe_text(
            operator_evidence.get("report_catalog_record_write_artifact_path")
            or operator_evidence.get(
                "telegram_dispatch_report_catalog_record_write_artifact_path"
            )
            or operator_evidence.get("market_intel_report_catalog_record_write_artifact_path")
        ),
        "report_catalog_write_preflight_artifact_path_recorded": _has_text(
            operator_evidence.get("report_catalog_write_preflight_artifact_path")
            or operator_evidence.get(
                "telegram_dispatch_report_catalog_write_preflight_artifact_path"
            )
        ),
        "report_catalog_index_artifact_path_recorded": _has_text(
            operator_evidence.get("report_catalog_index_artifact_path")
            or operator_evidence.get(
                "telegram_dispatch_report_catalog_index_artifact_path"
            )
        ),
        "report_output_artifact_path_recorded": _has_text(
            operator_evidence.get("report_output_artifact_path")
            or operator_evidence.get("telegram_dispatch_report_output_artifact_path")
        ),
        "catalog_record_key_recorded": _has_text(
            operator_evidence.get("catalog_record_key")
            or operator_evidence.get("report_catalog_key")
        ),
        "catalog_family_recorded": _has_text(
            operator_evidence.get("catalog_family")
            or operator_evidence.get("report_catalog_family")
        ),
        "catalog_index_key_recorded": _has_text(
            operator_evidence.get("catalog_index_key")
            or operator_evidence.get("report_catalog_index_key")
        ),
        "catalog_record_schema_recorded": _has_text(
            operator_evidence.get("catalog_record_schema")
            or operator_evidence.get("report_catalog_record_schema")
        ),
        "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")
        ),
        "operator_confirmed_report_catalog_record_write": bool(
            operator_evidence.get("operator_confirmed_report_catalog_record_write")
            or operator_evidence.get(
                "operator_confirmed_market_intel_report_catalog_record_write"
            )
        ),
        "operator_confirmed_catalog_record_write_is_cli_only": bool(
            operator_evidence.get("operator_confirmed_catalog_record_write_is_cli_only")
            or operator_evidence.get("operator_confirmed_report_catalog_record_cli_only")
        ),
        "operator_confirmed_catalog_record_write_dry_run_reviewed": bool(
            operator_evidence.get(
                "operator_confirmed_catalog_record_write_dry_run_reviewed"
            )
            or operator_evidence.get("operator_confirmed_record_writer_dry_run_reviewed")
        ),
        "operator_confirmed_catalog_record_backup_required": bool(
            operator_evidence.get("operator_confirmed_catalog_record_backup_required")
            or operator_evidence.get("operator_confirmed_backup_before_catalog_record_write")
        ),
        "operator_confirmed_report_catalog_record_commit_requires_separate_gate": bool(
            operator_evidence.get(
                "operator_confirmed_report_catalog_record_commit_requires_separate_gate"
            )
        ),
        "operator_confirmed_postwrite_smoke_required": bool(
            operator_evidence.get("operator_confirmed_postwrite_smoke_required")
            or operator_evidence.get(
                "operator_confirmed_catalog_record_postwrite_smoke_required"
            )
        ),
        "operator_confirmed_no_token_in_report_catalog_record_write": bool(
            operator_evidence.get(
                "operator_confirmed_no_token_in_report_catalog_record_write"
            )
            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_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_write_notes_recorded": _has_text(
            operator_evidence.get("report_catalog_record_write_notes")
            or operator_evidence.get("catalog_record_write_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 _record_write_sections(summary):
    trace_refs = sum(
        1
        for key in (
            "report_catalog_write_preflight_artifact_path",
            "report_catalog_index_artifact_path",
            "report_output_artifact_path",
            "report_output_hash",
        )
        if summary[key]
    )
    return [
        {
            "key": "catalog_record_write_identity",
            "title": "Catalog record write identity",
            "facts": [
                f"family={summary['target_report_family'] or 'missing'}",
                f"catalog_key_recorded={summary['catalog_record_key_recorded']}",
                f"schema_recorded={summary['catalog_record_schema_recorded']}",
            ],
        },
        {
            "key": "catalog_record_write_trace",
            "title": "Catalog record write trace",
            "facts": [
                f"preflight_passed={summary['catalog_write_preflight_passed']}",
                f"trace_refs={trace_refs}",
                f"report_hash={summary['report_output_hash'] or 'missing'}",
            ],
        },
        {
            "key": "catalog_record_write_runtime_plan",
            "title": "Catalog record write runtime plan",
            "facts": [
                "api_write_executed=false",
                "manual_cli_required=true",
                "commit_requires_separate_gate=true",
            ],
        },
        {
            "key": "catalog_record_write_safety",
            "title": "Catalog record write safety",
            "facts": [
                "catalog_record_written=false",
                "database_write_executed=false",
                "telegram_dispatched=false",
                "scheduler_attached=false",
            ],
        },
    ]


def _record_write_gates(summary, operator, apply_real_write):
    return [
        {
            "key": "report_catalog_write_preflight_preview_provided",
            "label": "必須提供上一階段 report catalog write preflight preview",
            "passed": bool(
                summary["provided"]
                and summary["mode"]
                == "candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_catalog_write_preflight_preview"
            ),
        },
        {
            "key": "report_catalog_write_preflight_passed",
            "label": "report catalog write preflight 必須已通過",
            "passed": summary["catalog_write_preflight_passed"],
        },
        {
            "key": "report_catalog_write_preflight_ready_for_record_write",
            "label": "catalog write preflight 只能放行到 catalog record write",
            "passed": bool(
                summary["ready_for_market_intel_report_catalog_record_write"]
                and summary["ready_for_next_manual_phase"]
                and not summary["ready_for_market_intel_report_catalog_record_commit"]
                and summary["promotion_allowed"]
                and summary["promotion_next_manual_phase"]
                == "market_intel_report_catalog_record_write"
                and summary["promotion_requires_real_db_write"]
                and summary["promotion_record_write_separate_gate"]
                and summary["promotion_record_commit_separate_gate"]
            ),
        },
        {
            "key": "catalog_record_write_traceability_complete",
            "label": "catalog record write 必須保留 preflight、index、record key、schema 與 report hash trace",
            "passed": bool(
                summary["target_report_family"]
                and summary["report_output_artifact_path"]
                and summary["report_output_hash"]
                and summary["report_catalog_index_artifact_path"]
                and summary["report_catalog_write_preflight_artifact_path"]
                and summary["report_catalog_index_artifact_path_recorded"]
                and summary["report_output_artifact_path_recorded"]
                and summary["catalog_record_key_recorded"]
                and summary["catalog_family_recorded"]
                and summary["catalog_index_key_recorded"]
                and summary["catalog_record_schema_recorded"]
                and summary["operator_confirmed_report_catalog_write_preflight"]
                and summary["operator_confirmed_catalog_write_preflight_is_read_only"]
                and summary["operator_confirmed_report_catalog_index_reviewed"]
                and summary["operator_confirmed_catalog_record_schema_reviewed"]
                and summary[
                    "operator_confirmed_report_catalog_record_write_requires_separate_gate"
                ]
            ),
        },
        {
            "key": "report_catalog_write_preflight_runtime_boundaries_clear",
            "label": "preflight payload 不得顯示 API 寫檔、DB、Telegram、LLM 或 scheduler 副作用",
            "passed": all(not summary[key] for key in FALSE_RESPONSE_KEYS),
        },
        {
            "key": "report_catalog_write_preflight_safe_boundaries_complete",
            "label": "write preflight 必須保留 record write separate gate 與 runtime 安全邊界",
            "passed": summary["safe_boundaries_complete"],
        },
        {
            "key": "operator_confirmed_report_catalog_record_write",
            "label": "操作員確認 catalog record write 僅允許後續 CLI gate，且 commit 另開 gate",
            "passed": bool(
                operator["report_catalog_record_write_artifact_path"]
                and operator["report_catalog_write_preflight_artifact_path_recorded"]
                and operator["report_catalog_index_artifact_path_recorded"]
                and operator["report_output_artifact_path_recorded"]
                and operator["catalog_record_key_recorded"]
                and operator["catalog_family_recorded"]
                and operator["catalog_index_key_recorded"]
                and operator["catalog_record_schema_recorded"]
                and operator["catalog_record_backup_artifact_path_recorded"]
                and operator["catalog_record_write_dry_run_artifact_path_recorded"]
                and operator["operator_confirmed_report_catalog_record_write"]
                and operator["operator_confirmed_catalog_record_write_is_cli_only"]
                and operator["operator_confirmed_catalog_record_write_dry_run_reviewed"]
                and operator["operator_confirmed_catalog_record_backup_required"]
                and operator[
                    "operator_confirmed_report_catalog_record_commit_requires_separate_gate"
                ]
                and operator["operator_confirmed_postwrite_smoke_required"]
            ),
        },
        {
            "key": "operator_confirmed_report_catalog_record_write_runtime_boundaries",
            "label": "操作員確認本 API 不寫檔、不寫 DB、不派送 Telegram、不呼叫 LLM、不掛 scheduler",
            "passed": bool(
                operator["operator_confirmed_no_token_in_report_catalog_record_write"]
                and operator["operator_confirmed_no_api_file_write"]
                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_write_no_token_submitted_to_api",
            "label": "catalog record write payload 不得包含 approval 或 Telegram token key",
            "passed": not operator["forbidden_token_submitted_to_api"]
            and not summary["forbidden_token_key_detected"],
        },
        {
            "key": "report_catalog_record_write_apply_real_write_not_requested_from_api",
            "label": "API/UI report catalog record write gate 不接受 apply_real_write",
            "passed": not apply_real_write,
        },
    ]


def build_candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_catalog_record_write(
    *,
    telegram_dispatch_report_catalog_write_preflight,
    operator_evidence=None,
    execute_requested=False,
    apply_real_write=False,
):
    """建立 Telegram dispatch report catalog record write gate；不執行副作用。"""
    summary = _catalog_record_write_preflight(
        telegram_dispatch_report_catalog_write_preflight
    )
    operator = _operator_summary(operator_evidence)
    sections = _record_write_sections(summary)
    gates = _record_write_gates(summary, operator, bool(apply_real_write))
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    record_write_passed = bool(not blocked_reasons)

    return {
        "mode": "candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_catalog_record_write_preview",
        "target_table": TARGET_TABLE,
        "target_column": TARGET_COLUMN,
        "target_json_path": [
            "market_intel_ai_summary",
            "telegram_dispatch_report_catalog_record_write",
        ],
        "target_operation": "gate_market_intel_report_catalog_record_write",
        "execute_requested": bool(execute_requested),
        "apply_real_write_requested": bool(apply_real_write),
        "report_catalog_record_write_reviewed": True,
        "telegram_dispatch_report_catalog_record_write_passed": record_write_passed,
        "summary_persistence_telegram_dispatch_report_catalog_record_write_passed": record_write_passed,
        "report_catalog_record_write_passed": record_write_passed,
        "ready_for_next_manual_phase": record_write_passed,
        "ready_for_market_intel_report_catalog_record_write": record_write_passed,
        "ready_for_market_intel_report_catalog_record_cli_run": record_write_passed,
        "ready_for_market_intel_report_catalog_record_commit": False,
        **{key: False for key in FALSE_RESPONSE_KEYS},
        "statement_count": summary["statement_count"],
        "expected_summary_payload_hash": summary["expected_summary_payload_hash"],
        "blocked_reasons": blocked_reasons,
        "gates": gates,
        "telegram_dispatch_report_catalog_write_preflight": summary,
        "telegram_dispatch_report_catalog_record_write_sections": sections,
        "operator_telegram_dispatch_report_catalog_record_write": operator,
        "promotion_gate": {
            "allowed": record_write_passed,
            "next_manual_phase": "market_intel_report_catalog_record_run_package",
            "requires_real_db_write": True,
            "requires_cli_run": True,
            "requires_scheduler_attach": False,
            "requires_operator_approval": True,
            "requires_postwrite_smoke": True,
            "api_must_not_generate_report": True,
            "api_must_not_write_file": True,
            "api_must_not_write_catalog_record": True,
            "api_must_not_write_database": True,
            "api_must_not_dispatch_telegram": True,
            "report_catalog_record_run_package_requires_separate_gate": True,
            "report_catalog_record_commit_requires_separate_gate": True,
        },
        "next_operator_steps": [
            "保存 report catalog record write gate artifact path",
            "確認 catalog record writer dry-run、backup artifact、record key/schema/hash trace",
            "下一階段 report catalog record run package 必須另開 gate；本 API 不寫檔、不寫 catalog record",
            "若任何 catalog record write gate 阻擋，停在 report catalog write preflight 階段並保留 feature flags 關閉",
        ],
        "safe_boundaries": [
            "do_not_read_approval_token_from_report_catalog_record_write_api",
            "do_not_read_telegram_token_from_report_catalog_record_write_api",
            "do_not_call_llm_from_report_catalog_record_write",
            "do_not_generate_report_from_report_catalog_record_write_api",
            "do_not_write_report_catalog_record_write_artifact_from_api",
            "do_not_write_report_catalog_record_from_api",
            "do_not_dispatch_telegram_from_report_catalog_record_write_api",
            "do_not_open_database_connection_from_report_catalog_record_write",
            "do_not_update_review_state_from_report_catalog_record_write",
            "do_not_attach_scheduler_from_report_catalog_record_write",
            "future_market_intel_report_catalog_record_run_package_must_use_separate_gate",
            "report_catalog_record_write_preview_only",
            "no_remove_orphans",
            "no_momo_db_lifecycle_change",
        ],
    }
