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

本模組只把正式 CLI 寫入 metadata_json 前需要保存的 payload、命令、
證據與回退資訊整理成可審核預覽；不讀 approval token、不寫本機檔案、
不開 DB connection、不執行 CLI、不寫 metadata_json、不 commit、不掛 scheduler。
"""

import hashlib
import json


FORBIDDEN_TOKEN_KEYWORDS = (
    "approval_token",
    "approval-token",
    "market_intel_queue_write_approval",
)
SAFE_TOKEN_METADATA_KEYS = {
    "approval_token_present",
    "approval_token_valid",
    "approval_token_secret_configured",
}
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_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 == 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_api_database_write",
        "ready_for_telegram_dispatch",
        "ready_for_scheduler_attach",
        "api_executes_cli",
        "api_executes_llm",
        "api_reads_approval_token",
        "api_writes_file",
        "api_writes_database",
        "api_updates_review_state",
        "summary_persistence_run_package_file_written",
        "run_package_file_written",
        "package_artifact_created",
        "summary_persistence_writer_preflight_file_written",
        "summary_persistence_transaction_file_written",
        "summary_file_written",
        "summary_record_written",
        "summary_persistence_record_written",
        "metadata_patch_written",
        "transaction_file_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",
        "external_network_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 _operator_summary(operator_evidence):
    operator_evidence = _as_dict(operator_evidence)
    return {
        "provided_keys": sorted(operator_evidence.keys()),
        "operator_confirmed_ai_summary_persistence_run_package": bool(
            operator_evidence.get("operator_confirmed_ai_summary_persistence_run_package")
            or operator_evidence.get("operator_confirmed_summary_persistence_run_package")
        ),
        "operator_confirmed_payload_manifest_reviewed": bool(
            operator_evidence.get("operator_confirmed_payload_manifest_reviewed")
        ),
        "operator_confirmed_cli_command_reviewed": bool(
            operator_evidence.get("operator_confirmed_cli_command_reviewed")
        ),
        "operator_confirmed_summary_persistence_is_cli_only": bool(
            operator_evidence.get("operator_confirmed_summary_persistence_is_cli_only")
            or operator_evidence.get("operator_confirmed_persistence_requires_cli")
        ),
        "operator_confirmed_no_api_db_write": bool(
            operator_evidence.get("operator_confirmed_no_api_db_write")
        ),
        "operator_confirmed_no_telegram_dispatch": bool(
            operator_evidence.get("operator_confirmed_no_telegram_dispatch")
        ),
        "operator_confirmed_no_scheduler_attach": bool(
            operator_evidence.get("operator_confirmed_no_scheduler_attach")
        ),
        "ai_summary_persistence_transaction_artifact_path": _safe_text(
            operator_evidence.get("ai_summary_persistence_transaction_artifact_path")
            or operator_evidence.get("summary_persistence_transaction_artifact_path")
        ),
        "ai_summary_persistence_writer_preflight_artifact_path": _safe_text(
            operator_evidence.get(
                "ai_summary_persistence_writer_preflight_artifact_path"
            )
            or operator_evidence.get("summary_persistence_writer_preflight_artifact_path")
        ),
        "ai_summary_persistence_run_package_artifact_path": _safe_text(
            operator_evidence.get("ai_summary_persistence_run_package_artifact_path")
            or operator_evidence.get("summary_persistence_run_package_artifact_path")
        ),
        "metadata_json_backup_artifact_path": _safe_text(
            operator_evidence.get("metadata_json_backup_artifact_path")
            or operator_evidence.get("summary_metadata_backup_artifact_path")
        ),
        "approval_token_submitted_to_api": _contains_forbidden_token_key(
            operator_evidence
        ),
    }


def _writer_preflight_summary(writer_preflight):
    writer_preflight = _as_dict(writer_preflight)
    contract = _as_dict(writer_preflight.get("writer_preflight_contract"))
    payloads = [_as_dict(item) for item in _as_list(writer_preflight.get("statement_payloads"))]
    return {
        "provided": bool(writer_preflight),
        "mode": writer_preflight.get("mode"),
        "summary_persistence_writer_preflight_ready": bool(
            writer_preflight.get("summary_persistence_writer_preflight_ready")
        ),
        "ready_for_summary_persistence_run_package": bool(
            writer_preflight.get("ready_for_summary_persistence_run_package")
        ),
        "statement_count": int(writer_preflight.get("statement_count") or 0),
        "invalid_statement_count": int(
            writer_preflight.get("invalid_statement_count") or 0
        ),
        "expected_dedupe_keys": _as_list(writer_preflight.get("expected_dedupe_keys")),
        "summary_payload_hash": writer_preflight.get("summary_payload_hash"),
        "statement_payloads": payloads,
        "writer_preflight_contract": contract,
        "blocked_reasons": _as_list(writer_preflight.get("blocked_reasons")),
        "safe_boundaries": _as_list(writer_preflight.get("safe_boundaries")),
        "side_effects_clear": _side_effects_clear(writer_preflight),
    }


def _contract_ready(writer):
    contract = writer["writer_preflight_contract"]
    return bool(
        contract.get("target_table") == TARGET_TABLE
        and contract.get("target_column") == TARGET_COLUMN
        and _as_list(contract.get("target_json_path")) == [SUMMARY_METADATA_KEY]
        and contract.get("manual_cli_required") is True
        and contract.get("api_write_allowed") is False
        and contract.get("requires_metadata_json_backup") is True
        and contract.get("requires_postwrite_smoke") is True
    )


def _payload_manifest(writer):
    payloads = []
    for index, payload in enumerate(writer["statement_payloads"], start=1):
        payload = _as_dict(payload)
        manifest = {
            "index": index,
            "statement_type": payload.get("statement_type") or "UPDATE",
            "table": payload.get("table"),
            "target_column": payload.get("target_column"),
            "dedupe_key": payload.get("dedupe_key"),
            "metadata_key": payload.get("metadata_key"),
            "payload_hash": payload.get("payload_hash"),
            "execute_in_api": bool(payload.get("execute_in_api")),
            "payload_manifest_hash": _stable_hash(payload),
        }
        if manifest["dedupe_key"] and manifest["payload_hash"]:
            payloads.append(manifest)
    return {
        "payload_count": len(payloads),
        "manifest_hash": _stable_hash(payloads),
        "dedupe_keys": [item["dedupe_key"] for item in payloads],
        "summary_payload_hash": writer["summary_payload_hash"],
        "payloads": payloads,
        "redaction_policy": [
            "do_not_include_approval_token",
            "do_not_include_raw_html",
            "do_not_include_login_or_member_data",
        ],
    }


def _package_gates(*, writer, operator, manifest, apply_real_write):
    return [
        {
            "key": "summary_persistence_writer_preflight_ready",
            "label": "summary persistence writer preflight 必須已通過",
            "passed": bool(
                writer["mode"]
                == "candidate_queue_review_ai_summary_persistence_writer_preflight_preview"
                and writer["summary_persistence_writer_preflight_ready"]
                and writer["ready_for_summary_persistence_run_package"]
            ),
        },
        {
            "key": "summary_persistence_writer_contract_ready",
            "label": "writer contract 必須標示 CLI-only、metadata backup 與 post-write smoke",
            "passed": _contract_ready(writer),
        },
        {
            "key": "summary_persistence_payload_manifest_ready",
            "label": "run package 必須有 1 到 5 筆 metadata_json statement payload",
            "passed": bool(
                0 < manifest["payload_count"] <= 5
                and writer["invalid_statement_count"] == 0
            ),
        },
        {
            "key": "summary_persistence_payloads_api_execution_disabled",
            "label": "所有 payload 都必須禁止 API/UI 執行",
            "passed": bool(
                manifest["payloads"]
                and all(not item["execute_in_api"] for item in manifest["payloads"])
            ),
        },
        {
            "key": "operator_confirmed_summary_persistence_run_package",
            "label": "操作員確認本步只產生 run package preview，正式寫入走 CLI",
            "passed": bool(
                operator["operator_confirmed_ai_summary_persistence_run_package"]
                and operator["operator_confirmed_payload_manifest_reviewed"]
                and operator["operator_confirmed_cli_command_reviewed"]
                and operator["operator_confirmed_summary_persistence_is_cli_only"]
                and operator["operator_confirmed_no_api_db_write"]
                and operator["operator_confirmed_no_telegram_dispatch"]
                and operator["operator_confirmed_no_scheduler_attach"]
            ),
        },
        {
            "key": "summary_persistence_run_package_artifacts_recorded",
            "label": "transaction、writer preflight、run package 與 metadata backup artifact path 必須齊備",
            "passed": bool(
                operator["ai_summary_persistence_transaction_artifact_path"]
                and operator["ai_summary_persistence_writer_preflight_artifact_path"]
                and operator["ai_summary_persistence_run_package_artifact_path"]
                and operator["metadata_json_backup_artifact_path"]
            ),
        },
        {
            "key": "summary_persistence_run_package_no_approval_token_submitted_to_api",
            "label": "payload 不得包含一次性 approval token key",
            "passed": not operator["approval_token_submitted_to_api"],
        },
        {
            "key": "summary_persistence_run_package_apply_real_write_not_requested_from_api",
            "label": "API/UI run package 不接受 apply_real_write",
            "passed": not apply_real_write,
        },
        {
            "key": "summary_persistence_run_package_has_no_side_effects",
            "label": "run package preview 不得開 DB、寫檔、呼叫 LLM、派 Telegram 或掛 scheduler",
            "passed": writer["side_effects_clear"],
        },
    ]


def build_candidate_queue_review_ai_summary_persistence_run_package(
    *,
    ai_summary_persistence_writer_preflight,
    operator_evidence=None,
    execute_requested=False,
    apply_real_write=False,
):
    """建立 AI summary persistence run package preview；不執行 CLI 或副作用。"""
    writer = _writer_preflight_summary(ai_summary_persistence_writer_preflight)
    operator = _operator_summary(operator_evidence)
    manifest = _payload_manifest(writer)
    gates = _package_gates(
        writer=writer,
        operator=operator,
        manifest=manifest,
        apply_real_write=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_run_package_preview",
        "target_table": TARGET_TABLE,
        "target_column": TARGET_COLUMN,
        "target_operation": "persist_ai_summary_metadata_json",
        "execute_requested": bool(execute_requested),
        "apply_real_write_requested": bool(apply_real_write),
        "package_ready": package_ready,
        "ready_for_summary_persistence_run_readiness": package_ready,
        "ready_for_summary_persistence_cli_run": False,
        "ready_for_real_write": False,
        "ready_for_api_database_write": False,
        "ready_for_telegram_dispatch": False,
        "ready_for_scheduler_attach": False,
        "package_artifact_created": False,
        "summary_persistence_run_package_file_written": False,
        "run_package_file_written": False,
        "api_executes_cli": False,
        "api_executes_llm": False,
        "api_reads_approval_token": False,
        "api_writes_file": False,
        "api_writes_database": False,
        "api_updates_review_state": False,
        "summary_file_written": False,
        "summary_record_written": False,
        "summary_persistence_record_written": False,
        "metadata_patch_written": False,
        "transaction_file_written": False,
        "ai_summary_generated": False,
        "llm_call_executed": False,
        "ollama_call_executed": False,
        "gemini_call_executed": False,
        "telegram_dispatched": 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["payload_count"],
        "payload_manifest": manifest,
        "blocked_reasons": blocked_reasons,
        "package_gates": gates,
        "operator_ai_summary_persistence_run_package": operator,
        "writer_preflight_summary": {
            "mode": writer["mode"],
            "writer_preflight_ready": writer[
                "summary_persistence_writer_preflight_ready"
            ],
            "run_package_ready": writer["ready_for_summary_persistence_run_package"],
            "statement_count": writer["statement_count"],
            "invalid_statement_count": writer["invalid_statement_count"],
        },
        "required_artifacts": [
            {
                "key": "ai_summary_persistence_transaction_json",
                "label": "操作員保存的 AI summary persistence transaction JSON",
                "path_shape": "artifacts/market_intel/ai-summary-persistence-transaction-YYYYMMDD-HHMMSS.json",
                "created_by_api": False,
            },
            {
                "key": "ai_summary_persistence_writer_preflight_json",
                "label": "操作員保存的 writer preflight JSON",
                "path_shape": "artifacts/market_intel/ai-summary-persistence-writer-preflight-YYYYMMDD-HHMMSS.json",
                "created_by_api": False,
            },
            {
                "key": "metadata_json_backup_json",
                "label": "CLI 寫入前的 metadata_json 備份",
                "path_shape": "artifacts/market_intel/ai-summary-metadata-json-backup-YYYYMMDD-HHMMSS.json",
                "created_by_api": False,
            },
            {
                "key": "ai_summary_persistence_writer_output_json",
                "label": "CLI writer 正式執行輸出",
                "path_shape": "artifacts/market_intel/ai-summary-persistence-writer-output-YYYYMMDD-HHMMSS.json",
                "created_by_api": False,
            },
            {
                "key": "ai_summary_persistence_postwrite_smoke_json",
                "label": "post-write smoke 只讀驗證輸出",
                "path_shape": "artifacts/market_intel/ai-summary-persistence-postwrite-smoke-YYYYMMDD-HHMMSS.json",
                "created_by_api": False,
            },
        ],
        "command_bundle": [
            {
                "step": 1,
                "key": "save_run_package",
                "command_shape": (
                    "mkdir -p artifacts/market_intel && write run package JSON to "
                    "artifacts/market_intel/ai-summary-persistence-run-package-YYYYMMDD-HHMMSS.json"
                ),
                "executes_database": False,
                "executed": False,
            },
            {
                "step": 2,
                "key": "backup_metadata_json",
                "command_shape": (
                    "python3 scripts/market_intel_ai_summary_persistence_writer.py "
                    "--transaction-json artifacts/market_intel/ai-summary-persistence-transaction.json "
                    "--backup-metadata-json > artifacts/market_intel/ai-summary-metadata-json-backup.json"
                ),
                "executes_database": False,
                "executed": False,
            },
            {
                "step": 3,
                "key": "writer_preflight",
                "command_shape": (
                    "python3 scripts/market_intel_ai_summary_persistence_writer.py "
                    "--transaction-json artifacts/market_intel/ai-summary-persistence-transaction.json "
                    "--read-only-preflight > artifacts/market_intel/ai-summary-persistence-writer-preflight.json"
                ),
                "executes_database": False,
                "executed": False,
            },
            {
                "step": 4,
                "key": "metadata_json_writer",
                "command_shape": (
                    "MARKET_INTEL_QUEUE_WRITE_APPROVAL=... "
                    "python3 scripts/market_intel_ai_summary_persistence_writer.py "
                    "--transaction-json artifacts/market_intel/ai-summary-persistence-transaction.json "
                    "--backup-verified --execute --apply-real-write "
                    "> artifacts/market_intel/ai-summary-persistence-writer-output.json"
                ),
                "executes_database": True,
                "executed": False,
            },
            {
                "step": 5,
                "key": "postwrite_smoke",
                "command_shape": (
                    "POST /api/market_intel/manual_sample_review/"
                    "candidate_queue_review_ai_summary_persistence_postwrite_smoke?execute=true "
                    "> artifacts/market_intel/ai-summary-persistence-postwrite-smoke.json"
                ),
                "executes_database": False,
                "executed": False,
            },
        ],
        "operator_signoff": [
            "確認 payload manifest 的 dedupe_key 與 summary payload hash",
            "確認 metadata_json backup artifact 已保存且可還原",
            "確認 approval token 只在 operator shell 環境提供",
            "確認 CLI writer output 沒有改動 review_state",
            "確認 post-write smoke 只讀驗證 metadata_json.ai_summary_review",
        ],
        "rollback_plan": [
            {
                "key": "no_preview_side_effect",
                "label": "此 run package preview 沒有副作用，不需要 DB rollback",
            },
            {
                "key": "restore_metadata_json_from_backup",
                "label": "正式 CLI 寫入後若需回退，依 dedupe_key 還原 metadata_json backup",
            },
            {
                "key": "keep_market_flags_disabled",
                "label": "異常時維持 MARKET_INTEL_* flags 關閉，不掛 scheduler",
            },
        ],
        "safe_boundaries": [
            "do_not_create_summary_persistence_run_artifacts_from_api",
            "do_not_execute_summary_persistence_writer_from_run_package_api",
            "do_not_read_approval_token_from_summary_persistence_run_package_api",
            "do_not_open_database_connection_from_summary_persistence_run_package",
            "do_not_write_metadata_json_from_summary_persistence_run_package",
            "do_not_update_review_state_from_summary_persistence_run_package",
            "do_not_commit_summary_persistence_run_package",
            "do_not_dispatch_telegram_from_summary_persistence_run_package",
            "do_not_attach_scheduler_from_summary_persistence_run_package",
            "future_summary_persistence_write_must_use_cli_only_gate",
            "metadata_json_backup_required_before_summary_persistence_write",
            "summary_persistence_postwrite_smoke_required",
            "ai_summary_persistence_run_package_preview_only",
            "no_remove_orphans",
            "no_momo_db_lifecycle_change",
        ],
    }
