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

本模組只審核人工 Telegram 派送後貼回的 receipt；不讀 approval 或
Telegram token、不呼叫 LLM、不補發 Telegram、不開 DB、不寫檔、不更新
review_state、不 commit、不掛 scheduler。
"""


FORBIDDEN_TOKEN_KEYWORDS = (
    "approval_token",
    "approval-token",
    "market_intel_queue_write_approval",
    "telegram_bot_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"
EXPECTED_RECEIPT_MODES = {
    "candidate_queue_review_ai_summary_telegram_dispatch_manual_receipt",
    "market_intel_ai_summary_telegram_dispatch_manual_receipt",
    "telegram_dispatch_manual_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 _safe_text(value, limit=300):
    if value is None:
        return None
    text = str(value).strip()
    return text[:limit] if text else None


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 _hash_matches_expected(expected_hash, observed_hash):
    return bool(expected_hash and observed_hash and str(expected_hash) == str(observed_hash))


def _run_readiness_summary(run_readiness):
    run_readiness = _as_dict(run_readiness)
    package = _as_dict(run_readiness.get("telegram_dispatch_run_package_summary"))
    return {
        "provided": bool(run_readiness),
        "mode": run_readiness.get("mode"),
        "run_readiness_ready": bool(
            run_readiness.get("telegram_dispatch_run_readiness_ready")
            or run_readiness.get("run_readiness_ready")
        ),
        "ready_for_manual_telegram_dispatch": bool(
            run_readiness.get("ready_for_manual_telegram_dispatch")
        ),
        "ready_for_summary_persistence_telegram_dispatch_run_receipt": bool(
            run_readiness.get(
                "ready_for_summary_persistence_telegram_dispatch_run_receipt"
            )
        ),
        "target_channel": package.get("target_channel"),
        "message_format": package.get("message_format"),
        "expected_dedupe_key_count": _safe_int(
            package.get("expected_dedupe_key_count")
            or run_readiness.get("statement_count")
        ),
        "expected_summary_payload_hash": package.get("expected_summary_payload_hash"),
        "manifest_hash": package.get("manifest_hash"),
        "manual_dispatch_command_present": bool(
            package.get("manual_dispatch_command_present")
        ),
        "commands_executed": bool(package.get("commands_executed")),
        "side_effects_clear": bool(package.get("side_effects_clear")),
        "blocked_reasons": _as_list(run_readiness.get("blocked_reasons")),
    }


def _receipt_payload(operator_evidence, telegram_dispatch_receipt):
    operator_evidence = _as_dict(operator_evidence)
    receipt = _as_dict(telegram_dispatch_receipt)
    embedded = _as_dict(
        operator_evidence.get("telegram_dispatch_receipt")
        or operator_evidence.get("telegram_dispatch_receipt_json")
        or operator_evidence.get("ai_summary_telegram_dispatch_receipt")
    )
    return receipt or embedded


def _receipt_summary(receipt, expected_hash):
    receipt = _as_dict(receipt)
    response = _as_dict(
        receipt.get("telegram_response")
        or receipt.get("response")
        or receipt.get("api_response")
    )
    result = _as_dict(response.get("result") or receipt.get("result"))
    message_id = (
        receipt.get("message_id")
        or response.get("message_id")
        or result.get("message_id")
    )
    chat = _as_dict(result.get("chat") or response.get("chat") or receipt.get("chat"))
    chat_id = receipt.get("chat_id") or response.get("chat_id") or chat.get("id")
    channel = (
        receipt.get("telegram_channel_label")
        or receipt.get("target_channel")
        or receipt.get("channel")
        or chat.get("username")
        or chat.get("title")
    )
    observed_hash = (
        receipt.get("summary_payload_hash")
        or receipt.get("expected_summary_payload_hash")
        or receipt.get("payload_hash")
    )
    return {
        "provided": bool(receipt),
        "mode": receipt.get("mode"),
        "ok": bool(receipt.get("ok") or receipt.get("success") or response.get("ok")),
        "telegram_dispatch_attempted": bool(
            receipt.get("telegram_dispatch_attempted")
            or receipt.get("dispatch_attempted")
        ),
        "telegram_dispatched": bool(
            receipt.get("telegram_dispatched")
            or receipt.get("dispatch_success")
            or receipt.get("message_sent")
        ),
        "message_id": _safe_text(message_id, 120),
        "chat_id": _safe_text(chat_id, 120),
        "telegram_channel_label": _safe_text(channel, 180),
        "sent_at": _safe_text(
            receipt.get("sent_at")
            or receipt.get("dispatched_at")
            or receipt.get("created_at"),
            120,
        ),
        "summary_payload_hash": _safe_text(observed_hash, 80),
        "expected_summary_payload_hash": _safe_text(expected_hash, 80),
        "summary_payload_hash_matches_expected": _hash_matches_expected(
            expected_hash,
            observed_hash,
        ),
        "database_write_executed": bool(receipt.get("database_write_executed")),
        "database_commit_executed": bool(receipt.get("database_commit_executed")),
        "api_updates_review_state": bool(receipt.get("api_updates_review_state")),
        "review_state_update_executed": bool(
            receipt.get("review_state_update_executed")
        ),
        "llm_call_executed": bool(receipt.get("llm_call_executed")),
        "external_network_executed": bool(receipt.get("external_network_executed")),
        "scheduler_attached": bool(receipt.get("scheduler_attached")),
        "api_dispatches_telegram": bool(receipt.get("api_dispatches_telegram")),
        "approval_or_telegram_token_key_detected": _contains_forbidden_token_key(
            receipt
        ),
    }


def _operator_summary(operator_evidence):
    operator_evidence = _as_dict(operator_evidence)
    return {
        "provided_keys": sorted(operator_evidence.keys()),
        "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")
        ),
        "telegram_message_preview_artifact_path_recorded": _has_text(
            operator_evidence.get("telegram_message_preview_artifact_path")
            or operator_evidence.get("ai_summary_telegram_message_preview_artifact_path")
        ),
        "operator_confirmed_telegram_dispatch_receipt": bool(
            operator_evidence.get(
                "operator_confirmed_ai_summary_telegram_dispatch_run_receipt"
            )
            or operator_evidence.get("operator_confirmed_telegram_dispatch_receipt")
        ),
        "operator_confirmed_message_id_recorded": bool(
            operator_evidence.get("operator_confirmed_message_id_recorded")
        ),
        "operator_confirmed_summary_hash_matched": bool(
            operator_evidence.get("operator_confirmed_summary_hash_matched")
        ),
        "operator_confirmed_no_token_in_receipt": bool(
            operator_evidence.get("operator_confirmed_no_token_in_receipt")
            or operator_evidence.get("operator_confirmed_no_token_in_artifacts")
        ),
        "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")
        ),
        "receipt_notes_recorded": _has_text(operator_evidence.get("receipt_notes")),
        "forbidden_token_submitted_to_api": _contains_forbidden_token_key(
            operator_evidence
        ),
    }


def _receipt_gates(
    *,
    run_readiness,
    receipt,
    operator,
    apply_real_write,
):
    return [
        {
            "key": "telegram_dispatch_run_readiness_passed_before_manual_dispatch",
            "label": "Telegram dispatch run readiness 必須先通過",
            "passed": bool(
                run_readiness["mode"]
                == "candidate_queue_review_ai_summary_persistence_telegram_dispatch_run_readiness_preview"
                and run_readiness["run_readiness_ready"]
                and run_readiness["ready_for_manual_telegram_dispatch"]
                and run_readiness[
                    "ready_for_summary_persistence_telegram_dispatch_run_receipt"
                ]
            ),
        },
        {
            "key": "telegram_dispatch_receipt_provided",
            "label": "操作員需貼回人工 Telegram dispatch receipt",
            "passed": receipt["provided"],
        },
        {
            "key": "telegram_dispatch_receipt_mode_and_success",
            "label": "receipt 必須是人工 Telegram dispatch 且回傳成功",
            "passed": bool(
                receipt["mode"] in EXPECTED_RECEIPT_MODES
                and receipt["ok"]
                and receipt["telegram_dispatch_attempted"]
                and receipt["telegram_dispatched"]
            ),
        },
        {
            "key": "telegram_dispatch_receipt_message_id_recorded",
            "label": "receipt 必須有 Telegram message id 與 chat/channel",
            "passed": bool(
                receipt["message_id"]
                and receipt["chat_id"]
                and receipt["telegram_channel_label"]
            ),
        },
        {
            "key": "telegram_dispatch_receipt_summary_hash_matches_expected",
            "label": "receipt 的 summary payload hash 必須符合 readiness manifest",
            "passed": receipt["summary_payload_hash_matches_expected"],
        },
        {
            "key": "telegram_dispatch_receipt_runtime_boundaries",
            "label": "receipt 不得顯示 DB write、LLM、scheduler、review_state 或 API dispatch",
            "passed": bool(
                not receipt["database_write_executed"]
                and not receipt["database_commit_executed"]
                and not receipt["api_updates_review_state"]
                and not receipt["review_state_update_executed"]
                and not receipt["llm_call_executed"]
                and not receipt["scheduler_attached"]
                and not receipt["api_dispatches_telegram"]
            ),
        },
        {
            "key": "telegram_dispatch_receipt_no_token_key",
            "label": "receipt 不得包含 approval 或 Telegram token key",
            "passed": not receipt["approval_or_telegram_token_key_detected"],
        },
        {
            "key": "operator_confirmed_telegram_dispatch_receipt",
            "label": "操作員確認 receipt、message id、summary hash、無 token、無 API dispatch",
            "passed": bool(
                operator["telegram_dispatch_receipt_artifact_path_recorded"]
                and operator["telegram_message_preview_artifact_path_recorded"]
                and operator["operator_confirmed_telegram_dispatch_receipt"]
                and operator["operator_confirmed_message_id_recorded"]
                and operator["operator_confirmed_summary_hash_matched"]
                and operator["operator_confirmed_no_token_in_receipt"]
                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_run_receipt_no_token_submitted_to_api",
            "label": "payload 不得包含 approval 或 Telegram token key",
            "passed": not operator["forbidden_token_submitted_to_api"],
        },
        {
            "key": "telegram_dispatch_run_receipt_apply_real_write_not_requested_from_api",
            "label": "API/UI receipt review 不接受 apply_real_write",
            "passed": not apply_real_write,
        },
    ]


def build_candidate_queue_review_ai_summary_persistence_telegram_dispatch_run_receipt(
    *,
    telegram_dispatch_run_readiness,
    telegram_dispatch_receipt=None,
    operator_evidence=None,
    execute_requested=False,
    apply_real_write=False,
):
    """建立 Telegram dispatch receipt review；不補發 Telegram 或執行副作用。"""
    run_readiness = _run_readiness_summary(telegram_dispatch_run_readiness)
    receipt_payload = _receipt_payload(operator_evidence, telegram_dispatch_receipt)
    receipt = _receipt_summary(
        receipt_payload,
        run_readiness["expected_summary_payload_hash"],
    )
    operator = _operator_summary(operator_evidence)
    gates = _receipt_gates(
        run_readiness=run_readiness,
        receipt=receipt,
        operator=operator,
        apply_real_write=bool(apply_real_write),
    )
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    receipt_passed = bool(not blocked_reasons)

    return {
        "mode": "candidate_queue_review_ai_summary_persistence_telegram_dispatch_run_receipt_preview",
        "target_table": TARGET_TABLE,
        "target_column": TARGET_COLUMN,
        "target_json_path": [SUMMARY_METADATA_KEY],
        "target_operation": "review_manual_ai_summary_telegram_dispatch_receipt",
        "execute_requested": bool(execute_requested),
        "apply_real_write_requested": bool(apply_real_write),
        "receipt_reviewed": True,
        "run_receipt_passed": receipt_passed,
        "telegram_dispatch_run_receipt_passed": receipt_passed,
        "summary_persistence_telegram_dispatch_run_receipt_passed": receipt_passed,
        "ready_for_next_manual_phase": receipt_passed,
        "ready_for_summary_persistence_telegram_dispatch_closeout": receipt_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,
        "package_artifact_created": False,
        "telegram_dispatch_run_receipt_file_written": False,
        "telegram_dispatch_receipt_file_written": False,
        "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": run_readiness["expected_dedupe_key_count"],
        "expected_summary_payload_hash": run_readiness["expected_summary_payload_hash"],
        "blocked_reasons": blocked_reasons,
        "gates": gates,
        "telegram_dispatch_run_readiness_summary": run_readiness,
        "telegram_dispatch_receipt_summary": receipt,
        "operator_telegram_dispatch_run_receipt": operator,
        "promotion_gate": {
            "allowed": receipt_passed,
            "next_manual_phase": "summary_persistence_telegram_dispatch_closeout",
            "requires_real_db_write": False,
            "requires_scheduler_attach": False,
            "requires_operator_approval": True,
            "api_must_not_dispatch_telegram": True,
        },
        "next_operator_steps": [
            "保存人工 Telegram dispatch receipt artifact",
            "人工確認 message id、channel、summary payload hash 與 evidence refs",
            "只在 receipt 通過後進入 Telegram dispatch closeout",
            "不得從 API/UI 補發 Telegram、重送訊息、寫 DB 或掛 scheduler",
        ],
        "safe_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",
            "future_telegram_dispatch_closeout_must_use_separate_gate",
            "telegram_receipt_must_not_include_tokens",
            "no_remove_orphans",
            "no_momo_db_lifecycle_change",
        ],
    }
