"""候選審核 queue AI summary persistence preflight 預覽。

本模組只檢查人工 AI 摘要 receipt 是否可進入後續 metadata persistence
transaction preview；不呼叫 LLM、不派送 Telegram、不讀 approval token、
不執行 CLI、不寫檔、不寫 DB、不更新 review_state、不 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",
}
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 _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 _safe_text(value, limit=1000):
    if value is None:
        return None
    text = str(value).strip()
    return text[:limit] if text else None


def _safe_json_list(value, limit=12):
    items = []
    for item in _as_list(value)[:limit]:
        if isinstance(item, dict):
            items.append(item)
        elif item is not None:
            items.append({"text": _safe_text(item)})
    return items


def _side_effects_clear(*payloads):
    blocked_keys = (
        "api_executes_cli",
        "api_executes_llm",
        "api_reads_approval_token",
        "api_writes_file",
        "api_writes_database",
        "api_updates_review_state",
        "run_package_file_written",
        "summary_file_written",
        "summary_record_written",
        "summary_manifest_written",
        "summary_receipt_file_written",
        "summary_persistence_preflight_file_written",
        "summary_persistence_record_written",
        "metadata_patch_written",
        "database_write_executed",
        "database_commit_executed",
        "review_state_update_executed",
        "llm_call_executed",
        "ollama_call_executed",
        "gemini_call_executed",
        "telegram_dispatched",
        "ai_summary_generated",
        "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 _summary_output(operator_evidence):
    operator_evidence = _as_dict(operator_evidence)
    return _as_dict(
        operator_evidence.get("ai_summary_output")
        or operator_evidence.get("summary_output")
    )


def _operator_summary(operator_evidence):
    operator_evidence = _as_dict(operator_evidence)
    return {
        "provided_keys": sorted(operator_evidence.keys()),
        "operator_confirmed_ai_summary_persistence_preflight": bool(
            operator_evidence.get("operator_confirmed_ai_summary_persistence_preflight")
            or operator_evidence.get("operator_confirmed_summary_persistence_preflight")
        ),
        "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_output_artifact_path": _safe_text(
            operator_evidence.get("ai_summary_output_artifact_path")
            or operator_evidence.get("summary_output_artifact_path")
        ),
        "ai_summary_receipt_artifact_path": _safe_text(
            operator_evidence.get("ai_summary_receipt_artifact_path")
            or operator_evidence.get("summary_receipt_artifact_path")
        ),
        "ai_summary_persistence_preflight_artifact_path": _safe_text(
            operator_evidence.get("ai_summary_persistence_preflight_artifact_path")
            or operator_evidence.get("summary_persistence_preflight_artifact_path")
        ),
        "approval_token_submitted_to_api": _contains_forbidden_token_key(
            operator_evidence
        ),
    }


def _receipt_payload(ai_summary_output_receipt):
    receipt = _as_dict(ai_summary_output_receipt)
    validation = _as_dict(receipt.get("summary_output_validation"))
    return {
        "provided": bool(receipt),
        "mode": receipt.get("mode"),
        "ai_summary_output_receipt_ready": bool(
            receipt.get("ai_summary_output_receipt_ready")
        ),
        "ready_for_summary_persistence_review": bool(
            receipt.get("ready_for_summary_persistence_review")
        ),
        "manual_ai_summary_output_provided": bool(
            receipt.get("manual_ai_summary_output_provided")
        ),
        "summary_output_schema_valid": bool(receipt.get("summary_output_schema_valid")),
        "summary_output_evidence_refs_grounded": bool(
            receipt.get("summary_output_evidence_refs_grounded")
        ),
        "summary_output_model_route_accepted": bool(
            receipt.get("summary_output_model_route_accepted")
        ),
        "expected_dedupe_keys": [
            str(key) for key in _as_list(receipt.get("expected_dedupe_keys"))
        ],
        "summary_section_keys": [
            str(key) for key in _as_list(receipt.get("summary_section_keys"))
        ],
        "evidence_refs": [
            str(ref) for ref in _as_list(validation.get("evidence_refs"))
        ],
        "model_route_policy": _as_dict(receipt.get("model_route_policy")),
        "blocked_reasons": _as_list(receipt.get("blocked_reasons")),
        "safe_boundaries": _as_list(receipt.get("safe_boundaries")),
        "llm_call_executed": bool(receipt.get("llm_call_executed")),
        "ollama_call_executed": bool(receipt.get("ollama_call_executed")),
        "gemini_call_executed": bool(receipt.get("gemini_call_executed")),
        "telegram_dispatched": bool(receipt.get("telegram_dispatched")),
        "database_write_executed": bool(receipt.get("database_write_executed")),
        "database_commit_executed": bool(receipt.get("database_commit_executed")),
        "review_state_update_executed": bool(receipt.get("review_state_update_executed")),
        "scheduler_attached": bool(receipt.get("scheduler_attached")),
    }


def _model_route_summary(output):
    model_route = _as_dict(output.get("model_route"))
    return {
        "provider": _safe_text(model_route.get("provider"), 80),
        "host": _safe_text(model_route.get("host"), 120),
        "model": _safe_text(model_route.get("model"), 120),
        "fallback_reason": _safe_text(model_route.get("fallback_reason"), 300),
    }


def _summary_payload(*, output, receipt, operator):
    payload = {
        "schema_version": "market_intel_ai_summary_persistence_v1",
        "target_metadata_key": SUMMARY_METADATA_KEY,
        "headline": _safe_text(output.get("headline"), 240),
        "executive_summary": _safe_text(output.get("executive_summary"), 2000),
        "key_findings": _safe_json_list(output.get("key_findings")),
        "risk_flags": _safe_json_list(output.get("risk_flags")),
        "recommended_actions": _safe_json_list(output.get("recommended_actions")),
        "evidence_refs": [str(ref) for ref in _as_list(output.get("evidence_refs"))],
        "model_route": _model_route_summary(output),
        "source": {
            "generated_by": "manual_ollama_summary",
            "receipt_mode": receipt["mode"],
            "expected_dedupe_keys": receipt["expected_dedupe_keys"],
            "summary_section_keys": receipt["summary_section_keys"],
            "artifact_paths": {
                "ai_summary_output": operator["ai_summary_output_artifact_path"],
                "ai_summary_receipt": operator["ai_summary_receipt_artifact_path"],
                "ai_summary_persistence_preflight": operator[
                    "ai_summary_persistence_preflight_artifact_path"
                ],
            },
        },
    }
    encoded = json.dumps(payload, ensure_ascii=False, sort_keys=True).encode("utf-8")
    return payload, hashlib.sha256(encoded).hexdigest()


def _persistence_contract(*, receipt, payload_hash):
    return {
        "schema_version": "market_intel_ai_summary_persistence_contract_v1",
        "target_table": TARGET_TABLE,
        "target_column": TARGET_COLUMN,
        "target_json_path": [SUMMARY_METADATA_KEY],
        "match_column": "dedupe_key",
        "match_values": receipt["expected_dedupe_keys"],
        "planned_update_count": len(receipt["expected_dedupe_keys"]),
        "payload_hash": payload_hash,
        "conflict_policy": "merge_metadata_json_without_overwriting_operator_decision",
        "write_path": "future_cli_only_transaction_preview",
        "api_write_allowed": False,
    }


def _record_preview(*, payload, payload_hash, receipt):
    return {
        "payload_hash": payload_hash,
        "schema_version": payload["schema_version"],
        "headline": payload["headline"],
        "executive_summary_present": bool(payload["executive_summary"]),
        "key_finding_count": len(payload["key_findings"]),
        "risk_flag_count": len(payload["risk_flags"]),
        "recommended_action_count": len(payload["recommended_actions"]),
        "evidence_refs": payload["evidence_refs"],
        "model_route": payload["model_route"],
        "expected_dedupe_keys": receipt["expected_dedupe_keys"],
    }


def _preflight_gates(*, receipt, output, operator, payload_hash):
    return [
        {
            "key": "ai_summary_output_receipt_ready",
            "label": "AI summary output receipt 必須已通過",
            "passed": bool(
                receipt["provided"]
                and receipt["mode"]
                == "candidate_queue_review_ai_summary_output_receipt_preview"
                and receipt["ai_summary_output_receipt_ready"]
                and receipt["ready_for_summary_persistence_review"]
            ),
        },
        {
            "key": "manual_ai_summary_output_still_provided",
            "label": "preflight payload 必須仍提供人工摘要 output",
            "passed": bool(output and receipt["manual_ai_summary_output_provided"]),
        },
        {
            "key": "summary_output_receipt_validation_passed",
            "label": "receipt schema、evidence_refs 與 model_route 必須通過",
            "passed": bool(
                receipt["summary_output_schema_valid"]
                and receipt["summary_output_evidence_refs_grounded"]
                and receipt["summary_output_model_route_accepted"]
            ),
        },
        {
            "key": "summary_persistence_target_contract_ready",
            "label": "必須有 dedupe key 可對應 market_alert_review_queue.metadata_json",
            "passed": bool(receipt["expected_dedupe_keys"]),
        },
        {
            "key": "summary_payload_hash_ready",
            "label": "摘要 payload 必須可產生穩定 hash",
            "passed": bool(payload_hash and len(payload_hash) == 64),
        },
        {
            "key": "operator_confirmed_summary_persistence_preflight",
            "label": "操作員確認本步只做 persistence preflight，後續寫入走 CLI-only gate",
            "passed": bool(
                operator["operator_confirmed_ai_summary_persistence_preflight"]
                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_preflight_artifacts_recorded",
            "label": "output、receipt 與 preflight artifact path 必須由操作員提供",
            "passed": bool(
                operator["ai_summary_output_artifact_path"]
                and operator["ai_summary_receipt_artifact_path"]
                and operator["ai_summary_persistence_preflight_artifact_path"]
            ),
        },
        {
            "key": "summary_persistence_preflight_no_approval_token_submitted_to_api",
            "label": "payload 不得包含一次性 approval token key",
            "passed": not operator["approval_token_submitted_to_api"],
        },
        {
            "key": "summary_persistence_preflight_has_no_side_effects",
            "label": "persistence preflight 不得呼叫 LLM、派送 Telegram、寫檔、寫 DB 或掛 scheduler",
            "passed": _side_effects_clear(receipt),
        },
    ]


def build_candidate_queue_review_ai_summary_persistence_preflight(
    *,
    ai_summary_output_receipt,
    operator_evidence=None,
    execute_requested=False,
):
    """建立 AI summary persistence preflight 預覽；不產生任何寫入副作用。"""
    receipt = _receipt_payload(ai_summary_output_receipt)
    operator = _operator_summary(operator_evidence)
    output = _summary_output(operator_evidence)
    payload, payload_hash = _summary_payload(
        output=output,
        receipt=receipt,
        operator=operator,
    )
    contract = _persistence_contract(receipt=receipt, payload_hash=payload_hash)
    gates = _preflight_gates(
        receipt=receipt,
        output=output,
        operator=operator,
        payload_hash=payload_hash,
    )
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    preflight_ready = bool(not blocked_reasons)

    return {
        "mode": "candidate_queue_review_ai_summary_persistence_preflight_preview",
        "target_table": TARGET_TABLE,
        "target_operation": "preflight_ai_summary_metadata_persistence",
        "execute_requested": bool(execute_requested),
        "summary_persistence_preflight_ready": preflight_ready,
        "ready_for_summary_transaction_preview": preflight_ready,
        "ready_for_next_manual_phase": preflight_ready,
        "ready_for_summary_persistence_cli_run": False,
        "ready_for_ai_summary_generation": False,
        "ready_for_llm_call": False,
        "ready_for_telegram_dispatch": False,
        "ready_for_api_review_state_update": False,
        "ready_for_api_database_write": False,
        "ready_for_scheduler_attach": 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_persistence_preflight_file_written": False,
        "summary_file_written": False,
        "summary_record_written": False,
        "summary_manifest_written": False,
        "summary_receipt_file_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,
        "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,
        "expected_dedupe_keys": receipt["expected_dedupe_keys"],
        "summary_payload_hash": payload_hash,
        "summary_persistence_contract": contract,
        "summary_record_preview": _record_preview(
            payload=payload,
            payload_hash=payload_hash,
            receipt=receipt,
        ),
        "metadata_patch_preview": {
            "target_table": TARGET_TABLE,
            "target_column": TARGET_COLUMN,
            "target_json_path": [SUMMARY_METADATA_KEY],
            "match_values": receipt["expected_dedupe_keys"],
            "payload_hash": payload_hash,
            "statement_preview_created": False,
            "metadata_patch_preview_created": True,
            "api_write_allowed": False,
        },
        "operator_ai_summary_persistence_preflight": operator,
        "receipt_summary": {
            "mode": receipt["mode"],
            "ai_summary_output_receipt_ready": receipt[
                "ai_summary_output_receipt_ready"
            ],
            "ready_for_summary_persistence_review": receipt[
                "ready_for_summary_persistence_review"
            ],
            "summary_output_schema_valid": receipt["summary_output_schema_valid"],
            "summary_output_evidence_refs_grounded": receipt[
                "summary_output_evidence_refs_grounded"
            ],
            "summary_output_model_route_accepted": receipt[
                "summary_output_model_route_accepted"
            ],
            "evidence_refs": receipt["evidence_refs"],
        },
        "blocked_reasons": blocked_reasons,
        "gates": gates,
        "next_operator_steps": [
            "確認 summary payload hash 與人工摘要 output artifact 一致",
            "後續若要落地 metadata_json，必須另開 transaction preview 與 CLI-only writer gate",
            "Telegram dispatch 必須另開 dispatch preflight，不得由 persistence preflight 派送",
            "本 preflight 不寫檔、不寫 DB、不呼叫模型、不發 Telegram",
        ],
        "safe_boundaries": [
            "do_not_call_llm_from_ai_summary_persistence_preflight",
            "do_not_dispatch_telegram_from_ai_summary_persistence_preflight",
            "do_not_write_summary_persistence_preflight_file_from_api",
            "do_not_write_summary_record_from_api",
            "do_not_write_metadata_json_from_ai_summary_persistence_preflight",
            "do_not_update_review_state_from_ai_summary_persistence_preflight",
            "do_not_read_approval_token_from_ai_summary_persistence_preflight",
            "do_not_execute_cli_from_ai_summary_persistence_preflight",
            "do_not_attach_scheduler_from_ai_summary_persistence_preflight",
            "future_summary_persistence_must_use_cli_only_gate",
            "telegram_dispatch_requires_separate_gate",
            "ai_summary_persistence_preflight_preview_only",
            "no_remove_orphans",
            "no_momo_db_lifecycle_change",
        ],
    }
