"""候選審核 queue review_state 交易預覽。

本模組只把已批准的 decision update preview 轉成 CLI-only transaction
preview；不連 DB、不開 transaction、不更新 review_state、不讀 approval token。
"""

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"
ALLOWED_DECISIONS = ("confirmed", "rejected", "deferred")
REVIEW_STATE_UPDATE_SQL_SHAPE = (
    "UPDATE market_alert_review_queue SET review_state = :next_review_state, "
    "reviewed_at = NOW(), updated_at = NOW() WHERE dedupe_key = :dedupe_key "
    "AND review_state = :expected_current_review_state RETURNING id, dedupe_key, "
    "review_state"
)


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 _payload_hash(payload):
    encoded = json.dumps(payload, ensure_ascii=False, sort_keys=True).encode("utf-8")
    return hashlib.sha256(encoded).hexdigest()[:16]


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 _operator_summary(operator_evidence):
    operator_evidence = _as_dict(operator_evidence)
    return {
        "provided_keys": sorted(operator_evidence.keys()),
        "decision_transaction_notes_present": bool(
            str(operator_evidence.get("decision_transaction_notes") or "").strip()
        ),
        "operator_confirmed_transaction_payload_reviewed": bool(
            operator_evidence.get("operator_confirmed_transaction_payload_reviewed")
        ),
        "operator_confirmed_cli_only_transaction": bool(
            operator_evidence.get("operator_confirmed_cli_only_transaction")
        ),
        "operator_confirmed_review_state_update_is_not_api": bool(
            operator_evidence.get("operator_confirmed_review_state_update_is_not_api")
        ),
        "operator_confirmed_no_api_db_write": bool(
            operator_evidence.get("operator_confirmed_no_api_db_write")
        ),
        "operator_confirmed_no_scheduler_attach": bool(
            operator_evidence.get("operator_confirmed_no_scheduler_attach")
        ),
        "approval_token_submitted_to_api": _contains_forbidden_token_key(
            operator_evidence
        ),
    }


def _transaction_statements(decision_approval):
    statements = []
    for index, row in enumerate(
        _as_list(_as_dict(decision_approval).get("decision_update_preview")),
        start=1,
    ):
        row = _as_dict(row)
        parameter_preview = {
            "dedupe_key": row.get("dedupe_key"),
            "expected_current_review_state": row.get(
                "expected_current_review_state"
            ),
            "next_review_state": row.get("approved_next_review_state"),
        }
        statements.append(
            {
                "index": index,
                "operation": "update",
                "statement_type": "update_review_state",
                "table": TARGET_TABLE,
                "lookup": {"dedupe_key": row.get("dedupe_key")},
                "sql_shape": REVIEW_STATE_UPDATE_SQL_SHAPE,
                "sql_template": REVIEW_STATE_UPDATE_SQL_SHAPE,
                "parameter_keys": sorted(parameter_preview),
                "parameter_preview": parameter_preview,
                "parameter_payload_hash": _payload_hash(parameter_preview),
                "expected_current_review_state": row.get(
                    "expected_current_review_state"
                ),
                "next_review_state": row.get("approved_next_review_state"),
                "priority_lane": row.get("priority_lane"),
                "total_score": row.get("total_score"),
                "idempotency_key": (
                    f"{TARGET_TABLE}:review_state:{row.get('dedupe_key')}"
                ),
                "write_status": "blocked_transaction_preview_only",
            }
        )
    return statements


def _transaction_gates(decision_approval, operator_summary, statements):
    return [
        {
            "key": "decision_approval_ready",
            "label": "上一階段 decision approval 必須通過",
            "passed": bool(
                decision_approval.get("mode")
                == "candidate_queue_review_decision_approval_preview"
                and decision_approval.get("approval_ready")
                and decision_approval.get("ready_for_review_state_transaction_preview")
            ),
        },
        {
            "key": "transaction_statements_present",
            "label": "必須有 review_state update statement preview",
            "passed": bool(statements),
        },
        {
            "key": "transaction_transition_allowed",
            "label": "只能從 needs_review 轉為 confirmed / rejected / deferred",
            "passed": bool(
                statements
                and all(
                    item.get("expected_current_review_state") == "needs_review"
                    and item.get("next_review_state") in ALLOWED_DECISIONS
                    for item in statements
                )
            ),
        },
        {
            "key": "operator_reviewed_transaction_payload",
            "label": "操作員確認已人工檢查 transaction payload",
            "passed": bool(
                operator_summary[
                    "operator_confirmed_transaction_payload_reviewed"
                ]
            ),
        },
        {
            "key": "operator_confirmed_cli_only_transaction",
            "label": "操作員確認 review_state 更新只能走 CLI/shell 流程",
            "passed": bool(
                operator_summary["operator_confirmed_cli_only_transaction"]
                and operator_summary[
                    "operator_confirmed_review_state_update_is_not_api"
                ]
            ),
        },
        {
            "key": "operator_confirmed_no_api_db_write_or_scheduler",
            "label": "操作員確認本 API 不寫 DB、不掛 scheduler",
            "passed": bool(
                operator_summary["operator_confirmed_no_api_db_write"]
                and operator_summary["operator_confirmed_no_scheduler_attach"]
            ),
        },
        {
            "key": "decision_transaction_notes_present",
            "label": "transaction preview 需留下 notes，方便後續稽核",
            "passed": bool(
                operator_summary["decision_transaction_notes_present"]
            ),
        },
        {
            "key": "transaction_no_token_submitted_to_api",
            "label": "payload 不得包含一次性 approval token key",
            "passed": not operator_summary["approval_token_submitted_to_api"],
        },
    ]


def build_candidate_queue_review_decision_transaction(
    *,
    decision_approval,
    operator_evidence=None,
):
    """建立 review_state update transaction preview；不執行 DB update。"""
    decision_approval = _as_dict(decision_approval)
    operator_summary = _operator_summary(operator_evidence)
    statements = _transaction_statements(decision_approval)
    gates = _transaction_gates(decision_approval, operator_summary, statements)
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    transaction_ready = bool(not blocked_reasons)

    return {
        "mode": "candidate_queue_review_decision_transaction_preview",
        "target_table": TARGET_TABLE,
        "transaction_preview_created": bool(statements),
        "transaction_ready": transaction_ready,
        "ready_for_manual_shell_update_window": transaction_ready,
        "ready_for_cli_decision_writer": transaction_ready,
        "ready_for_api_review_state_update": False,
        "ready_for_api_database_write": False,
        "ready_for_scheduler_attach": False,
        "review_state_update_allowed_from_api": False,
        "decision_apply_allowed_from_api": False,
        "api_executes_cli": False,
        "api_reads_approval_token": False,
        "api_writes_file": False,
        "api_writes_database": False,
        "api_updates_review_state": False,
        "approval_record_written": False,
        "decision_record_written": False,
        "review_state_update_executed": False,
        "database_connection_opened": False,
        "database_session_created": False,
        "explicit_transaction_opened": False,
        "transaction_opened": False,
        "transaction_committed": False,
        "transaction_rolled_back": 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,
        "statements": statements,
        "operator_transaction_summary": operator_summary,
        "blocked_reasons": blocked_reasons,
        "transaction_gates": gates,
        "transaction_preview_summary": {
            "target_table": TARGET_TABLE,
            "statement_count": len(statements),
            "allowed_next_states": list(ALLOWED_DECISIONS),
            "api_write_allowed": False,
            "manual_cli_required": True,
        },
        "transaction_contract": {
            "lookup_key": "dedupe_key",
            "expected_current_state": "needs_review",
            "allowed_next_states": list(ALLOWED_DECISIONS),
            "sql_shape": REVIEW_STATE_UPDATE_SQL_SHAPE,
            "next_stage": "manual_shell_review_state_update_window",
            "required_runtime_order": [
                "backup_verified",
                "operator_reviewed_transaction_preview",
                "manual_shell_window_opened",
                "one_time_queue_write_token_verified_in_shell_only",
                "review_state_update_transaction",
                "post_update_read_only_inventory",
            ],
            "forbidden_api_actions": [
                "update_review_state",
                "write_decision_record",
                "execute_cli",
                "read_approval_token",
                "attach_scheduler",
            ],
        },
        "rollback_plan": [
            {
                "key": "transaction_not_opened_by_preview",
                "label": "本 preview 不開 transaction；正式更新必須由 shell/CLI transaction 自行 rollback",
            },
            {
                "key": "review_state_reversal_requires_manual_audit",
                "label": "若正式更新後需回退，必須依 dedupe_key 與審核證據人工稽核後再改回 needs_review",
            },
        ],
        "next_operator_steps": [
            "人工確認每個 dedupe_key 的目前狀態仍為 needs_review",
            "確認 next state 僅為 confirmed / rejected / deferred",
            "只在正式 shell/CLI 寫入窗口讀取一次性 approval token",
            "正式更新後執行只讀 inventory / smoke 驗證 review_state",
        ],
        "safe_boundaries": [
            "do_not_update_review_state_from_transaction_api",
            "do_not_write_decision_record_from_transaction_api",
            "do_not_read_approval_token_from_transaction_api",
            "do_not_execute_cli_from_transaction_api",
            "do_not_open_database_connection_from_transaction_api",
            "do_not_commit_transaction_from_transaction_api",
            "do_not_attach_scheduler_from_transaction_api",
            "no_remove_orphans",
            "no_momo_db_lifecycle_change",
        ],
    }
