"""候選審核 queue AI summary Telegram dispatch report catalog index preview。

本模組只在 report catalog handoff 通過後整理 catalog index 契約；
不讀 approval 或 Telegram token、不呼叫 LLM、不補產報表、不派送 Telegram、
不開 DB、不寫檔、不寫 catalog record、不更新 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_handoff import (
    FALSE_RESPONSE_KEYS as REPORT_CATALOG_HANDOFF_FALSE_RESPONSE_KEYS,
)


REQUIRED_CATALOG_HANDOFF_BOUNDARIES = {
    "do_not_read_approval_token_from_report_catalog_handoff_api",
    "do_not_read_telegram_token_from_report_catalog_handoff_api",
    "do_not_call_llm_from_report_catalog_handoff",
    "do_not_generate_report_from_report_catalog_handoff_api",
    "do_not_write_report_catalog_handoff_artifact_from_api",
    "do_not_write_report_catalog_record_from_api",
    "do_not_dispatch_telegram_from_report_catalog_handoff_api",
    "do_not_open_database_connection_from_report_catalog_handoff",
    "do_not_update_review_state_from_report_catalog_handoff",
    "do_not_attach_scheduler_from_report_catalog_handoff",
    "future_market_intel_report_catalog_index_must_use_separate_gate",
}
FALSE_RESPONSE_KEYS = tuple(
    dict.fromkeys(
        REPORT_CATALOG_HANDOFF_FALSE_RESPONSE_KEYS
        + (
            "telegram_dispatch_report_catalog_index_file_written",
            "report_catalog_index_file_written",
            "catalog_index_file_written",
            "report_catalog_index_manifest_written",
            "catalog_index_manifest_written",
            "catalog_manifest_written",
            "catalog_record_written",
            "report_catalog_record_written",
            "report_catalog_write_preflight_file_written",
            "catalog_record_write_preflight_file_written",
            "report_catalog_record_write_file_written",
        )
    )
)


def _catalog_handoff_index(telegram_dispatch_report_catalog_handoff):
    handoff_payload = _as_dict(telegram_dispatch_report_catalog_handoff)
    handoff_summary = _as_dict(
        handoff_payload.get("telegram_dispatch_report_archive_summary")
    )
    operator_handoff = _as_dict(
        handoff_payload.get("operator_telegram_dispatch_report_catalog_handoff")
    )
    promotion = _as_dict(handoff_payload.get("promotion_gate"))
    sections = _as_list(
        handoff_payload.get("telegram_dispatch_report_catalog_handoff_sections")
    )
    safe_boundaries = set(
        str(item) for item in _as_list(handoff_payload.get("safe_boundaries"))
    )
    missing_boundaries = sorted(REQUIRED_CATALOG_HANDOFF_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(handoff_payload),
        "mode": handoff_payload.get("mode"),
        "target_operation": handoff_payload.get("target_operation"),
        "catalog_handoff_passed": bool(
            handoff_payload.get("telegram_dispatch_report_catalog_handoff_passed")
            or handoff_payload.get(
                "summary_persistence_telegram_dispatch_report_catalog_handoff_passed"
            )
            or handoff_payload.get("report_catalog_handoff_passed")
        ),
        "ready_for_market_intel_report_catalog_index": bool(
            handoff_payload.get("ready_for_market_intel_report_catalog_index")
        ),
        "ready_for_next_manual_phase": bool(
            handoff_payload.get("ready_for_next_manual_phase")
        ),
        "statement_count": _safe_int(handoff_payload.get("statement_count")),
        "expected_summary_payload_hash": _safe_text(
            handoff_payload.get("expected_summary_payload_hash"),
            80,
        ),
        "target_report_family": handoff_summary.get("target_report_family"),
        "language": handoff_summary.get("language"),
        "report_output_artifact_path": handoff_summary.get(
            "report_output_artifact_path"
        ),
        "report_output_hash": handoff_summary.get("report_output_hash"),
        "summary_payload_hash": handoff_summary.get("summary_payload_hash"),
        "summary_payload_hash_matches_expected": bool(
            handoff_summary.get("summary_payload_hash_matches_expected")
        ),
        "required_report_sections_present": bool(
            handoff_summary.get("required_report_sections_present")
        ),
        "section_keys": section_keys,
        "section_count": len(section_keys),
        "report_catalog_handoff_artifact_path": operator_handoff.get(
            "report_catalog_handoff_artifact_path"
        ),
        "report_archive_summary_artifact_path_recorded": bool(
            operator_handoff.get("report_archive_summary_artifact_path_recorded")
        ),
        "report_archive_artifact_path_recorded": bool(
            operator_handoff.get("report_archive_artifact_path_recorded")
        ),
        "report_output_artifact_path_recorded": bool(
            operator_handoff.get("report_output_artifact_path_recorded")
        ),
        "catalog_record_key_recorded": bool(
            operator_handoff.get("catalog_record_key_recorded")
        ),
        "catalog_family_recorded": bool(
            operator_handoff.get("catalog_family_recorded")
        ),
        "operator_confirmed_report_catalog_handoff": bool(
            operator_handoff.get("operator_confirmed_report_catalog_handoff")
        ),
        "operator_confirmed_catalog_handoff_is_read_only": bool(
            operator_handoff.get("operator_confirmed_catalog_handoff_is_read_only")
        ),
        "operator_confirmed_report_archive_summary_reviewed": bool(
            operator_handoff.get(
                "operator_confirmed_report_archive_summary_reviewed"
            )
        ),
        "operator_confirmed_catalog_identity_reviewed": bool(
            operator_handoff.get("operator_confirmed_catalog_identity_reviewed")
        ),
        "operator_confirmed_report_catalog_index_requires_separate_gate": bool(
            operator_handoff.get(
                "operator_confirmed_report_catalog_index_requires_separate_gate"
            )
        ),
        "promotion_allowed": bool(promotion.get("allowed")),
        "promotion_next_manual_phase": promotion.get("next_manual_phase"),
        "promotion_catalog_index_separate_gate": bool(
            promotion.get("report_catalog_index_requires_separate_gate")
        ),
        "promotion_write_preflight_separate_gate": bool(
            promotion.get("report_catalog_write_preflight_requires_separate_gate")
        ),
        "safe_boundaries_complete": not missing_boundaries,
        "missing_safe_boundaries": missing_boundaries,
        "forbidden_token_key_detected": _contains_forbidden_token_key(
            _strip_safe_token_boolean_keys(handoff_payload)
        ),
        "blocked_count": len(_as_list(handoff_payload.get("blocked_reasons"))),
        **{key: bool(handoff_payload.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_index_artifact_path": _safe_text(
            operator_evidence.get("report_catalog_index_artifact_path")
            or operator_evidence.get("telegram_dispatch_report_catalog_index_artifact_path")
            or operator_evidence.get("market_intel_report_catalog_index_artifact_path")
        ),
        "report_catalog_handoff_artifact_path_recorded": _has_text(
            operator_evidence.get("report_catalog_handoff_artifact_path")
            or operator_evidence.get(
                "telegram_dispatch_report_catalog_handoff_artifact_path"
            )
        ),
        "report_archive_summary_artifact_path_recorded": _has_text(
            operator_evidence.get("report_archive_summary_artifact_path")
            or operator_evidence.get(
                "telegram_dispatch_report_archive_summary_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")
        ),
        "operator_confirmed_report_catalog_index": bool(
            operator_evidence.get("operator_confirmed_report_catalog_index")
            or operator_evidence.get("operator_confirmed_market_intel_report_catalog_index")
        ),
        "operator_confirmed_catalog_index_is_read_only": bool(
            operator_evidence.get("operator_confirmed_catalog_index_is_read_only")
            or operator_evidence.get("operator_confirmed_report_catalog_index_read_only")
        ),
        "operator_confirmed_report_catalog_handoff_reviewed": bool(
            operator_evidence.get("operator_confirmed_report_catalog_handoff_reviewed")
            or operator_evidence.get("operator_confirmed_report_catalog_handoff")
        ),
        "operator_confirmed_catalog_manifest_reviewed": bool(
            operator_evidence.get("operator_confirmed_catalog_manifest_reviewed")
            or operator_evidence.get("operator_confirmed_catalog_identity_reviewed")
        ),
        "operator_confirmed_report_catalog_write_preflight_requires_separate_gate": bool(
            operator_evidence.get(
                "operator_confirmed_report_catalog_write_preflight_requires_separate_gate"
            )
        ),
        "operator_confirmed_no_token_in_report_catalog_index": bool(
            operator_evidence.get("operator_confirmed_no_token_in_report_catalog_index")
            or operator_evidence.get("operator_confirmed_no_token_in_artifacts")
        ),
        "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")
        ),
        "operator_confirmed_no_api_file_write": bool(
            operator_evidence.get("operator_confirmed_no_api_file_write")
            or operator_evidence.get("operator_confirmed_no_catalog_index_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_index_notes_recorded": _has_text(
            operator_evidence.get("report_catalog_index_notes")
            or operator_evidence.get("catalog_index_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 _index_sections(summary):
    manifest_count = sum(
        1
        for key in (
            "report_catalog_handoff_artifact_path",
            "report_archive_summary_artifact_path_recorded",
            "report_output_artifact_path_recorded",
            "catalog_record_key_recorded",
            "catalog_family_recorded",
        )
        if summary[key]
    )
    return [
        {
            "key": "catalog_index_identity",
            "title": "Catalog index identity",
            "facts": [
                f"family={summary['target_report_family'] or 'missing'}",
                f"language={summary['language'] or 'missing'}",
                f"catalog_family_recorded={summary['catalog_family_recorded']}",
            ],
        },
        {
            "key": "catalog_source_trace",
            "title": "Catalog source trace",
            "facts": [
                f"handoff_passed={summary['catalog_handoff_passed']}",
                f"handoff_path={summary['report_catalog_handoff_artifact_path'] or 'missing'}",
                f"summary_hash={summary['expected_summary_payload_hash'] or 'missing'}",
            ],
        },
        {
            "key": "index_manifest",
            "title": "Index manifest",
            "facts": [
                f"manifest_count={manifest_count}",
                f"section_count={summary['section_count']}",
                f"report_hash={summary['report_output_hash'] or 'missing'}",
            ],
        },
        {
            "key": "runtime_safety",
            "title": "Runtime safety",
            "facts": [
                "catalog_index_written=false",
                "catalog_record_written=false",
                "database_write_executed=false",
                "telegram_dispatched=false",
                "scheduler_attached=false",
            ],
        },
    ]


def _index_gates(summary, operator, apply_real_write):
    return [
        {
            "key": "report_catalog_handoff_preview_provided",
            "label": "必須提供上一階段 report catalog handoff preview",
            "passed": bool(
                summary["provided"]
                and summary["mode"]
                == "candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_catalog_handoff_preview"
            ),
        },
        {
            "key": "report_catalog_handoff_passed",
            "label": "report catalog handoff 必須已通過",
            "passed": summary["catalog_handoff_passed"],
        },
        {
            "key": "report_catalog_handoff_ready_for_index",
            "label": "catalog handoff 只能放行到 catalog index",
            "passed": bool(
                summary["ready_for_market_intel_report_catalog_index"]
                and summary["ready_for_next_manual_phase"]
                and summary["promotion_allowed"]
                and summary["promotion_next_manual_phase"]
                == "market_intel_report_catalog_index"
                and summary["promotion_catalog_index_separate_gate"]
                and summary["promotion_write_preflight_separate_gate"]
            ),
        },
        {
            "key": "catalog_index_traceability_complete",
            "label": "catalog index 必須保留 catalog identity、handoff artifact、section keys 與 hash trace",
            "passed": bool(
                summary["target_report_family"]
                and summary["report_output_artifact_path"]
                and summary["report_output_hash"]
                and summary["summary_payload_hash_matches_expected"]
                and summary["required_report_sections_present"]
                and summary["section_count"] >= 4
                and summary["report_catalog_handoff_artifact_path"]
                and summary["report_archive_summary_artifact_path_recorded"]
                and summary["report_output_artifact_path_recorded"]
                and summary["catalog_record_key_recorded"]
                and summary["catalog_family_recorded"]
                and summary["operator_confirmed_report_catalog_handoff"]
                and summary["operator_confirmed_catalog_handoff_is_read_only"]
                and summary["operator_confirmed_report_archive_summary_reviewed"]
                and summary["operator_confirmed_catalog_identity_reviewed"]
                and summary["operator_confirmed_report_catalog_index_requires_separate_gate"]
            ),
        },
        {
            "key": "report_catalog_handoff_runtime_boundaries_clear",
            "label": "handoff payload 不得顯示 API 產報表、寫檔、DB、Telegram、LLM 或 scheduler 副作用",
            "passed": all(not summary[key] for key in FALSE_RESPONSE_KEYS),
        },
        {
            "key": "report_catalog_handoff_safe_boundaries_complete",
            "label": "catalog handoff 必須保留 catalog index separate gate 與 runtime 安全邊界",
            "passed": summary["safe_boundaries_complete"],
        },
        {
            "key": "operator_confirmed_report_catalog_index",
            "label": "操作員確認 catalog index 只整理索引契約，且 catalog write preflight 另開 gate",
            "passed": bool(
                operator["report_catalog_index_artifact_path"]
                and operator["report_catalog_handoff_artifact_path_recorded"]
                and operator["report_archive_summary_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["operator_confirmed_report_catalog_index"]
                and operator["operator_confirmed_catalog_index_is_read_only"]
                and operator["operator_confirmed_report_catalog_handoff_reviewed"]
                and operator["operator_confirmed_catalog_manifest_reviewed"]
                and operator[
                    "operator_confirmed_report_catalog_write_preflight_requires_separate_gate"
                ]
            ),
        },
        {
            "key": "operator_confirmed_report_catalog_index_runtime_boundaries",
            "label": "操作員確認本 API 不產報表、不寫檔、不派送 Telegram、不寫 DB、不呼叫 LLM、不掛 scheduler",
            "passed": bool(
                operator["operator_confirmed_no_token_in_report_catalog_index"]
                and operator["operator_confirmed_no_api_report_generation"]
                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_index_no_token_submitted_to_api",
            "label": "catalog index payload 不得包含 approval 或 Telegram token key",
            "passed": not operator["forbidden_token_submitted_to_api"]
            and not summary["forbidden_token_key_detected"],
        },
        {
            "key": "report_catalog_index_apply_real_write_not_requested_from_api",
            "label": "API/UI report catalog index 不接受 apply_real_write",
            "passed": not apply_real_write,
        },
    ]


def build_candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_catalog_index(
    *,
    telegram_dispatch_report_catalog_handoff,
    operator_evidence=None,
    execute_requested=False,
    apply_real_write=False,
):
    """建立 Telegram dispatch report catalog index gate；不執行任何副作用。"""
    summary = _catalog_handoff_index(telegram_dispatch_report_catalog_handoff)
    operator = _operator_summary(operator_evidence)
    sections = _index_sections(summary)
    gates = _index_gates(summary, operator, bool(apply_real_write))
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    index_passed = bool(not blocked_reasons)

    return {
        "mode": "candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_catalog_index_preview",
        "target_table": TARGET_TABLE,
        "target_column": TARGET_COLUMN,
        "target_json_path": [
            "market_intel_ai_summary",
            "telegram_dispatch_report_catalog_index",
        ],
        "target_operation": "index_archived_market_intel_report_catalog_handoff",
        "execute_requested": bool(execute_requested),
        "apply_real_write_requested": bool(apply_real_write),
        "report_catalog_index_reviewed": True,
        "telegram_dispatch_report_catalog_index_passed": index_passed,
        "summary_persistence_telegram_dispatch_report_catalog_index_passed": index_passed,
        "report_catalog_index_passed": index_passed,
        "ready_for_next_manual_phase": index_passed,
        "ready_for_market_intel_report_catalog_write_preflight": index_passed,
        "ready_for_market_intel_report_catalog_record_write": 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_handoff": summary,
        "telegram_dispatch_report_catalog_index_sections": sections,
        "operator_telegram_dispatch_report_catalog_index": operator,
        "promotion_gate": {
            "allowed": index_passed,
            "next_manual_phase": "market_intel_report_catalog_write_preflight",
            "requires_real_db_write": False,
            "requires_scheduler_attach": False,
            "requires_operator_approval": True,
            "api_must_not_generate_report": True,
            "api_must_not_write_catalog_index_file": True,
            "api_must_not_write_catalog_record": True,
            "api_must_not_dispatch_telegram": True,
            "report_catalog_write_preflight_requires_separate_gate": True,
            "report_catalog_record_write_requires_separate_gate": True,
        },
        "next_operator_steps": [
            "保存 report catalog index artifact path",
            "確認 catalog index key、catalog family、handoff artifact 與 report hash trace 可被 write preflight 引用",
            "下一階段 report catalog write preflight 必須另開 gate；本 API 不寫檔、不寫 catalog record",
            "若任何 catalog index gate 阻擋，停在 report catalog handoff 階段並保留 feature flags 關閉",
        ],
        "safe_boundaries": [
            "do_not_read_approval_token_from_report_catalog_index_api",
            "do_not_read_telegram_token_from_report_catalog_index_api",
            "do_not_call_llm_from_report_catalog_index",
            "do_not_generate_report_from_report_catalog_index_api",
            "do_not_write_report_catalog_index_artifact_from_api",
            "do_not_write_report_catalog_record_from_api",
            "do_not_dispatch_telegram_from_report_catalog_index_api",
            "do_not_open_database_connection_from_report_catalog_index",
            "do_not_update_review_state_from_report_catalog_index",
            "do_not_attach_scheduler_from_report_catalog_index",
            "future_market_intel_report_catalog_write_preflight_must_use_separate_gate",
            "report_catalog_index_preview_only",
            "no_remove_orphans",
            "no_momo_db_lifecycle_change",
        ],
    }
