"""候選審核 queue AI summary Telegram dispatch closeout preview。

本模組只在人工 Telegram dispatch receipt review 通過後整理 closeout gate；
不讀 approval 或 Telegram token、不補發 Telegram、不開 DB、不寫檔、不更新
review_state、不呼叫 LLM、不掛 scheduler。
"""


FORBIDDEN_TOKEN_KEYWORDS = (
    "approval_token",
    "approval-token",
    "market_intel_queue_write_approval",
    "telegram_bot_token",
    "telegram-token",
    "telegram_token",
    "bot_token",
)
SAFE_TOKEN_METADATA_KEYS = {
    "approval_token_present",
    "approval_token_valid",
    "approval_token_secret_configured",
    "telegram_token_present",
    "telegram_token_configured",
}
SAFE_APPROVAL_ENV_VAR = "MARKET_INTEL_QUEUE_WRITE_APPROVAL"
REQUIRED_RECEIPT_BOUNDARIES = {
    "do_not_read_approval_token_from_telegram_dispatch_run_receipt_api",
    "do_not_read_telegram_token_from_telegram_dispatch_run_receipt_api",
    "do_not_call_llm_from_telegram_dispatch_run_receipt",
    "do_not_dispatch_telegram_from_telegram_dispatch_run_receipt_api",
    "do_not_retry_telegram_dispatch_from_receipt_api",
    "do_not_echo_operator_telegram_receipt_payload",
    "do_not_open_database_connection_from_telegram_dispatch_run_receipt",
    "do_not_write_dispatch_receipt_artifact_from_api",
    "do_not_update_review_state_from_telegram_dispatch_run_receipt",
    "do_not_attach_scheduler_from_telegram_dispatch_run_receipt",
}
TARGET_TABLE = "market_alert_review_queue"
TARGET_COLUMN = "metadata_json"
SUMMARY_METADATA_KEY = "ai_summary_review"


def _as_dict(value):
    return value if isinstance(value, dict) else {}


def _as_list(value):
    if value is None:
        return []
    if isinstance(value, (list, tuple, set)):
        return list(value)
    return [value]


def _safe_int(value):
    try:
        return int(value or 0)
    except (TypeError, ValueError):
        return 0


def _has_text(value):
    return bool(isinstance(value, str) and value.strip())


def _contains_forbidden_token_key(value):
    if isinstance(value, dict):
        for key, nested in value.items():
            normalized_key = str(key).lower()
            if normalized_key in SAFE_TOKEN_METADATA_KEYS and isinstance(nested, bool):
                continue
            if normalized_key == "approval_env_var" and nested == SAFE_APPROVAL_ENV_VAR:
                continue
            if any(token_key in normalized_key for token_key in FORBIDDEN_TOKEN_KEYWORDS):
                return True
            if _contains_forbidden_token_key(nested):
                return True
    elif isinstance(value, list):
        return any(_contains_forbidden_token_key(item) for item in value)
    return False


def _receipt_summary(telegram_dispatch_run_receipt):
    run_receipt = _as_dict(telegram_dispatch_run_receipt)
    receipt = _as_dict(run_receipt.get("telegram_dispatch_receipt_summary"))
    readiness = _as_dict(run_receipt.get("telegram_dispatch_run_readiness_summary"))
    blocked_reasons = _as_list(run_receipt.get("blocked_reasons"))
    safe_boundaries = set(str(item) for item in _as_list(run_receipt.get("safe_boundaries")))
    missing_boundaries = sorted(REQUIRED_RECEIPT_BOUNDARIES - safe_boundaries)

    return {
        "provided": bool(run_receipt),
        "mode": run_receipt.get("mode"),
        "target_operation": run_receipt.get("target_operation"),
        "receipt_passed": bool(
            run_receipt.get("telegram_dispatch_run_receipt_passed")
            or run_receipt.get("summary_persistence_telegram_dispatch_run_receipt_passed")
            or run_receipt.get("run_receipt_passed")
        ),
        "ready_for_summary_persistence_telegram_dispatch_closeout": bool(
            run_receipt.get("ready_for_summary_persistence_telegram_dispatch_closeout")
        ),
        "ready_for_next_manual_phase": bool(
            run_receipt.get("ready_for_next_manual_phase")
        ),
        "statement_count": _safe_int(
            run_receipt.get("statement_count")
            or readiness.get("expected_dedupe_key_count")
        ),
        "expected_summary_payload_hash": (
            run_receipt.get("expected_summary_payload_hash")
            or readiness.get("expected_summary_payload_hash")
            or receipt.get("expected_summary_payload_hash")
        ),
        "blocked_count": len(blocked_reasons),
        "receipt_provided": bool(receipt.get("provided")),
        "receipt_mode": receipt.get("mode"),
        "receipt_ok": bool(receipt.get("ok")),
        "receipt_attempted": bool(receipt.get("telegram_dispatch_attempted")),
        "receipt_dispatched": bool(receipt.get("telegram_dispatched")),
        "message_id": receipt.get("message_id"),
        "chat_id": receipt.get("chat_id"),
        "telegram_channel_label": receipt.get("telegram_channel_label"),
        "summary_payload_hash": receipt.get("summary_payload_hash"),
        "summary_payload_hash_matches_expected": bool(
            receipt.get("summary_payload_hash_matches_expected")
        ),
        "approval_or_telegram_token_key_detected": bool(
            receipt.get("approval_or_telegram_token_key_detected")
        ),
        "safe_boundaries_complete": not missing_boundaries,
        "missing_safe_boundaries": missing_boundaries,
        "ready_for_telegram_dispatch": bool(run_receipt.get("ready_for_telegram_dispatch")),
        "ready_for_manual_telegram_dispatch": bool(
            run_receipt.get("ready_for_manual_telegram_dispatch")
        ),
        "ready_for_api_database_write": bool(
            run_receipt.get("ready_for_api_database_write")
        ),
        "ready_for_scheduler_attach": bool(run_receipt.get("ready_for_scheduler_attach")),
        "api_executes_cli": bool(run_receipt.get("api_executes_cli")),
        "api_executes_llm": bool(run_receipt.get("api_executes_llm")),
        "api_dispatches_telegram": bool(run_receipt.get("api_dispatches_telegram")),
        "api_reads_approval_token": bool(run_receipt.get("api_reads_approval_token")),
        "api_writes_file": bool(run_receipt.get("api_writes_file")),
        "api_writes_database": bool(run_receipt.get("api_writes_database")),
        "api_updates_review_state": bool(run_receipt.get("api_updates_review_state")),
        "telegram_dispatch_run_receipt_file_written": bool(
            run_receipt.get("telegram_dispatch_run_receipt_file_written")
        ),
        "telegram_dispatch_receipt_file_written": bool(
            run_receipt.get("telegram_dispatch_receipt_file_written")
        ),
        "telegram_message_file_written": bool(
            run_receipt.get("telegram_message_file_written")
        ),
        "llm_call_executed": bool(run_receipt.get("llm_call_executed")),
        "telegram_dispatched": bool(run_receipt.get("telegram_dispatched")),
        "telegram_dispatch_attempted": bool(
            run_receipt.get("telegram_dispatch_attempted")
        ),
        "external_network_executed": bool(run_receipt.get("external_network_executed")),
        "database_connection_opened": bool(
            run_receipt.get("database_connection_opened")
        ),
        "database_write_executed": bool(run_receipt.get("database_write_executed")),
        "database_commit_executed": bool(run_receipt.get("database_commit_executed")),
        "review_state_update_executed": bool(
            run_receipt.get("review_state_update_executed")
        ),
        "scheduler_attached": bool(run_receipt.get("scheduler_attached")),
    }


def _operator_closeout_summary(operator_evidence):
    operator_evidence = _as_dict(operator_evidence)
    return {
        "provided_keys": sorted(operator_evidence.keys()),
        "telegram_dispatch_closeout_artifact_path_recorded": _has_text(
            operator_evidence.get("telegram_dispatch_closeout_artifact_path")
            or operator_evidence.get("ai_summary_telegram_dispatch_closeout_artifact_path")
            or operator_evidence.get("closeout_artifact_path")
        ),
        "telegram_dispatch_receipt_artifact_path_recorded": _has_text(
            operator_evidence.get("telegram_dispatch_receipt_artifact_path")
            or operator_evidence.get("ai_summary_telegram_dispatch_receipt_artifact_path")
            or operator_evidence.get("telegram_dispatch_receipt_json_path")
        ),
        "operator_confirmed_telegram_dispatch_closeout": bool(
            operator_evidence.get("operator_confirmed_telegram_dispatch_closeout")
            or operator_evidence.get(
                "operator_confirmed_ai_summary_telegram_dispatch_closeout"
            )
        ),
        "operator_confirmed_receipt_archived": bool(
            operator_evidence.get("operator_confirmed_receipt_archived")
            or operator_evidence.get("operator_confirmed_telegram_dispatch_receipt_archived")
        ),
        "operator_confirmed_message_visible": bool(
            operator_evidence.get("operator_confirmed_message_visible")
            or operator_evidence.get("operator_confirmed_telegram_message_visible")
        ),
        "operator_confirmed_summary_hash_matched": bool(
            operator_evidence.get("operator_confirmed_summary_hash_matched")
        ),
        "operator_confirmed_no_duplicate_dispatch": bool(
            operator_evidence.get("operator_confirmed_no_duplicate_dispatch")
        ),
        "operator_confirmed_no_retry_needed": bool(
            operator_evidence.get("operator_confirmed_no_retry_needed")
            or operator_evidence.get("operator_confirmed_no_telegram_retry")
        ),
        "operator_confirmed_no_token_in_artifacts": bool(
            operator_evidence.get("operator_confirmed_no_token_in_artifacts")
            or operator_evidence.get("operator_confirmed_no_token_in_receipt")
        ),
        "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")
        ),
        "operator_confirmed_post_closeout_monitoring": bool(
            operator_evidence.get("operator_confirmed_post_closeout_monitoring")
            or operator_evidence.get("operator_confirmed_monitoring_required")
        ),
        "closeout_notes_recorded": _has_text(operator_evidence.get("closeout_notes")),
        "forbidden_token_submitted_to_api": _contains_forbidden_token_key(
            operator_evidence
        ),
    }


def _dispatch_audit_summary(receipt_summary, operator_summary):
    return {
        "manual_dispatch_proven": bool(
            receipt_summary["receipt_provided"]
            and receipt_summary["receipt_ok"]
            and receipt_summary["receipt_attempted"]
            and receipt_summary["receipt_dispatched"]
            and receipt_summary["message_id"]
            and receipt_summary["chat_id"]
            and receipt_summary["telegram_channel_label"]
        ),
        "message_id": receipt_summary["message_id"],
        "chat_id": receipt_summary["chat_id"],
        "telegram_channel_label": receipt_summary["telegram_channel_label"],
        "summary_payload_hash": receipt_summary["summary_payload_hash"],
        "summary_payload_hash_matches_expected": receipt_summary[
            "summary_payload_hash_matches_expected"
        ],
        "api_dispatch_blocked": bool(
            not receipt_summary["api_dispatches_telegram"]
            and not receipt_summary["telegram_dispatched"]
            and not receipt_summary["telegram_dispatch_attempted"]
        ),
        "duplicate_dispatch_ruled_out": operator_summary[
            "operator_confirmed_no_duplicate_dispatch"
        ],
        "receipt_archived": operator_summary["operator_confirmed_receipt_archived"],
        "post_closeout_monitoring_confirmed": operator_summary[
            "operator_confirmed_post_closeout_monitoring"
        ],
    }


def _closeout_gates(receipt_summary, operator_summary, apply_real_write):
    return [
        {
            "key": "telegram_dispatch_run_receipt_preview_provided",
            "label": "必須提供上一階段 Telegram dispatch run receipt preview",
            "passed": bool(
                receipt_summary["provided"]
                and receipt_summary["mode"]
                == "candidate_queue_review_ai_summary_persistence_telegram_dispatch_run_receipt_preview"
            ),
        },
        {
            "key": "telegram_dispatch_run_receipt_passed",
            "label": "run receipt 必須已通過人工 Telegram 派送審核",
            "passed": receipt_summary["receipt_passed"],
        },
        {
            "key": "telegram_dispatch_run_receipt_ready_for_closeout",
            "label": "run receipt 必須只放行到 Telegram dispatch closeout",
            "passed": bool(
                receipt_summary[
                    "ready_for_summary_persistence_telegram_dispatch_closeout"
                ]
                and receipt_summary["ready_for_next_manual_phase"]
            ),
        },
        {
            "key": "manual_telegram_dispatch_receipt_proves_message",
            "label": "人工 receipt 必須有成功派送、message id、chat/channel",
            "passed": bool(
                receipt_summary["receipt_provided"]
                and receipt_summary["receipt_ok"]
                and receipt_summary["receipt_attempted"]
                and receipt_summary["receipt_dispatched"]
                and receipt_summary["message_id"]
                and receipt_summary["chat_id"]
                and receipt_summary["telegram_channel_label"]
            ),
        },
        {
            "key": "manual_telegram_dispatch_hash_and_token_safe",
            "label": "人工 receipt 必須符合 summary hash 且不得包含 token key",
            "passed": bool(
                receipt_summary["summary_payload_hash_matches_expected"]
                and not receipt_summary["approval_or_telegram_token_key_detected"]
            ),
        },
        {
            "key": "telegram_dispatch_run_receipt_top_level_no_api_side_effects",
            "label": "run receipt 頂層不得顯示 API dispatch、DB write、LLM、檔案或 scheduler 副作用",
            "passed": bool(
                not receipt_summary["ready_for_telegram_dispatch"]
                and not receipt_summary["ready_for_manual_telegram_dispatch"]
                and not receipt_summary["ready_for_api_database_write"]
                and not receipt_summary["ready_for_scheduler_attach"]
                and not receipt_summary["api_executes_cli"]
                and not receipt_summary["api_executes_llm"]
                and not receipt_summary["api_dispatches_telegram"]
                and not receipt_summary["api_reads_approval_token"]
                and not receipt_summary["api_writes_file"]
                and not receipt_summary["api_writes_database"]
                and not receipt_summary["api_updates_review_state"]
                and not receipt_summary["telegram_dispatch_run_receipt_file_written"]
                and not receipt_summary["telegram_dispatch_receipt_file_written"]
                and not receipt_summary["telegram_message_file_written"]
                and not receipt_summary["llm_call_executed"]
                and not receipt_summary["telegram_dispatched"]
                and not receipt_summary["telegram_dispatch_attempted"]
                and not receipt_summary["external_network_executed"]
                and not receipt_summary["database_connection_opened"]
                and not receipt_summary["database_write_executed"]
                and not receipt_summary["database_commit_executed"]
                and not receipt_summary["review_state_update_executed"]
                and not receipt_summary["scheduler_attached"]
            ),
        },
        {
            "key": "telegram_dispatch_run_receipt_safe_boundaries_complete",
            "label": "run receipt 必須保留 Telegram/token/DB/scheduler 安全邊界",
            "passed": receipt_summary["safe_boundaries_complete"],
        },
        {
            "key": "telegram_dispatch_closeout_artifact_path_recorded",
            "label": "操作員需記錄 Telegram dispatch closeout artifact 路徑",
            "passed": operator_summary[
                "telegram_dispatch_closeout_artifact_path_recorded"
            ],
        },
        {
            "key": "telegram_dispatch_receipt_artifact_path_recorded",
            "label": "操作員需保留 Telegram dispatch receipt artifact 路徑",
            "passed": operator_summary[
                "telegram_dispatch_receipt_artifact_path_recorded"
            ],
        },
        {
            "key": "operator_confirmed_telegram_dispatch_closeout",
            "label": "操作員確認 Telegram dispatch closeout 已完成",
            "passed": operator_summary[
                "operator_confirmed_telegram_dispatch_closeout"
            ],
        },
        {
            "key": "operator_confirmed_receipt_archived",
            "label": "操作員確認 receipt 已封存",
            "passed": operator_summary["operator_confirmed_receipt_archived"],
        },
        {
            "key": "operator_confirmed_message_visible_and_hash_matched",
            "label": "操作員確認 Telegram 訊息可見且 summary hash 已對齊",
            "passed": bool(
                operator_summary["operator_confirmed_message_visible"]
                and operator_summary["operator_confirmed_summary_hash_matched"]
            ),
        },
        {
            "key": "operator_confirmed_no_duplicate_dispatch",
            "label": "操作員確認沒有重複派送",
            "passed": operator_summary["operator_confirmed_no_duplicate_dispatch"],
        },
        {
            "key": "operator_confirmed_no_retry_needed",
            "label": "操作員確認 closeout API 不需重試或補發 Telegram",
            "passed": operator_summary["operator_confirmed_no_retry_needed"],
        },
        {
            "key": "operator_confirmed_no_token_in_artifacts",
            "label": "操作員確認 artifacts 不含 approval 或 Telegram token",
            "passed": operator_summary["operator_confirmed_no_token_in_artifacts"],
        },
        {
            "key": "operator_confirmed_no_api_telegram_dispatch",
            "label": "操作員確認本階段不由 API/UI 派送 Telegram",
            "passed": operator_summary["operator_confirmed_no_api_telegram_dispatch"],
        },
        {
            "key": "operator_confirmed_no_api_db_write_llm_scheduler",
            "label": "操作員確認本階段不寫 DB、不呼叫 LLM、不掛 scheduler",
            "passed": bool(
                operator_summary["operator_confirmed_no_api_db_write"]
                and operator_summary["operator_confirmed_no_llm_call"]
                and operator_summary["operator_confirmed_no_scheduler_attach"]
            ),
        },
        {
            "key": "operator_confirmed_post_closeout_monitoring",
            "label": "操作員確認 closeout 後需監控重複派送與告警狀態",
            "passed": operator_summary[
                "operator_confirmed_post_closeout_monitoring"
            ],
        },
        {
            "key": "telegram_dispatch_closeout_no_token_submitted_to_api",
            "label": "closeout payload 不得包含 approval 或 Telegram token key",
            "passed": not operator_summary["forbidden_token_submitted_to_api"],
        },
        {
            "key": "telegram_dispatch_closeout_apply_real_write_not_requested_from_api",
            "label": "API/UI closeout 不接受 apply_real_write",
            "passed": not apply_real_write,
        },
    ]


def build_candidate_queue_review_ai_summary_persistence_telegram_dispatch_closeout(
    *,
    telegram_dispatch_run_receipt,
    operator_evidence=None,
    execute_requested=False,
    apply_real_write=False,
):
    """建立 Telegram dispatch closeout gate；不執行 Telegram 或 DB 副作用。"""
    receipt_summary = _receipt_summary(telegram_dispatch_run_receipt)
    operator_summary = _operator_closeout_summary(operator_evidence)
    dispatch_audit = _dispatch_audit_summary(receipt_summary, operator_summary)
    gates = _closeout_gates(
        receipt_summary,
        operator_summary,
        bool(apply_real_write),
    )
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    closeout_passed = bool(not blocked_reasons)

    return {
        "mode": "candidate_queue_review_ai_summary_persistence_telegram_dispatch_closeout_preview",
        "target_table": TARGET_TABLE,
        "target_column": TARGET_COLUMN,
        "target_json_path": [SUMMARY_METADATA_KEY],
        "target_operation": "closeout_manual_ai_summary_telegram_dispatch",
        "execute_requested": bool(execute_requested),
        "apply_real_write_requested": bool(apply_real_write),
        "closeout_reviewed": True,
        "closeout_passed": closeout_passed,
        "telegram_dispatch_closeout_passed": closeout_passed,
        "summary_persistence_telegram_dispatch_closeout_passed": closeout_passed,
        "ready_for_next_manual_phase": closeout_passed,
        "ready_for_summary_persistence_telegram_dispatch_archive": closeout_passed,
        "ready_for_telegram_dispatch": False,
        "ready_for_manual_telegram_dispatch": False,
        "ready_for_api_database_write": False,
        "ready_for_scheduler_attach": False,
        "ready_for_llm_call": False,
        "ready_for_real_write": 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,
        "telegram_dispatch_closeout_file_written": False,
        "closeout_file_written": False,
        "telegram_dispatch_run_receipt_file_written": False,
        "telegram_dispatch_receipt_file_written": False,
        "telegram_message_file_written": False,
        "summary_file_written": False,
        "summary_record_written": False,
        "summary_persistence_record_written": False,
        "metadata_patch_written": False,
        "ai_summary_generated": False,
        "llm_call_executed": False,
        "ollama_call_executed": False,
        "gemini_call_executed": False,
        "telegram_dispatched": False,
        "telegram_dispatch_attempted": False,
        "review_state_update_executed": False,
        "read_only_query_executed": False,
        "database_connection_opened": False,
        "database_session_created": False,
        "explicit_transaction_opened": False,
        "transaction_opened": False,
        "transaction_committed": False,
        "database_write_executed": False,
        "database_commit_executed": False,
        "database_rollback_executed": False,
        "external_network_executed": False,
        "scheduler_attached": False,
        "writes_executed": False,
        "would_write_database": False,
        "statement_count": receipt_summary["statement_count"],
        "expected_summary_payload_hash": receipt_summary[
            "expected_summary_payload_hash"
        ],
        "blocked_reasons": blocked_reasons,
        "gates": gates,
        "telegram_dispatch_run_receipt_summary": receipt_summary,
        "operator_telegram_dispatch_closeout": operator_summary,
        "dispatch_audit_summary": dispatch_audit,
        "promotion_gate": {
            "allowed": closeout_passed,
            "next_manual_phase": "summary_persistence_telegram_dispatch_archive",
            "requires_real_db_write": False,
            "requires_scheduler_attach": False,
            "requires_operator_approval": True,
            "telegram_dispatch_already_manual": True,
            "api_must_not_retry_telegram": True,
        },
        "next_operator_steps": [
            "保存 Telegram dispatch closeout artifact 與 receipt artifact 路徑",
            "人工確認 Telegram message id、channel、summary payload hash 與封存紀錄",
            "監控是否出現重複 dispatch、告警錯誤或 channel mismatch",
            "後續若需封存或報表摘要，另開 archive gate；不得從 closeout API 補發 Telegram",
        ],
        "safe_boundaries": [
            "do_not_read_approval_token_from_telegram_dispatch_closeout_api",
            "do_not_read_telegram_token_from_telegram_dispatch_closeout_api",
            "do_not_call_llm_from_telegram_dispatch_closeout",
            "do_not_dispatch_telegram_from_telegram_dispatch_closeout_api",
            "do_not_retry_telegram_dispatch_from_closeout_api",
            "do_not_echo_operator_telegram_receipt_payload",
            "do_not_open_database_connection_from_telegram_dispatch_closeout",
            "do_not_write_closeout_artifact_from_api",
            "do_not_update_review_state_from_telegram_dispatch_closeout",
            "do_not_attach_scheduler_from_telegram_dispatch_closeout",
            "telegram_dispatch_closeout_preview_only",
            "no_remove_orphans",
            "no_momo_db_lifecycle_change",
        ],
    }
