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

本模組只在 report archive summary 通過後整理 catalog/index handoff 契約；
不讀 approval 或 Telegram token、不呼叫 LLM、不補產報表、不派送 Telegram、
不開 DB、不寫檔、不更新 review_state、不掛 scheduler。
"""

from services.market_intel.candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_archive_summary import (
    FALSE_RESPONSE_KEYS as REPORT_ARCHIVE_SUMMARY_FALSE_RESPONSE_KEYS,
    REQUIRED_ARCHIVE_BOUNDARIES,
    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_SUMMARY_BOUNDARIES = {
    "do_not_read_approval_token_from_report_archive_summary_api",
    "do_not_read_telegram_token_from_report_archive_summary_api",
    "do_not_call_llm_from_report_archive_summary",
    "do_not_generate_report_from_report_archive_summary_api",
    "do_not_write_report_archive_summary_artifact_from_api",
    "do_not_dispatch_telegram_from_report_archive_summary_api",
    "do_not_open_database_connection_from_report_archive_summary",
    "do_not_update_review_state_from_report_archive_summary",
    "do_not_attach_scheduler_from_report_archive_summary",
    "future_market_intel_report_catalog_handoff_must_use_separate_gate",
}
FALSE_RESPONSE_KEYS = tuple(
    dict.fromkeys(
        REPORT_ARCHIVE_SUMMARY_FALSE_RESPONSE_KEYS
        + (
            "telegram_dispatch_report_catalog_handoff_file_written",
            "report_catalog_handoff_file_written",
            "catalog_handoff_file_written",
            "report_catalog_index_file_written",
            "catalog_index_written",
            "catalog_manifest_written",
            "catalog_record_written",
            "report_catalog_record_written",
            "report_archive_summary_catalog_handoff_file_written",
        )
    )
)


def _archive_summary_handoff(telegram_dispatch_report_archive_summary):
    summary_payload = _as_dict(telegram_dispatch_report_archive_summary)
    archive_summary = _as_dict(
        summary_payload.get("telegram_dispatch_report_archive_summary")
    )
    operator_summary = _as_dict(
        summary_payload.get("operator_telegram_dispatch_report_archive_summary")
    )
    promotion = _as_dict(summary_payload.get("promotion_gate"))
    sections = _as_list(
        summary_payload.get("telegram_dispatch_report_archive_summary_sections")
    )
    safe_boundaries = set(str(item) for item in _as_list(summary_payload.get("safe_boundaries")))
    missing_boundaries = sorted(REQUIRED_ARCHIVE_SUMMARY_BOUNDARIES - safe_boundaries)
    archive_safe_boundaries = set(_as_list(archive_summary.get("safe_boundaries")))
    missing_archive_boundaries = sorted(REQUIRED_ARCHIVE_BOUNDARIES - archive_safe_boundaries)
    section_keys = sorted(
        str(item.get("key"))
        for item in sections
        if isinstance(item, dict) and item.get("key")
    )

    return {
        "provided": bool(summary_payload),
        "mode": summary_payload.get("mode"),
        "target_operation": summary_payload.get("target_operation"),
        "archive_summary_passed": bool(
            summary_payload.get("telegram_dispatch_report_archive_summary_passed")
            or summary_payload.get("summary_persistence_telegram_dispatch_report_archive_summary_passed")
            or summary_payload.get("report_archive_summary_passed")
        ),
        "ready_for_market_intel_report_catalog_handoff": bool(
            summary_payload.get("ready_for_market_intel_report_catalog_handoff")
        ),
        "ready_for_next_manual_phase": bool(summary_payload.get("ready_for_next_manual_phase")),
        "statement_count": _safe_int(summary_payload.get("statement_count")),
        "expected_summary_payload_hash": _safe_text(
            summary_payload.get("expected_summary_payload_hash")
            or archive_summary.get("expected_summary_payload_hash"),
            80,
        ),
        "target_report_family": archive_summary.get("target_report_family"),
        "language": archive_summary.get("language"),
        "report_output_artifact_path": archive_summary.get("report_output_artifact_path"),
        "report_output_hash": archive_summary.get("report_output_hash"),
        "summary_payload_hash": archive_summary.get("summary_payload_hash"),
        "summary_payload_hash_matches_expected": bool(
            archive_summary.get("summary_payload_hash_matches_expected")
        ),
        "required_report_sections_present": bool(
            archive_summary.get("required_report_sections_present")
        ),
        "section_keys": section_keys,
        "section_count": len(section_keys),
        "report_archive_summary_artifact_path": operator_summary.get(
            "report_archive_summary_artifact_path"
        ),
        "report_archive_artifact_path_recorded": bool(
            operator_summary.get("report_archive_artifact_path_recorded")
        ),
        "report_closeout_artifact_path_recorded": bool(
            operator_summary.get("report_closeout_artifact_path_recorded")
        ),
        "report_run_receipt_artifact_path_recorded": bool(
            operator_summary.get("report_run_receipt_artifact_path_recorded")
        ),
        "report_output_artifact_path_recorded": bool(
            operator_summary.get("report_output_artifact_path_recorded")
        ),
        "operator_confirmed_report_archive_summary": bool(
            operator_summary.get("operator_confirmed_report_archive_summary")
        ),
        "operator_confirmed_summary_is_read_only": bool(
            operator_summary.get("operator_confirmed_summary_is_read_only")
        ),
        "operator_confirmed_report_archive_reviewed": bool(
            operator_summary.get("operator_confirmed_report_archive_reviewed")
        ),
        "operator_confirmed_report_traceability_reviewed": bool(
            operator_summary.get("operator_confirmed_report_traceability_reviewed")
        ),
        "operator_confirmed_report_catalog_handoff_requires_separate_gate": bool(
            operator_summary.get(
                "operator_confirmed_report_catalog_handoff_requires_separate_gate"
            )
        ),
        "promotion_allowed": bool(promotion.get("allowed")),
        "promotion_next_manual_phase": promotion.get("next_manual_phase"),
        "promotion_catalog_handoff_separate_gate": bool(
            promotion.get("report_catalog_handoff_requires_separate_gate")
        ),
        "safe_boundaries_complete": not missing_boundaries,
        "missing_safe_boundaries": missing_boundaries,
        "archive_safe_boundaries_complete": not missing_archive_boundaries,
        "missing_archive_safe_boundaries": missing_archive_boundaries,
        "forbidden_token_key_detected": _contains_forbidden_token_key(
            _strip_safe_token_boolean_keys(summary_payload)
        ),
        "blocked_count": len(_as_list(summary_payload.get("blocked_reasons"))),
        **{key: bool(summary_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_handoff_artifact_path": _safe_text(
            operator_evidence.get("report_catalog_handoff_artifact_path")
            or operator_evidence.get("telegram_dispatch_report_catalog_handoff_artifact_path")
            or operator_evidence.get("market_intel_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_archive_artifact_path_recorded": _has_text(
            operator_evidence.get("report_archive_artifact_path")
            or operator_evidence.get("telegram_dispatch_report_archive_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")
        ),
        "operator_confirmed_report_catalog_handoff": bool(
            operator_evidence.get("operator_confirmed_report_catalog_handoff")
            or operator_evidence.get("operator_confirmed_market_intel_report_catalog_handoff")
        ),
        "operator_confirmed_catalog_handoff_is_read_only": bool(
            operator_evidence.get("operator_confirmed_catalog_handoff_is_read_only")
            or operator_evidence.get("operator_confirmed_report_catalog_handoff_read_only")
        ),
        "operator_confirmed_report_archive_summary_reviewed": bool(
            operator_evidence.get("operator_confirmed_report_archive_summary_reviewed")
            or operator_evidence.get("operator_confirmed_report_archive_summary")
        ),
        "operator_confirmed_catalog_identity_reviewed": bool(
            operator_evidence.get("operator_confirmed_catalog_identity_reviewed")
            or operator_evidence.get("operator_confirmed_report_traceability_reviewed")
        ),
        "operator_confirmed_report_catalog_index_requires_separate_gate": bool(
            operator_evidence.get(
                "operator_confirmed_report_catalog_index_requires_separate_gate"
            )
        ),
        "operator_confirmed_no_token_in_report_catalog_handoff": bool(
            operator_evidence.get("operator_confirmed_no_token_in_report_catalog_handoff")
            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_handoff_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_handoff_notes_recorded": _has_text(
            operator_evidence.get("report_catalog_handoff_notes")
            or operator_evidence.get("catalog_handoff_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 _handoff_sections(summary):
    artifact_count = sum(
        1
        for key in (
            "report_archive_summary_artifact_path",
            "report_archive_artifact_path_recorded",
            "report_output_artifact_path_recorded",
        )
        if summary[key]
    )
    return [
        {
            "key": "catalog_identity",
            "title": "Catalog identity",
            "facts": [
                f"family={summary['target_report_family'] or 'missing'}",
                f"language={summary['language'] or 'missing'}",
                f"report_hash={summary['report_output_hash'] or 'missing'}",
            ],
        },
        {
            "key": "archive_summary_trace",
            "title": "Archive summary trace",
            "facts": [
                f"summary_passed={summary['archive_summary_passed']}",
                f"summary_hash={summary['expected_summary_payload_hash'] or 'missing'}",
                f"section_count={summary['section_count']}",
            ],
        },
        {
            "key": "artifact_manifest",
            "title": "Artifact manifest",
            "facts": [
                f"artifact_count={artifact_count}",
                f"archive_path_recorded={summary['report_archive_artifact_path_recorded']}",
                f"output_path_recorded={summary['report_output_artifact_path_recorded']}",
            ],
        },
        {
            "key": "runtime_safety",
            "title": "Runtime safety",
            "facts": [
                "report_generated=false",
                "file_written=false",
                "catalog_record_written=false",
                "database_write_executed=false",
                "telegram_dispatched=false",
            ],
        },
    ]


def _handoff_gates(summary, operator, apply_real_write):
    return [
        {
            "key": "report_archive_summary_preview_provided",
            "label": "必須提供上一階段 report archive summary preview",
            "passed": bool(
                summary["provided"]
                and summary["mode"]
                == "candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_archive_summary_preview"
            ),
        },
        {
            "key": "report_archive_summary_passed",
            "label": "report archive summary 必須已通過",
            "passed": summary["archive_summary_passed"],
        },
        {
            "key": "report_archive_summary_ready_for_catalog_handoff",
            "label": "report archive summary 只能放行到 catalog handoff",
            "passed": bool(
                summary["ready_for_market_intel_report_catalog_handoff"]
                and summary["ready_for_next_manual_phase"]
                and summary["promotion_allowed"]
                and summary["promotion_next_manual_phase"]
                == "market_intel_report_catalog_handoff"
                and summary["promotion_catalog_handoff_separate_gate"]
            ),
        },
        {
            "key": "catalog_handoff_traceability_complete",
            "label": "catalog handoff 必須保留 report identity、artifact path、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_archive_summary_artifact_path"]
                and summary["report_archive_artifact_path_recorded"]
                and summary["report_output_artifact_path_recorded"]
                and summary["operator_confirmed_report_archive_summary"]
                and summary["operator_confirmed_summary_is_read_only"]
                and summary["operator_confirmed_report_archive_reviewed"]
                and summary["operator_confirmed_report_traceability_reviewed"]
            ),
        },
        {
            "key": "report_archive_summary_runtime_boundaries_clear",
            "label": "summary payload 不得顯示 API 產報表、寫檔、DB、Telegram、LLM 或 scheduler 副作用",
            "passed": all(not summary[key] for key in FALSE_RESPONSE_KEYS),
        },
        {
            "key": "report_archive_summary_safe_boundaries_complete",
            "label": "archive summary 必須保留 catalog handoff separate gate 與 runtime 安全邊界",
            "passed": summary["safe_boundaries_complete"],
        },
        {
            "key": "operator_confirmed_report_catalog_handoff",
            "label": "操作員確認 catalog handoff 只整理索引前置契約，且 catalog index 另開 gate",
            "passed": bool(
                operator["report_catalog_handoff_artifact_path"]
                and operator["report_archive_summary_artifact_path_recorded"]
                and operator["report_archive_artifact_path_recorded"]
                and operator["report_output_artifact_path_recorded"]
                and operator["catalog_record_key_recorded"]
                and operator["catalog_family_recorded"]
                and operator["operator_confirmed_report_catalog_handoff"]
                and operator["operator_confirmed_catalog_handoff_is_read_only"]
                and operator["operator_confirmed_report_archive_summary_reviewed"]
                and operator["operator_confirmed_catalog_identity_reviewed"]
                and operator["operator_confirmed_report_catalog_index_requires_separate_gate"]
            ),
        },
        {
            "key": "operator_confirmed_report_catalog_handoff_runtime_boundaries",
            "label": "操作員確認本 API 不產報表、不寫檔、不派送 Telegram、不寫 DB、不呼叫 LLM、不掛 scheduler",
            "passed": bool(
                operator["operator_confirmed_no_token_in_report_catalog_handoff"]
                and operator["operator_confirmed_no_api_report_generation"]
                and operator["operator_confirmed_no_api_file_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_handoff_no_token_submitted_to_api",
            "label": "catalog handoff payload 不得包含 approval 或 Telegram token key",
            "passed": not operator["forbidden_token_submitted_to_api"]
            and not summary["forbidden_token_key_detected"],
        },
        {
            "key": "report_catalog_handoff_apply_real_write_not_requested_from_api",
            "label": "API/UI report catalog handoff 不接受 apply_real_write",
            "passed": not apply_real_write,
        },
    ]


def build_candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_catalog_handoff(
    *,
    telegram_dispatch_report_archive_summary,
    operator_evidence=None,
    execute_requested=False,
    apply_real_write=False,
):
    """建立 Telegram dispatch report catalog handoff gate；不執行任何副作用。"""
    summary = _archive_summary_handoff(telegram_dispatch_report_archive_summary)
    operator = _operator_summary(operator_evidence)
    sections = _handoff_sections(summary)
    gates = _handoff_gates(summary, operator, bool(apply_real_write))
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    handoff_passed = bool(not blocked_reasons)

    return {
        "mode": "candidate_queue_review_ai_summary_persistence_telegram_dispatch_report_catalog_handoff_preview",
        "target_table": TARGET_TABLE,
        "target_column": TARGET_COLUMN,
        "target_json_path": [
            "market_intel_ai_summary",
            "telegram_dispatch_report_catalog_handoff",
        ],
        "target_operation": "handoff_archived_market_intel_report_to_catalog",
        "execute_requested": bool(execute_requested),
        "apply_real_write_requested": bool(apply_real_write),
        "report_catalog_handoff_reviewed": True,
        "telegram_dispatch_report_catalog_handoff_passed": handoff_passed,
        "summary_persistence_telegram_dispatch_report_catalog_handoff_passed": handoff_passed,
        "report_catalog_handoff_passed": handoff_passed,
        "ready_for_next_manual_phase": handoff_passed,
        "ready_for_market_intel_report_catalog_index": handoff_passed,
        "ready_for_market_intel_report_catalog_write_preflight": 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_archive_summary": summary,
        "telegram_dispatch_report_catalog_handoff_sections": sections,
        "operator_telegram_dispatch_report_catalog_handoff": operator,
        "promotion_gate": {
            "allowed": handoff_passed,
            "next_manual_phase": "market_intel_report_catalog_index",
            "requires_real_db_write": False,
            "requires_scheduler_attach": False,
            "requires_operator_approval": True,
            "api_must_not_generate_report": True,
            "api_must_not_write_catalog_handoff_file": True,
            "api_must_not_write_catalog_record": True,
            "api_must_not_dispatch_telegram": True,
            "report_catalog_index_requires_separate_gate": True,
            "report_catalog_write_preflight_requires_separate_gate": True,
        },
        "next_operator_steps": [
            "保存 report catalog handoff artifact path",
            "確認 catalog identity、artifact manifest、section keys 與 hash trace 可被索引引用",
            "下一階段 report catalog index 必須另開 gate；本 API 不寫檔、不寫 catalog record",
            "若任何 catalog handoff gate 阻擋，停在 report archive summary 階段並保留 feature flags 關閉",
        ],
        "safe_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",
            "report_catalog_handoff_preview_only",
            "no_remove_orphans",
            "no_momo_db_lifecycle_change",
        ],
    }
