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

本模組只組裝正式 CLI 寫入前後的操作順序與 gate；
不讀 approval token、不開 DB connection、不寫 queue、不 commit、不掛 scheduler。
"""


def _statement_summary(transaction_preview):
    summary = transaction_preview.get("transaction_summary", {})
    return {
        "transaction_preview_created": bool(
            transaction_preview.get("transaction_preview_created")
        ),
        "statement_count": int(summary.get("statement_count") or 0),
        "idempotency_key_count": int(summary.get("idempotency_key_count") or 0),
        "conflict_policy": summary.get("conflict_policy"),
    }


def _gates(transaction_preview, writer_preflight, writer_status, postwrite_smoke):
    statement_summary = _statement_summary(transaction_preview)
    return [
        {
            "key": "transaction_preview_created",
            "label": "已產生候選 queue transaction preview",
            "passed": statement_summary["transaction_preview_created"],
        },
        {
            "key": "transaction_has_statements",
            "label": "transaction preview 至少有一筆 idempotent statement",
            "passed": statement_summary["statement_count"] > 0,
        },
        {
            "key": "writer_preflight_available",
            "label": "writer preflight 已可用，正式操作前需人工執行只讀 catalog smoke",
            "passed": bool(writer_preflight),
        },
        {
            "key": "writer_cli_available",
            "label": "CLI writer gate 已可用，真寫入只允許 CLI 執行",
            "passed": bool(writer_status),
        },
        {
            "key": "postwrite_smoke_available",
            "label": "post-write smoke 已可用，寫入後可用 dedupe key 只讀驗證",
            "passed": bool(postwrite_smoke),
        },
        {
            "key": "api_does_not_execute_write",
            "label": "API/UI 不讀 token、不替操作員執行 DB 寫入",
            "passed": True,
        },
        {
            "key": "backup_verified_by_operator",
            "label": "正式寫入前操作員必須完成備份並保留備份檔路徑",
            "passed": False,
        },
        {
            "key": "migration_live_smoke_passed_by_operator",
            "label": "正式寫入前操作員必須完成 schema live smoke",
            "passed": False,
        },
        {
            "key": "one_time_token_supplied_in_shell_only",
            "label": "一次性 approval token 只能在 CLI shell 提供，不可透過 API/UI",
            "passed": False,
        },
    ]


def build_candidate_queue_writer_operator_drill(
    *,
    transaction_preview,
    writer_preflight,
    writer_status,
    postwrite_smoke,
):
    """建立 operator drill preview；不執行任何 DB 或 CLI 動作。"""
    statement_summary = _statement_summary(transaction_preview)
    gates = _gates(
        transaction_preview,
        writer_preflight,
        writer_status,
        postwrite_smoke,
    )
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    command_sequence = [
        {
            "step": 1,
            "key": "render_reviewed_sample_json",
            "label": "將已人工審核通過的 sample result 存成本機 reviewed JSON",
            "command_shape": "write local reviewed-sample.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": "只讀確認 queue table 欄位與 dedupe unique index",
            "command_shape": (
                "python3 scripts/market_intel_candidate_queue_writer.py "
                "--sample-json reviewed-sample.json --read-only-preflight"
            ),
            "executes_database": False,
        },
        {
            "step": 4,
            "key": "run_cli_writer",
            "label": "只在 CLI shell 以一次性 token 執行受控 idempotent insert",
            "command_shape": (
                "MARKET_INTEL_QUEUE_WRITE_APPROVAL=... "
                "python3 scripts/market_intel_candidate_queue_writer.py "
                "--sample-json reviewed-sample.json --read-only-preflight "
                "--backup-verified --migration-live-smoke-passed "
                "--execute --apply-real-write --approval-token \"$MARKET_INTEL_QUEUE_WRITE_APPROVAL\""
            ),
            "executes_database": True,
        },
        {
            "step": 5,
            "key": "run_postwrite_smoke",
            "label": "寫入後用 dedupe key 只讀查詢 queue row 是否存在",
            "command_shape": (
                "POST /api/market_intel/manual_sample_review/"
                "candidate_queue_writer_postwrite_smoke?execute=true"
            ),
            "executes_database": False,
        },
    ]
    return {
        "mode": "candidate_queue_writer_operator_drill_preview",
        "target_table": "market_alert_review_queue",
        "operator_drill_ready": bool(
            statement_summary["transaction_preview_created"]
            and statement_summary["statement_count"] > 0
        ),
        "api_executes_cli": False,
        "api_reads_approval_token": False,
        "api_writes_database": False,
        "database_connection_opened": False,
        "database_session_created": False,
        "explicit_transaction_opened": 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,
        "gates": gates,
        "command_sequence": command_sequence,
        "input_summaries": {
            "writer_preflight_mode": writer_preflight.get("mode"),
            "writer_status_mode": writer_status.get("mode"),
            "postwrite_smoke_mode": postwrite_smoke.get("mode"),
            "postwrite_smoke_execute_requested": bool(
                postwrite_smoke.get("execute_requested")
            ),
        },
        "rollback_plan": [
            {
                "key": "no_write_no_db_rollback_required",
                "label": "若 drill preview 或任一 gate 阻擋，沒有 DB rollback 需求",
            },
            {
                "key": "dedupe_key_cleanup_review",
                "label": "若 CLI 真寫入後需回退，依 affected_dedupe_keys 人工審核清理",
            },
            {
                "key": "disable_market_intel_flags",
                "label": "異常時維持 MARKET_INTEL_* flags 關閉並回退 momo-app 程式碼",
            },
        ],
        "safe_boundaries": [
            "do_not_execute_cli_from_api",
            "do_not_read_approval_token_from_api",
            "do_not_open_database_connection_from_operator_drill_preview",
            "do_not_write_queue_from_operator_drill_preview",
            "do_not_attach_scheduler_from_operator_drill",
            "no_remove_orphans",
            "no_momo_db_lifecycle_change",
        ],
    }
