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

本模組只把 Telegram dispatch gate 後的人工派送包整理成可審核預覽；
不讀 approval/Telegram token、不呼叫 LLM、不派送 Telegram、不開 DB、
不寫檔、不更新 review_state、不 commit、不掛 scheduler。
"""

import hashlib
import json


FORBIDDEN_TOKEN_KEYWORDS = (
    "approval_token",
    "approval-token",
    "market_intel_queue_write_approval",
    "telegram_bot_token",
    "telegram-token",
)
SAFE_TOKEN_METADATA_KEYS = {
    "approval_token_present",
    "approval_token_valid",
    "approval_token_secret_configured",
    "telegram_token_present",
}
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 _has_text(value):
    return bool(isinstance(value, str) and value.strip())


def _safe_text(value, limit=300):
    if value is None:
        return None
    text = str(value).strip()
    return text[:limit] if text else None


def _stable_hash(value):
    encoded = json.dumps(
        value,
        ensure_ascii=False,
        sort_keys=True,
        separators=(",", ":"),
    ).encode("utf-8")
    return hashlib.sha256(encoded).hexdigest()


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(payload):
    blocked_keys = (
        "ready_for_api_database_write",
        "ready_for_telegram_dispatch",
        "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_gate_file_written",
        "telegram_dispatch_run_package_file_written",
        "telegram_message_file_written",
        "summary_file_written",
        "summary_record_written",
        "summary_persistence_record_written",
        "metadata_patch_written",
        "database_connection_opened",
        "database_session_created",
        "explicit_transaction_opened",
        "transaction_opened",
        "transaction_committed",
        "database_write_executed",
        "database_commit_executed",
        "review_state_update_executed",
        "llm_call_executed",
        "ollama_call_executed",
        "gemini_call_executed",
        "telegram_dispatched",
        "telegram_dispatch_attempted",
        "external_network_executed",
        "scheduler_attached",
        "writes_executed",
        "would_write_database",
    )
    payload = _as_dict(payload)
    return all(not payload.get(key) for key in blocked_keys)


def _gate_summary(dispatch_gate):
    gate = _as_dict(dispatch_gate)
    contract = _as_dict(gate.get("telegram_message_contract"))
    promotion = _as_dict(gate.get("promotion_gate"))
    closeout = _as_dict(gate.get("closeout_summary"))
    return {
        "provided": bool(gate),
        "mode": gate.get("mode"),
        "target_operation": gate.get("target_operation"),
        "target_json_path": _as_list(gate.get("target_json_path")),
        "telegram_dispatch_gate_passed": bool(
            gate.get("telegram_dispatch_gate_passed")
            and gate.get("summary_persistence_telegram_dispatch_gate_passed")
        ),
        "ready_for_summary_persistence_telegram_dispatch_run_package": bool(
            gate.get("ready_for_summary_persistence_telegram_dispatch_run_package")
        ),
        "ready_for_manual_telegram_dispatch_run_package": bool(
            gate.get("ready_for_manual_telegram_dispatch_run_package")
        ),
        "promotion_allowed": bool(promotion.get("allowed")),
        "promotion_next_manual_phase": promotion.get("next_manual_phase"),
        "expected_dedupe_key_count": int(
            contract.get("expected_dedupe_key_count")
            or closeout.get("expected_dedupe_key_count")
            or 0
        ),
        "expected_summary_payload_hash": (
            contract.get("expected_summary_payload_hash")
            or closeout.get("expected_summary_payload_hash")
        ),
        "message_contract": contract,
        "message_contract_hash": _stable_hash(contract),
        "side_effects_clear": _side_effects_clear(gate),
        "blocked_reasons": _as_list(gate.get("blocked_reasons")),
    }


def _operator_summary(operator_evidence):
    operator_evidence = _as_dict(operator_evidence)
    return {
        "provided_keys": sorted(operator_evidence.keys()),
        "operator_confirmed_ai_summary_telegram_dispatch_run_package": bool(
            operator_evidence.get(
                "operator_confirmed_ai_summary_telegram_dispatch_run_package"
            )
            or operator_evidence.get("operator_confirmed_telegram_dispatch_run_package")
        ),
        "operator_confirmed_message_contract_reviewed": bool(
            operator_evidence.get("operator_confirmed_message_contract_reviewed")
            or operator_evidence.get("operator_confirmed_telegram_message_reviewed")
        ),
        "operator_confirmed_command_bundle_reviewed": bool(
            operator_evidence.get("operator_confirmed_command_bundle_reviewed")
        ),
        "operator_confirmed_dispatch_is_manual_only": bool(
            operator_evidence.get("operator_confirmed_dispatch_is_manual_only")
            or operator_evidence.get("operator_confirmed_manual_dispatch_only")
        ),
        "operator_confirmed_no_api_telegram_dispatch": bool(
            operator_evidence.get("operator_confirmed_no_api_telegram_dispatch")
            or operator_evidence.get("operator_confirmed_no_telegram_dispatch")
        ),
        "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_no_api_db_write": bool(
            operator_evidence.get("operator_confirmed_no_api_db_write")
        ),
        "telegram_dispatch_gate_artifact_path": _safe_text(
            operator_evidence.get("ai_summary_telegram_dispatch_gate_artifact_path")
            or operator_evidence.get("telegram_dispatch_gate_artifact_path")
        ),
        "telegram_dispatch_run_package_artifact_path": _safe_text(
            operator_evidence.get(
                "ai_summary_telegram_dispatch_run_package_artifact_path"
            )
            or operator_evidence.get("telegram_dispatch_run_package_artifact_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")
        ),
        "telegram_channel_label": _safe_text(
            operator_evidence.get("telegram_channel_label")
            or operator_evidence.get("telegram_dispatch_channel")
            or operator_evidence.get("notification_channel")
        ),
        "forbidden_token_submitted_to_api": _contains_forbidden_token_key(
            operator_evidence
        ),
    }


def _message_package_manifest(gate_summary, operator):
    contract = gate_summary["message_contract"]
    manifest = {
        "source_table": TARGET_TABLE,
        "source_column": TARGET_COLUMN,
        "source_json_path": [SUMMARY_METADATA_KEY],
        "message_contract_hash": gate_summary["message_contract_hash"],
        "target_channel": contract.get("target_channel") or operator["telegram_channel_label"],
        "message_format": contract.get("message_format"),
        "max_message_chars": contract.get("max_message_chars"),
        "expected_dedupe_key_count": gate_summary["expected_dedupe_key_count"],
        "expected_summary_payload_hash": gate_summary[
            "expected_summary_payload_hash"
        ],
        "requires_evidence_refs": bool(contract.get("requires_evidence_refs")),
        "requires_summary_payload_hash": bool(
            contract.get("requires_summary_payload_hash")
        ),
        "approval_tokens_allowed_in_message": bool(
            contract.get("approval_tokens_allowed_in_message")
        ),
        "api_dispatches_telegram": bool(contract.get("api_dispatches_telegram")),
        "scheduler_dispatches_telegram": bool(
            contract.get("scheduler_dispatches_telegram")
        ),
        "redaction_policy": [
            "do_not_include_approval_token",
            "do_not_include_telegram_bot_token",
            "do_not_include_login_or_member_data",
            "do_not_include_raw_html",
        ],
    }
    return {**manifest, "manifest_hash": _stable_hash(manifest)}


def _command_bundle(manifest):
    return [
        {
            "step": 1,
            "key": "save_run_package",
            "command_shape": (
                "mkdir -p artifacts/market_intel && write run package JSON to "
                "artifacts/market_intel/ai-summary-telegram-dispatch-run-package-YYYYMMDD-HHMMSS.json"
            ),
            "executes_telegram": False,
            "executes_database": False,
            "executed": False,
        },
        {
            "step": 2,
            "key": "render_message_preview",
            "command_shape": (
                "python3 scripts/market_intel_ai_summary_telegram_dispatch.py "
                "--source metadata_json.ai_summary_review --render-preview-only "
                "--channel-label "
                f"{manifest.get('target_channel') or 'telegram_manual_gate'} "
                "> artifacts/market_intel/ai-summary-telegram-message-preview.json"
            ),
            "executes_telegram": False,
            "executes_database": False,
            "executed": False,
        },
        {
            "step": 3,
            "key": "operator_message_review",
            "command_shape": "operator reviews rendered message preview and evidence refs",
            "executes_telegram": False,
            "executes_database": False,
            "executed": False,
        },
        {
            "step": 4,
            "key": "manual_telegram_dispatch",
            "command_shape": (
                "TELEGRAM_BOT_TOKEN=... python3 "
                "scripts/market_intel_ai_summary_telegram_dispatch.py "
                "--message-preview artifacts/market_intel/ai-summary-telegram-message-preview.json "
                "--execute --manual-operator-approved"
            ),
            "executes_telegram": True,
            "executes_database": False,
            "executed": False,
        },
        {
            "step": 5,
            "key": "dispatch_receipt",
            "command_shape": (
                "save Telegram response and operator receipt to "
                "artifacts/market_intel/ai-summary-telegram-dispatch-receipt.json"
            ),
            "executes_telegram": False,
            "executes_database": False,
            "executed": False,
        },
    ]


def _package_gates(gate_summary, operator, manifest, apply_real_write):
    return [
        {
            "key": "telegram_dispatch_gate_ready",
            "label": "Telegram dispatch gate 必須已通過並放行到 run package",
            "passed": bool(
                gate_summary["mode"]
                == "candidate_queue_review_ai_summary_persistence_telegram_dispatch_gate_preview"
                and gate_summary["telegram_dispatch_gate_passed"]
                and gate_summary[
                    "ready_for_summary_persistence_telegram_dispatch_run_package"
                ]
                and gate_summary["ready_for_manual_telegram_dispatch_run_package"]
                and gate_summary["promotion_allowed"]
                and gate_summary["promotion_next_manual_phase"]
                == "summary_persistence_telegram_dispatch_run_package"
            ),
        },
        {
            "key": "telegram_message_contract_ready",
            "label": "Telegram message contract 必須包含 channel、format、evidence refs 與 summary hash",
            "passed": bool(
                manifest["target_channel"]
                and manifest["message_format"] == "market_intel_ai_summary_brief"
                and manifest["requires_evidence_refs"]
                and manifest["requires_summary_payload_hash"]
                and manifest["expected_summary_payload_hash"]
                and manifest["expected_dedupe_key_count"] > 0
            ),
        },
        {
            "key": "telegram_message_contract_no_api_or_scheduler_dispatch",
            "label": "message contract 必須禁止 API/scheduler dispatch 且不得允許 token 進訊息",
            "passed": bool(
                not manifest["api_dispatches_telegram"]
                and not manifest["scheduler_dispatches_telegram"]
                and not manifest["approval_tokens_allowed_in_message"]
            ),
        },
        {
            "key": "operator_confirmed_telegram_dispatch_run_package",
            "label": "操作員確認本步只整理人工 Telegram dispatch run package",
            "passed": bool(
                operator["operator_confirmed_ai_summary_telegram_dispatch_run_package"]
                and operator["operator_confirmed_message_contract_reviewed"]
                and operator["operator_confirmed_command_bundle_reviewed"]
                and operator["operator_confirmed_dispatch_is_manual_only"]
                and operator["operator_confirmed_no_api_telegram_dispatch"]
                and operator["operator_confirmed_no_llm_call"]
                and operator["operator_confirmed_no_api_db_write"]
                and operator["operator_confirmed_no_scheduler_attach"]
            ),
        },
        {
            "key": "telegram_dispatch_run_package_artifacts_recorded",
            "label": "dispatch gate、run package 與 message preview artifact path 必須齊備",
            "passed": bool(
                operator["telegram_dispatch_gate_artifact_path"]
                and operator["telegram_dispatch_run_package_artifact_path"]
                and operator["telegram_message_preview_artifact_path"]
            ),
        },
        {
            "key": "telegram_dispatch_run_package_no_token_submitted_to_api",
            "label": "payload 不得包含 approval 或 Telegram token key",
            "passed": not operator["forbidden_token_submitted_to_api"],
        },
        {
            "key": "telegram_dispatch_run_package_apply_real_write_not_requested_from_api",
            "label": "API/UI run package 不接受 apply_real_write",
            "passed": not apply_real_write,
        },
        {
            "key": "telegram_dispatch_gate_has_no_side_effects",
            "label": "上游 gate 不得已有 DB/檔案/LLM/Telegram/scheduler 副作用",
            "passed": gate_summary["side_effects_clear"],
        },
    ]


def build_candidate_queue_review_ai_summary_persistence_telegram_dispatch_run_package(
    *,
    telegram_dispatch_gate,
    operator_evidence=None,
    execute_requested=False,
    apply_real_write=False,
):
    """建立 Telegram dispatch run package preview；不執行派送或副作用。"""
    gate_summary = _gate_summary(telegram_dispatch_gate)
    operator = _operator_summary(operator_evidence)
    manifest = _message_package_manifest(gate_summary, operator)
    command_bundle = _command_bundle(manifest)
    gates = _package_gates(
        gate_summary,
        operator,
        manifest,
        bool(apply_real_write),
    )
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    package_ready = bool(not blocked_reasons)

    return {
        "mode": "candidate_queue_review_ai_summary_persistence_telegram_dispatch_run_package_preview",
        "target_table": TARGET_TABLE,
        "target_column": TARGET_COLUMN,
        "target_json_path": [SUMMARY_METADATA_KEY],
        "target_operation": "prepare_ai_summary_telegram_dispatch_run_package",
        "execute_requested": bool(execute_requested),
        "apply_real_write_requested": bool(apply_real_write),
        "package_ready": package_ready,
        "telegram_dispatch_run_package_ready": package_ready,
        "summary_persistence_telegram_dispatch_run_package_ready": package_ready,
        "ready_for_next_manual_phase": package_ready,
        "ready_for_summary_persistence_telegram_dispatch_run_readiness": package_ready,
        "ready_for_manual_telegram_dispatch": False,
        "ready_for_telegram_dispatch": False,
        "ready_for_api_database_write": False,
        "ready_for_scheduler_attach": False,
        "ready_for_llm_call": 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_package_file_written": False,
        "run_package_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": manifest["expected_dedupe_key_count"],
        "message_package_manifest": manifest,
        "command_bundle": command_bundle,
        "package_gates": gates,
        "blocked_reasons": blocked_reasons,
        "telegram_dispatch_gate_summary": gate_summary,
        "operator_telegram_dispatch_run_package": operator,
        "required_artifacts": [
            {
                "key": "telegram_dispatch_gate_json",
                "label": "操作員保存的 Telegram dispatch gate JSON",
                "path_shape": "artifacts/market_intel/ai-summary-telegram-dispatch-gate-YYYYMMDD-HHMMSS.json",
                "created_by_api": False,
            },
            {
                "key": "telegram_dispatch_run_package_json",
                "label": "操作員保存的 Telegram dispatch run package JSON",
                "path_shape": "artifacts/market_intel/ai-summary-telegram-dispatch-run-package-YYYYMMDD-HHMMSS.json",
                "created_by_api": False,
            },
            {
                "key": "telegram_message_preview_json",
                "label": "正式派送前的 message preview JSON",
                "path_shape": "artifacts/market_intel/ai-summary-telegram-message-preview-YYYYMMDD-HHMMSS.json",
                "created_by_api": False,
            },
            {
                "key": "telegram_dispatch_receipt_json",
                "label": "人工派送後的 Telegram response / receipt JSON",
                "path_shape": "artifacts/market_intel/ai-summary-telegram-dispatch-receipt-YYYYMMDD-HHMMSS.json",
                "created_by_api": False,
            },
        ],
        "promotion_gate": {
            "allowed": package_ready,
            "next_manual_phase": "summary_persistence_telegram_dispatch_run_readiness",
            "requires_real_db_write": False,
            "requires_scheduler_attach": False,
            "requires_operator_approval": True,
            "api_must_not_dispatch_telegram": True,
        },
        "next_operator_steps": [
            "保存 Telegram dispatch run package 與 message preview artifact",
            "人工確認訊息只包含 DB 實證、summary hash 與 evidence refs",
            "下一階段 run readiness 才檢查 token 只能在 shell 提供",
            "任何 gate 阻擋時，停在 Telegram dispatch gate 階段",
        ],
        "safe_boundaries": [
            "do_not_read_approval_token_from_telegram_dispatch_run_package_api",
            "do_not_read_telegram_token_from_telegram_dispatch_run_package_api",
            "do_not_call_llm_from_telegram_dispatch_run_package",
            "do_not_dispatch_telegram_from_telegram_dispatch_run_package_api",
            "do_not_open_database_connection_from_telegram_dispatch_run_package",
            "do_not_write_dispatch_artifact_from_telegram_dispatch_run_package_api",
            "do_not_update_review_state_from_telegram_dispatch_run_package",
            "do_not_attach_scheduler_from_telegram_dispatch_run_package",
            "future_telegram_dispatch_must_use_readiness_receipt_closeout",
            "telegram_message_must_not_include_tokens",
            "no_remove_orphans",
            "no_momo_db_lifecycle_change",
        ],
    }
