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

本模組只在 Telegram dispatch closeout 通過後整理封存 manifest；
不讀 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"
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 _safe_text(value, limit=300):
    if value is None:
        return None
    text = str(value).strip()
    return text[:limit] if text else None


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 _side_effects_clear(*payloads):
    blocked_keys = (
        "ready_for_telegram_dispatch",
        "ready_for_manual_telegram_dispatch",
        "ready_for_api_database_write",
        "ready_for_scheduler_attach",
        "api_executes_cli",
        "api_executes_llm",
        "api_dispatches_telegram",
        "api_reads_approval_token",
        "api_writes_file",
        "api_writes_database",
        "api_updates_review_state",
        "telegram_dispatch_closeout_file_written",
        "telegram_dispatch_archive_file_written",
        "telegram_dispatch_receipt_file_written",
        "telegram_dispatch_run_receipt_file_written",
        "telegram_message_file_written",
        "archive_file_written",
        "archive_record_written",
        "archive_manifest_written",
        "summary_file_written",
        "summary_record_written",
        "summary_manifest_written",
        "ai_summary_generated",
        "llm_call_executed",
        "ollama_call_executed",
        "gemini_call_executed",
        "telegram_dispatched",
        "telegram_dispatch_attempted",
        "external_network_executed",
        "database_connection_opened",
        "database_write_executed",
        "database_commit_executed",
        "review_state_update_executed",
        "scheduler_attached",
        "writes_executed",
        "would_write_database",
    )
    return all(
        not _as_dict(payload).get(key)
        for payload in payloads
        for key in blocked_keys
    )


def _closeout_summary(telegram_dispatch_closeout):
    closeout = _as_dict(telegram_dispatch_closeout)
    receipt = _as_dict(closeout.get("telegram_dispatch_run_receipt_summary"))
    operator = _as_dict(closeout.get("operator_telegram_dispatch_closeout"))
    audit = _as_dict(closeout.get("dispatch_audit_summary"))
    blocked_reasons = _as_list(closeout.get("blocked_reasons"))
    return {
        "provided": bool(closeout),
        "mode": closeout.get("mode"),
        "target_operation": closeout.get("target_operation"),
        "closeout_passed": bool(
            closeout.get("telegram_dispatch_closeout_passed")
            or closeout.get("summary_persistence_telegram_dispatch_closeout_passed")
            or closeout.get("closeout_passed")
        ),
        "ready_for_summary_persistence_telegram_dispatch_archive": bool(
            closeout.get("ready_for_summary_persistence_telegram_dispatch_archive")
        ),
        "ready_for_next_manual_phase": bool(closeout.get("ready_for_next_manual_phase")),
        "statement_count": _safe_int(closeout.get("statement_count")),
        "expected_summary_payload_hash": closeout.get("expected_summary_payload_hash"),
        "blocked_count": len(blocked_reasons),
        "receipt": {
            "mode": receipt.get("mode"),
            "receipt_passed": bool(receipt.get("receipt_passed")),
            "message_id": _safe_text(receipt.get("message_id"), 120),
            "chat_id": _safe_text(receipt.get("chat_id"), 120),
            "telegram_channel_label": _safe_text(
                receipt.get("telegram_channel_label"),
                180,
            ),
            "summary_payload_hash": _safe_text(
                receipt.get("summary_payload_hash"),
                80,
            ),
            "summary_payload_hash_matches_expected": bool(
                receipt.get("summary_payload_hash_matches_expected")
            ),
        },
        "dispatch_audit": {
            "manual_dispatch_proven": bool(audit.get("manual_dispatch_proven")),
            "api_dispatch_blocked": bool(audit.get("api_dispatch_blocked")),
            "duplicate_dispatch_ruled_out": bool(
                audit.get("duplicate_dispatch_ruled_out")
            ),
            "receipt_archived": bool(audit.get("receipt_archived")),
            "post_closeout_monitoring_confirmed": bool(
                audit.get("post_closeout_monitoring_confirmed")
            ),
            "message_id": _safe_text(audit.get("message_id"), 120),
            "chat_id": _safe_text(audit.get("chat_id"), 120),
            "telegram_channel_label": _safe_text(
                audit.get("telegram_channel_label"),
                180,
            ),
            "summary_payload_hash": _safe_text(audit.get("summary_payload_hash"), 80),
            "summary_payload_hash_matches_expected": bool(
                audit.get("summary_payload_hash_matches_expected")
            ),
        },
        "operator": {
            "closeout_artifact_path_recorded": bool(
                operator.get("telegram_dispatch_closeout_artifact_path_recorded")
            ),
            "receipt_artifact_path_recorded": bool(
                operator.get("telegram_dispatch_receipt_artifact_path_recorded")
            ),
            "operator_confirmed_telegram_dispatch_closeout": bool(
                operator.get("operator_confirmed_telegram_dispatch_closeout")
            ),
            "operator_confirmed_receipt_archived": bool(
                operator.get("operator_confirmed_receipt_archived")
            ),
            "operator_confirmed_no_duplicate_dispatch": bool(
                operator.get("operator_confirmed_no_duplicate_dispatch")
            ),
            "operator_confirmed_post_closeout_monitoring": bool(
                operator.get("operator_confirmed_post_closeout_monitoring")
            ),
        },
        "safe_boundaries": _as_list(closeout.get("safe_boundaries")),
        "side_effects_clear": _side_effects_clear(closeout),
    }


def _operator_archive_summary(operator_evidence):
    operator_evidence = _as_dict(operator_evidence)
    return {
        "provided_keys": sorted(operator_evidence.keys()),
        "telegram_dispatch_archive_artifact_path": _safe_text(
            operator_evidence.get("telegram_dispatch_archive_artifact_path")
            or operator_evidence.get("ai_summary_telegram_dispatch_archive_artifact_path")
            or operator_evidence.get("archive_artifact_path")
        ),
        "telegram_dispatch_closeout_artifact_path": _safe_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": _safe_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")
        ),
        "telegram_message_preview_artifact_path": _safe_text(
            operator_evidence.get("telegram_message_preview_artifact_path")
            or operator_evidence.get("ai_summary_telegram_message_preview_artifact_path")
        ),
        "operator_confirmed_telegram_dispatch_archive": bool(
            operator_evidence.get("operator_confirmed_telegram_dispatch_archive")
            or operator_evidence.get(
                "operator_confirmed_ai_summary_telegram_dispatch_archive"
            )
        ),
        "operator_confirmed_archive_is_read_only": bool(
            operator_evidence.get("operator_confirmed_archive_is_read_only")
            or operator_evidence.get(
                "operator_confirmed_telegram_dispatch_archive_is_read_only"
            )
        ),
        "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_id_archived": bool(
            operator_evidence.get("operator_confirmed_message_id_archived")
        ),
        "operator_confirmed_dispatch_audit_archived": bool(
            operator_evidence.get("operator_confirmed_dispatch_audit_archived")
        ),
        "operator_confirmed_post_closeout_monitoring": bool(
            operator_evidence.get("operator_confirmed_post_closeout_monitoring")
            or operator_evidence.get("operator_confirmed_monitoring_required")
        ),
        "operator_confirmed_no_duplicate_dispatch": bool(
            operator_evidence.get("operator_confirmed_no_duplicate_dispatch")
        ),
        "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")
        ),
        "archive_notes_recorded": bool(
            _safe_text(operator_evidence.get("archive_notes"))
            or _safe_text(operator_evidence.get("closeout_notes"))
        ),
        "forbidden_token_submitted_to_api": _contains_forbidden_token_key(
            operator_evidence
        ),
    }


def _archive_manifest(closeout_summary, operator_summary):
    receipt = closeout_summary["receipt"]
    audit = closeout_summary["dispatch_audit"]
    return {
        "target_table": TARGET_TABLE,
        "target_column": TARGET_COLUMN,
        "target_json_path": [SUMMARY_METADATA_KEY],
        "statement_count": closeout_summary["statement_count"],
        "closeout": {
            "mode": closeout_summary["mode"],
            "closeout_passed": closeout_summary["closeout_passed"],
            "ready_for_archive": closeout_summary[
                "ready_for_summary_persistence_telegram_dispatch_archive"
            ],
        },
        "telegram_message": {
            "message_id": audit["message_id"] or receipt["message_id"],
            "chat_id": audit["chat_id"] or receipt["chat_id"],
            "telegram_channel_label": (
                audit["telegram_channel_label"]
                or receipt["telegram_channel_label"]
            ),
            "summary_payload_hash": (
                audit["summary_payload_hash"]
                or receipt["summary_payload_hash"]
            ),
            "summary_payload_hash_matches_expected": bool(
                audit["summary_payload_hash_matches_expected"]
                or receipt["summary_payload_hash_matches_expected"]
            ),
        },
        "dispatch_audit": {
            "manual_dispatch_proven": audit["manual_dispatch_proven"],
            "api_dispatch_blocked": audit["api_dispatch_blocked"],
            "duplicate_dispatch_ruled_out": audit["duplicate_dispatch_ruled_out"],
            "receipt_archived": audit["receipt_archived"],
            "post_closeout_monitoring_confirmed": audit[
                "post_closeout_monitoring_confirmed"
            ],
        },
        "artifact_paths": {
            "telegram_dispatch_receipt_artifact_path": operator_summary[
                "telegram_dispatch_receipt_artifact_path"
            ],
            "telegram_dispatch_closeout_artifact_path": operator_summary[
                "telegram_dispatch_closeout_artifact_path"
            ],
            "telegram_message_preview_artifact_path": operator_summary[
                "telegram_message_preview_artifact_path"
            ],
            "telegram_dispatch_archive_artifact_path": operator_summary[
                "telegram_dispatch_archive_artifact_path"
            ],
        },
    }


def _archive_gates(closeout_summary, operator_summary, manifest, apply_real_write):
    artifact_paths = manifest["artifact_paths"]
    telegram_message = manifest["telegram_message"]
    dispatch_audit = manifest["dispatch_audit"]
    return [
        {
            "key": "telegram_dispatch_closeout_preview_provided",
            "label": "必須提供 Telegram dispatch closeout preview",
            "passed": bool(
                closeout_summary["provided"]
                and closeout_summary["mode"]
                == "candidate_queue_review_ai_summary_persistence_telegram_dispatch_closeout_preview"
            ),
        },
        {
            "key": "telegram_dispatch_closeout_passed",
            "label": "Telegram dispatch closeout 必須已通過",
            "passed": closeout_summary["closeout_passed"],
        },
        {
            "key": "telegram_dispatch_closeout_ready_for_archive",
            "label": "closeout 必須只放行到 Telegram dispatch archive",
            "passed": bool(
                closeout_summary[
                    "ready_for_summary_persistence_telegram_dispatch_archive"
                ]
                and closeout_summary["ready_for_next_manual_phase"]
            ),
        },
        {
            "key": "telegram_dispatch_message_identity_complete",
            "label": "封存 manifest 必須包含 message id、chat/channel 與 summary hash",
            "passed": bool(
                telegram_message["message_id"]
                and telegram_message["chat_id"]
                and telegram_message["telegram_channel_label"]
                and telegram_message["summary_payload_hash"]
                and telegram_message["summary_payload_hash_matches_expected"]
            ),
        },
        {
            "key": "telegram_dispatch_audit_complete",
            "label": "dispatch audit 必須證明人工派送、API 未派送、無重複與監控已確認",
            "passed": bool(
                dispatch_audit["manual_dispatch_proven"]
                and dispatch_audit["api_dispatch_blocked"]
                and dispatch_audit["duplicate_dispatch_ruled_out"]
                and dispatch_audit["receipt_archived"]
                and dispatch_audit["post_closeout_monitoring_confirmed"]
            ),
        },
        {
            "key": "telegram_dispatch_closeout_side_effects_clear",
            "label": "closeout payload 不得顯示 Telegram、DB、LLM、檔案或 scheduler 副作用",
            "passed": closeout_summary["side_effects_clear"],
        },
        {
            "key": "telegram_dispatch_archive_artifact_paths_recorded",
            "label": "receipt、closeout、message preview 與 archive artifact path 必須齊備",
            "passed": all(artifact_paths.values()),
        },
        {
            "key": "operator_confirmed_telegram_dispatch_archive",
            "label": "操作員確認 Telegram dispatch archive 已可封存",
            "passed": bool(
                operator_summary["operator_confirmed_telegram_dispatch_archive"]
                and operator_summary["operator_confirmed_archive_is_read_only"]
                and operator_summary["operator_confirmed_receipt_archived"]
                and operator_summary["operator_confirmed_message_id_archived"]
                and operator_summary["operator_confirmed_dispatch_audit_archived"]
            ),
        },
        {
            "key": "operator_confirmed_archive_runtime_boundaries",
            "label": "操作員確認 archive 不派送 Telegram、不寫 DB、不呼叫 LLM、不掛 scheduler",
            "passed": bool(
                operator_summary["operator_confirmed_no_duplicate_dispatch"]
                and operator_summary["operator_confirmed_post_closeout_monitoring"]
                and operator_summary["operator_confirmed_no_token_in_artifacts"]
                and operator_summary["operator_confirmed_no_api_telegram_dispatch"]
                and 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": "telegram_dispatch_archive_no_token_submitted_to_api",
            "label": "archive payload 不得包含 approval 或 Telegram token key",
            "passed": not operator_summary["forbidden_token_submitted_to_api"],
        },
        {
            "key": "telegram_dispatch_archive_apply_real_write_not_requested_from_api",
            "label": "API/UI archive 不接受 apply_real_write",
            "passed": not apply_real_write,
        },
    ]


def build_candidate_queue_review_ai_summary_persistence_telegram_dispatch_archive(
    *,
    telegram_dispatch_closeout,
    operator_evidence=None,
    execute_requested=False,
    apply_real_write=False,
):
    """建立 Telegram dispatch archive gate；不執行任何副作用。"""
    closeout_summary = _closeout_summary(telegram_dispatch_closeout)
    operator_summary = _operator_archive_summary(operator_evidence)
    manifest = _archive_manifest(closeout_summary, operator_summary)
    gates = _archive_gates(
        closeout_summary,
        operator_summary,
        manifest,
        bool(apply_real_write),
    )
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    archive_ready = bool(not blocked_reasons)

    return {
        "mode": "candidate_queue_review_ai_summary_persistence_telegram_dispatch_archive_preview",
        "target_table": TARGET_TABLE,
        "target_column": TARGET_COLUMN,
        "target_json_path": [SUMMARY_METADATA_KEY],
        "target_operation": "archive_manual_ai_summary_telegram_dispatch_evidence",
        "execute_requested": bool(execute_requested),
        "apply_real_write_requested": bool(apply_real_write),
        "archive_reviewed": True,
        "telegram_dispatch_archive_ready": archive_ready,
        "summary_persistence_telegram_dispatch_archive_ready": archive_ready,
        "archive_manifest_ready": archive_ready,
        "ready_for_next_manual_phase": archive_ready,
        "ready_for_summary_persistence_telegram_dispatch_archive_summary": archive_ready,
        "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_archive_file_written": False,
        "telegram_dispatch_closeout_file_written": False,
        "telegram_dispatch_receipt_file_written": False,
        "telegram_dispatch_run_receipt_file_written": False,
        "telegram_message_file_written": False,
        "archive_file_written": False,
        "archive_record_written": False,
        "archive_manifest_written": False,
        "summary_file_written": False,
        "summary_record_written": False,
        "summary_manifest_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": closeout_summary["statement_count"],
        "expected_summary_payload_hash": closeout_summary[
            "expected_summary_payload_hash"
        ],
        "blocked_reasons": blocked_reasons,
        "gates": gates,
        "telegram_dispatch_closeout_summary": closeout_summary,
        "operator_telegram_dispatch_archive": operator_summary,
        "telegram_dispatch_archive_manifest": manifest,
        "promotion_gate": {
            "allowed": archive_ready,
            "next_manual_phase": "summary_persistence_telegram_dispatch_archive_summary",
            "requires_real_db_write": False,
            "requires_scheduler_attach": False,
            "requires_operator_approval": True,
            "api_must_not_dispatch_telegram": True,
            "api_must_not_write_archive": True,
        },
        "next_operator_steps": [
            "保存 Telegram dispatch archive manifest 與上游 artifact path",
            "人工確認 message id、channel、summary hash、receipt 與 closeout 可追溯",
            "保留 duplicate dispatch 與 post-closeout monitoring 檢查紀錄",
            "後續若要整理 archive summary 或報表輸入，必須另開獨立 gate",
        ],
        "safe_boundaries": [
            "do_not_read_approval_token_from_telegram_dispatch_archive_api",
            "do_not_read_telegram_token_from_telegram_dispatch_archive_api",
            "do_not_call_llm_from_telegram_dispatch_archive",
            "do_not_dispatch_telegram_from_telegram_dispatch_archive_api",
            "do_not_retry_telegram_dispatch_from_archive_api",
            "do_not_open_database_connection_from_telegram_dispatch_archive",
            "do_not_write_archive_artifact_from_api",
            "do_not_update_review_state_from_telegram_dispatch_archive",
            "do_not_attach_scheduler_from_telegram_dispatch_archive",
            "telegram_dispatch_archive_preview_only",
            "no_remove_orphans",
            "no_momo_db_lifecycle_change",
        ],
    }
