"""候選審核 queue review_state writer operator drill preview。

本模組只組裝人工 CLI 更新 review_state 的操作順序與 gate；
不讀 approval token、不開 DB connection、不更新 review_state、不 commit、不掛 scheduler。
"""

from services.market_intel.candidate_queue_review_decision_transaction import (
    ALLOWED_DECISIONS,
    TARGET_TABLE,
)


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"


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 _statement_summary(transaction_preview):
    transaction_preview = _as_dict(transaction_preview)
    statements = [_as_dict(item) for item in _as_list(transaction_preview.get("statements"))]
    invalid = []
    updates = []
    for statement in statements:
        parameter_preview = _as_dict(statement.get("parameter_preview"))
        dedupe_key = parameter_preview.get("dedupe_key") or _as_dict(
            statement.get("lookup")
        ).get("dedupe_key")
        current_state = (
            parameter_preview.get("expected_current_review_state")
            or statement.get("expected_current_review_state")
        )
        next_state = parameter_preview.get("next_review_state") or statement.get(
            "next_review_state"
        )
        updates.append(
            {
                "idempotency_key": statement.get("idempotency_key"),
                "dedupe_key": dedupe_key,
                "expected_current_review_state": current_state,
                "next_review_state": next_state,
                "operation": statement.get("operation"),
                "statement_type": statement.get("statement_type"),
                "parameter_payload_hash": statement.get("parameter_payload_hash"),
            }
        )
        if (
            not dedupe_key
            or current_state != "needs_review"
            or next_state not in ALLOWED_DECISIONS
            or statement.get("operation") != "update"
            or statement.get("statement_type") != "update_review_state"
        ):
            invalid.append(statement.get("idempotency_key") or dedupe_key or "unknown")
    summary = _as_dict(transaction_preview.get("transaction_preview_summary"))
    return {
        "transaction_preview_created": bool(
            transaction_preview.get("transaction_preview_created")
        ),
        "transaction_ready": bool(transaction_preview.get("transaction_ready")),
        "statement_count": int(summary.get("statement_count") or len(statements)),
        "invalid_statement_count": len(invalid),
        "invalid_statement_keys": invalid,
        "allowed_next_states": list(ALLOWED_DECISIONS),
        "review_state_updates": updates,
        "target_table": transaction_preview.get("target_table") or TARGET_TABLE,
    }


def _operator_summary(operator_evidence):
    operator_evidence = _as_dict(operator_evidence)
    return {
        "provided_keys": sorted(operator_evidence.keys()),
        "operator_confirmed_manual_shell_window": bool(
            operator_evidence.get("operator_confirmed_manual_shell_window")
        ),
        "operator_confirmed_transaction_payload_reviewed": bool(
            operator_evidence.get("operator_confirmed_transaction_payload_reviewed")
        ),
        "operator_confirmed_review_state_update_is_not_api": bool(
            operator_evidence.get("operator_confirmed_review_state_update_is_not_api")
        ),
        "operator_confirmed_post_update_inventory_planned": bool(
            operator_evidence.get("operator_confirmed_post_update_inventory_planned")
        ),
        "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")
        ),
        "operator_drill_notes_present": bool(
            str(operator_evidence.get("operator_drill_notes") or "").strip()
        ),
        "approval_token_submitted_to_api": _contains_forbidden_token_key(
            operator_evidence
        ),
    }


def _gates(statement_summary, operator_summary, writer_preflight, writer_status, postwrite_smoke):
    return [
        {
            "key": "transaction_preview_created",
            "label": "已產生 review_state transaction preview",
            "passed": statement_summary["transaction_preview_created"],
        },
        {
            "key": "transaction_ready_for_manual_shell_update",
            "label": "transaction preview 已通過人工 shell 更新前置 gate",
            "passed": statement_summary["transaction_ready"],
        },
        {
            "key": "transaction_has_update_statements",
            "label": "transaction preview 至少有一筆 update_review_state statement",
            "passed": statement_summary["statement_count"] > 0,
        },
        {
            "key": "transaction_statements_valid",
            "label": "statement 只能把 needs_review 更新為 confirmed / rejected / deferred",
            "passed": bool(
                statement_summary["statement_count"]
                and statement_summary["invalid_statement_count"] == 0
            ),
        },
        {
            "key": "writer_preflight_available",
            "label": "writer preflight 已可用，正式操作前需人工跑只讀檢查",
            "passed": bool(writer_preflight),
        },
        {
            "key": "writer_cli_gate_available",
            "label": "review_state writer CLI gate 已可用，真更新只允許 CLI 執行",
            "passed": bool(writer_status),
        },
        {
            "key": "postwrite_smoke_available",
            "label": "post-write smoke 已可用，更新後可只讀驗證 review_state",
            "passed": bool(postwrite_smoke),
        },
        {
            "key": "operator_reviewed_transaction_payload",
            "label": "操作員已人工確認 transaction payload",
            "passed": operator_summary["operator_confirmed_transaction_payload_reviewed"],
        },
        {
            "key": "manual_shell_window_acknowledged",
            "label": "操作員確認只能在人工 shell 寫入窗口執行",
            "passed": operator_summary["operator_confirmed_manual_shell_window"],
        },
        {
            "key": "post_update_inventory_planned",
            "label": "操作員確認正式更新後會執行只讀 inventory / smoke",
            "passed": operator_summary["operator_confirmed_post_update_inventory_planned"],
        },
        {
            "key": "operator_confirmed_no_api_db_write_or_scheduler",
            "label": "操作員確認 API/UI 不寫 DB、不掛 scheduler",
            "passed": bool(
                operator_summary["operator_confirmed_no_api_db_write"]
                and operator_summary["operator_confirmed_no_scheduler_attach"]
                and operator_summary["operator_confirmed_review_state_update_is_not_api"]
            ),
        },
        {
            "key": "operator_drill_notes_present",
            "label": "operator drill 需留下 notes，方便人工稽核",
            "passed": operator_summary["operator_drill_notes_present"],
        },
        {
            "key": "operator_drill_no_token_submitted_to_api",
            "label": "operator_evidence 不得包含一次性 approval token key",
            "passed": not operator_summary["approval_token_submitted_to_api"],
        },
        {
            "key": "api_does_not_execute_write",
            "label": "API/UI 不讀 token、不替操作員執行 DB 更新",
            "passed": True,
        },
        {
            "key": "backup_verified_by_operator",
            "label": "正式更新前操作員必須完成備份並保留備份檔路徑",
            "passed": False,
        },
    ]


def build_candidate_queue_review_decision_writer_operator_drill(
    *,
    transaction_preview,
    writer_preflight,
    writer_status,
    postwrite_smoke,
    operator_evidence=None,
):
    """建立 review_state writer operator drill preview；不執行 DB 或 CLI。"""
    statement_summary = _statement_summary(transaction_preview)
    operator_summary = _operator_summary(operator_evidence)
    gates = _gates(
        statement_summary,
        operator_summary,
        _as_dict(writer_preflight),
        _as_dict(writer_status),
        _as_dict(postwrite_smoke),
    )
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    command_sequence = [
        {
            "step": 1,
            "key": "render_review_state_transaction_json",
            "label": "將已批准的 review_state transaction preview 存成本機 JSON",
            "command_shape": "write local review-state-transaction.json outside API",
            "executes_database": False,
        },
        {
            "step": 2,
            "key": "run_backup",
            "label": "正式更新前先執行專案備份",
            "command_shape": "python3 scripts/tools/backup_system.py",
            "executes_database": False,
        },
        {
            "step": 3,
            "key": "run_read_only_preflight",
            "label": "只讀確認 review queue 欄位、dedupe lookup 與 update contract",
            "command_shape": (
                "python3 scripts/market_intel_review_decision_writer.py "
                "--transaction-json review-state-transaction.json --read-only-preflight"
            ),
            "executes_database": False,
        },
        {
            "step": 4,
            "key": "run_cli_review_state_writer",
            "label": "只在 CLI shell 以一次性 token 執行受控 review_state update",
            "command_shape": (
                "MARKET_INTEL_QUEUE_WRITE_APPROVAL=... "
                "python3 scripts/market_intel_review_decision_writer.py --execute "
                "--apply-real-write --transaction-json review-state-transaction.json"
            ),
            "executes_database": True,
        },
        {
            "step": 5,
            "key": "run_postwrite_smoke",
            "label": "更新後用 dedupe key 只讀確認 review_state 是否符合預期",
            "command_shape": (
                "POST /api/market_intel/manual_sample_review/"
                "candidate_queue_review_decision_writer_postwrite_smoke?execute=true"
            ),
            "executes_database": False,
        },
    ]
    return {
        "mode": "candidate_queue_review_decision_writer_operator_drill_preview",
        "target_table": TARGET_TABLE,
        "target_operation": "update_review_state",
        "operator_drill_ready": bool(
            statement_summary["transaction_preview_created"]
            and statement_summary["statement_count"] > 0
            and statement_summary["invalid_statement_count"] == 0
            and not operator_summary["approval_token_submitted_to_api"]
        ),
        "ready_for_api_review_state_update": False,
        "ready_for_api_database_write": False,
        "ready_for_scheduler_attach": 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,
        "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,
        "blocked_reasons": blocked_reasons,
        "statement_summary": statement_summary,
        "operator_drill_summary": operator_summary,
        "gates": gates,
        "command_sequence": command_sequence,
        "input_summaries": {
            "writer_preflight_mode": _as_dict(writer_preflight).get("mode"),
            "writer_status_mode": _as_dict(writer_status).get("mode"),
            "postwrite_smoke_mode": _as_dict(postwrite_smoke).get("mode"),
            "postwrite_smoke_execute_requested": bool(
                _as_dict(postwrite_smoke).get("execute_requested")
            ),
        },
        "rollback_plan": [
            {
                "key": "no_write_no_db_rollback_required",
                "label": "若 drill preview 或任一 gate 阻擋，沒有 DB rollback 需求",
            },
            {
                "key": "review_state_reversal_requires_manual_audit",
                "label": "若 CLI 真更新後需回退，必須依 dedupe_key 與審核證據人工稽核",
            },
            {
                "key": "disable_market_intel_flags",
                "label": "異常時維持 MARKET_INTEL_* flags 關閉並回退 momo-app 程式碼",
            },
        ],
        "safe_boundaries": [
            "do_not_execute_review_state_writer_from_operator_drill_api",
            "do_not_read_approval_token_from_operator_drill_api",
            "do_not_open_database_connection_from_review_state_operator_drill",
            "do_not_update_review_state_from_review_state_operator_drill",
            "do_not_commit_review_state_operator_drill",
            "do_not_attach_scheduler_from_review_state_operator_drill",
            "no_remove_orphans",
            "no_momo_db_lifecycle_change",
        ],
    }
