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

本模組只在 Telegram dispatch archive 通過後整理可供後續報表/summary gate
使用的結構化輸入；不讀 approval 或 Telegram token、不呼叫 LLM、不派送或
補發 Telegram、不開 DB、不寫檔、不更新 review_state、不掛 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",
        "ready_for_llm_call",
        "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_archive_file_written",
        "telegram_dispatch_archive_summary_file_written",
        "telegram_dispatch_closeout_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",
        "archive_summary_file_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 _archive_payload_summary(telegram_dispatch_archive):
    archive = _as_dict(telegram_dispatch_archive)
    manifest = _as_dict(archive.get("telegram_dispatch_archive_manifest"))
    message = _as_dict(manifest.get("telegram_message"))
    audit = _as_dict(manifest.get("dispatch_audit"))
    artifact_paths = _as_dict(manifest.get("artifact_paths"))
    closeout = _as_dict(archive.get("telegram_dispatch_closeout_summary"))
    blocked_reasons = _as_list(archive.get("blocked_reasons"))

    return {
        "provided": bool(archive),
        "mode": archive.get("mode"),
        "target_operation": archive.get("target_operation"),
        "telegram_dispatch_archive_ready": bool(
            archive.get("telegram_dispatch_archive_ready")
        ),
        "summary_persistence_telegram_dispatch_archive_ready": bool(
            archive.get("summary_persistence_telegram_dispatch_archive_ready")
        ),
        "archive_manifest_ready": bool(archive.get("archive_manifest_ready")),
        "ready_for_summary_persistence_telegram_dispatch_archive_summary": bool(
            archive.get(
                "ready_for_summary_persistence_telegram_dispatch_archive_summary"
            )
        ),
        "ready_for_next_manual_phase": bool(archive.get("ready_for_next_manual_phase")),
        "statement_count": _safe_int(archive.get("statement_count")),
        "expected_summary_payload_hash": archive.get("expected_summary_payload_hash"),
        "blocked_count": len(blocked_reasons),
        "closeout_mode": closeout.get("mode"),
        "closeout_passed": bool(closeout.get("closeout_passed")),
        "message": {
            "message_id": _safe_text(message.get("message_id"), 120),
            "chat_id": _safe_text(message.get("chat_id"), 120),
            "telegram_channel_label": _safe_text(
                message.get("telegram_channel_label"),
                180,
            ),
            "summary_payload_hash": _safe_text(
                message.get("summary_payload_hash"),
                80,
            ),
            "summary_payload_hash_matches_expected": bool(
                message.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")
            ),
        },
        "artifact_paths": {
            "telegram_dispatch_receipt_artifact_path": artifact_paths.get(
                "telegram_dispatch_receipt_artifact_path"
            ),
            "telegram_dispatch_closeout_artifact_path": artifact_paths.get(
                "telegram_dispatch_closeout_artifact_path"
            ),
            "telegram_message_preview_artifact_path": artifact_paths.get(
                "telegram_message_preview_artifact_path"
            ),
            "telegram_dispatch_archive_artifact_path": artifact_paths.get(
                "telegram_dispatch_archive_artifact_path"
            ),
        },
        "safe_boundaries": _as_list(archive.get("safe_boundaries")),
        "side_effects_clear": _side_effects_clear(archive),
    }


def _operator_summary(operator_evidence):
    operator_evidence = _as_dict(operator_evidence)
    return {
        "provided_keys": sorted(operator_evidence.keys()),
        "telegram_dispatch_archive_summary_artifact_path": _safe_text(
            operator_evidence.get("telegram_dispatch_archive_summary_artifact_path")
            or operator_evidence.get(
                "ai_summary_telegram_dispatch_archive_summary_artifact_path"
            )
            or operator_evidence.get("archive_summary_artifact_path")
        ),
        "operator_confirmed_telegram_dispatch_archive_summary": bool(
            operator_evidence.get(
                "operator_confirmed_telegram_dispatch_archive_summary"
            )
            or operator_evidence.get(
                "operator_confirmed_ai_summary_telegram_dispatch_archive_summary"
            )
        ),
        "operator_confirmed_summary_is_read_only": bool(
            operator_evidence.get("operator_confirmed_summary_is_read_only")
            or operator_evidence.get("operator_confirmed_archive_summary_is_read_only")
            or operator_evidence.get("operator_confirmed_archive_is_read_only")
        ),
        "operator_confirmed_message_and_artifacts_reviewed": bool(
            operator_evidence.get("operator_confirmed_message_and_artifacts_reviewed")
            or operator_evidence.get("operator_confirmed_message_id_archived")
        ),
        "operator_confirmed_dispatch_audit_reviewed": bool(
            operator_evidence.get("operator_confirmed_dispatch_audit_reviewed")
            or operator_evidence.get("operator_confirmed_dispatch_audit_archived")
        ),
        "operator_confirmed_report_input_requires_separate_gate": bool(
            operator_evidence.get(
                "operator_confirmed_report_input_requires_separate_gate"
            )
        ),
        "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_summary_notes_recorded": bool(
            _safe_text(operator_evidence.get("archive_summary_notes"))
            or _safe_text(operator_evidence.get("archive_notes"))
        ),
        "forbidden_token_submitted_to_api": _contains_forbidden_token_key(
            operator_evidence
        ),
    }


def _summary_sections(archive_summary):
    message = archive_summary["message"]
    audit = archive_summary["dispatch_audit"]
    artifact_paths = archive_summary["artifact_paths"]
    artifact_count = sum(1 for value in artifact_paths.values() if value)
    return [
        {
            "key": "telegram_message_identity",
            "title": "Telegram message identity",
            "facts": [
                f"message_id={message['message_id'] or 'missing'}",
                f"chat_id={message['chat_id'] or 'missing'}",
                f"channel={message['telegram_channel_label'] or 'missing'}",
                f"summary_hash_matched={message['summary_payload_hash_matches_expected']}",
            ],
        },
        {
            "key": "dispatch_audit",
            "title": "Dispatch audit",
            "facts": [
                f"manual_dispatch_proven={audit['manual_dispatch_proven']}",
                f"api_dispatch_blocked={audit['api_dispatch_blocked']}",
                f"duplicate_ruled_out={audit['duplicate_dispatch_ruled_out']}",
                f"monitoring_confirmed={audit['post_closeout_monitoring_confirmed']}",
            ],
        },
        {
            "key": "artifact_manifest",
            "title": "Artifact manifest",
            "facts": [
                f"artifact_path_count={artifact_count}",
                f"statement_count={archive_summary['statement_count']}",
            ],
        },
        {
            "key": "runtime_safety",
            "title": "Runtime safety",
            "facts": [
                "llm_call_executed=false",
                "telegram_dispatched=false",
                "database_write_executed=false",
                "scheduler_attached=false",
            ],
        },
    ]


def _summary_gates(archive_summary, operator, apply_real_write):
    message = archive_summary["message"]
    audit = archive_summary["dispatch_audit"]
    artifact_paths = archive_summary["artifact_paths"]
    return [
        {
            "key": "telegram_dispatch_archive_preview_provided",
            "label": "必須提供 Telegram dispatch archive preview",
            "passed": bool(
                archive_summary["provided"]
                and archive_summary["mode"]
                == "candidate_queue_review_ai_summary_persistence_telegram_dispatch_archive_preview"
            ),
        },
        {
            "key": "telegram_dispatch_archive_ready",
            "label": "Telegram dispatch archive 必須已通過",
            "passed": bool(
                archive_summary["telegram_dispatch_archive_ready"]
                and archive_summary[
                    "summary_persistence_telegram_dispatch_archive_ready"
                ]
                and archive_summary["archive_manifest_ready"]
                and archive_summary[
                    "ready_for_summary_persistence_telegram_dispatch_archive_summary"
                ]
                and archive_summary["ready_for_next_manual_phase"]
            ),
        },
        {
            "key": "telegram_dispatch_archive_message_identity_complete",
            "label": "archive summary 必須包含 message id、chat/channel 與 hash match",
            "passed": bool(
                message["message_id"]
                and message["chat_id"]
                and message["telegram_channel_label"]
                and message["summary_payload_hash"]
                and message["summary_payload_hash_matches_expected"]
            ),
        },
        {
            "key": "telegram_dispatch_archive_audit_complete",
            "label": "archive summary 必須保留人工派送、API 未派送、無重複與監控證據",
            "passed": bool(
                audit["manual_dispatch_proven"]
                and audit["api_dispatch_blocked"]
                and audit["duplicate_dispatch_ruled_out"]
                and audit["receipt_archived"]
                and audit["post_closeout_monitoring_confirmed"]
            ),
        },
        {
            "key": "telegram_dispatch_archive_artifact_paths_complete",
            "label": "receipt、closeout、message preview 與 archive artifact path 必須齊備",
            "passed": all(artifact_paths.values()),
        },
        {
            "key": "telegram_dispatch_archive_side_effects_clear",
            "label": "archive payload 不得顯示 Telegram、DB、LLM、檔案或 scheduler 副作用",
            "passed": archive_summary["side_effects_clear"],
        },
        {
            "key": "operator_confirmed_telegram_dispatch_archive_summary",
            "label": "操作員確認本階段只整理 archive summary input",
            "passed": bool(
                operator["operator_confirmed_telegram_dispatch_archive_summary"]
                and operator["operator_confirmed_summary_is_read_only"]
                and operator["operator_confirmed_message_and_artifacts_reviewed"]
                and operator["operator_confirmed_dispatch_audit_reviewed"]
                and operator["operator_confirmed_report_input_requires_separate_gate"]
            ),
        },
        {
            "key": "operator_confirmed_archive_summary_runtime_boundaries",
            "label": "操作員確認本階段不派送 Telegram、不寫 DB、不呼叫 LLM、不掛 scheduler",
            "passed": bool(
                operator["operator_confirmed_no_token_in_artifacts"]
                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": "telegram_dispatch_archive_summary_artifact_path_recorded",
            "label": "archive summary artifact path 必須由操作員提供",
            "passed": bool(operator["telegram_dispatch_archive_summary_artifact_path"]),
        },
        {
            "key": "telegram_dispatch_archive_summary_no_token_submitted_to_api",
            "label": "archive summary payload 不得包含 approval 或 Telegram token key",
            "passed": not operator["forbidden_token_submitted_to_api"],
        },
        {
            "key": "telegram_dispatch_archive_summary_apply_real_write_not_requested_from_api",
            "label": "API/UI archive summary 不接受 apply_real_write",
            "passed": not apply_real_write,
        },
    ]


def build_candidate_queue_review_ai_summary_persistence_telegram_dispatch_archive_summary(
    *,
    telegram_dispatch_archive,
    operator_evidence=None,
    execute_requested=False,
    apply_real_write=False,
):
    """建立 Telegram dispatch archive summary gate；不執行任何副作用。"""
    archive_summary = _archive_payload_summary(telegram_dispatch_archive)
    operator = _operator_summary(operator_evidence)
    sections = _summary_sections(archive_summary)
    gates = _summary_gates(archive_summary, operator, bool(apply_real_write))
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    summary_ready = bool(not blocked_reasons)

    return {
        "mode": "candidate_queue_review_ai_summary_persistence_telegram_dispatch_archive_summary_preview",
        "target_table": TARGET_TABLE,
        "target_column": TARGET_COLUMN,
        "target_json_path": [SUMMARY_METADATA_KEY],
        "target_operation": "prepare_manual_ai_summary_telegram_dispatch_archive_summary_input",
        "execute_requested": bool(execute_requested),
        "apply_real_write_requested": bool(apply_real_write),
        "archive_summary_reviewed": True,
        "telegram_dispatch_archive_summary_ready": summary_ready,
        "summary_persistence_telegram_dispatch_archive_summary_ready": summary_ready,
        "summary_input_ready": summary_ready,
        "ready_for_next_manual_phase": summary_ready,
        "ready_for_summary_persistence_telegram_dispatch_report_input": summary_ready,
        "ready_for_ai_summary_generation": False,
        "ready_for_llm_call": False,
        "ready_for_telegram_dispatch": False,
        "ready_for_manual_telegram_dispatch": False,
        "ready_for_api_database_write": False,
        "ready_for_scheduler_attach": 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_summary_file_written": False,
        "archive_summary_file_written": False,
        "telegram_dispatch_archive_file_written": False,
        "telegram_dispatch_closeout_file_written": False,
        "telegram_dispatch_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": archive_summary["statement_count"],
        "expected_summary_payload_hash": archive_summary[
            "expected_summary_payload_hash"
        ],
        "blocked_reasons": blocked_reasons,
        "gates": gates,
        "telegram_dispatch_archive_summary": archive_summary,
        "telegram_dispatch_archive_summary_sections": sections,
        "operator_telegram_dispatch_archive_summary": operator,
        "promotion_gate": {
            "allowed": summary_ready,
            "next_manual_phase": "summary_persistence_telegram_dispatch_report_input",
            "requires_real_db_write": False,
            "requires_scheduler_attach": False,
            "requires_operator_approval": True,
            "future_report_input_requires_separate_gate": True,
            "api_must_not_dispatch_telegram": True,
        },
        "next_operator_steps": [
            "保存 Telegram dispatch archive summary artifact path",
            "確認 summary sections 只包含 message identity、audit 與 artifact path 摘要",
            "後續若要輸出報表或週報輸入，必須另開 report input gate",
            "不得從 archive summary API 呼叫 LLM、補發 Telegram、寫 DB 或寫 artifact",
        ],
        "safe_boundaries": [
            "do_not_read_approval_token_from_telegram_dispatch_archive_summary_api",
            "do_not_read_telegram_token_from_telegram_dispatch_archive_summary_api",
            "do_not_call_llm_from_telegram_dispatch_archive_summary",
            "do_not_dispatch_telegram_from_telegram_dispatch_archive_summary_api",
            "do_not_retry_telegram_dispatch_from_archive_summary_api",
            "do_not_open_database_connection_from_telegram_dispatch_archive_summary",
            "do_not_write_archive_summary_artifact_from_api",
            "do_not_update_review_state_from_telegram_dispatch_archive_summary",
            "do_not_attach_scheduler_from_telegram_dispatch_archive_summary",
            "future_report_input_must_use_separate_gate",
            "telegram_dispatch_archive_summary_preview_only",
            "no_remove_orphans",
            "no_momo_db_lifecycle_change",
        ],
    }
