"""候選審核 queue review_state closeout 後只讀庫存檢查。

本模組只整理 review_state writer closeout 後的 inventory / smoke 結果；
不讀 approval token、不執行 CLI、不更新 review_state、不寫 DB、不 commit、
不掛 scheduler。
"""


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"


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 _expected_updates_from_transaction(transaction_preview):
    updates = []
    for statement in _as_list(_as_dict(transaction_preview).get("statements")):
        statement = _as_dict(statement)
        lookup = _as_dict(statement.get("lookup"))
        parameter_preview = _as_dict(statement.get("parameter_preview"))
        dedupe_key = lookup.get("dedupe_key") or parameter_preview.get("dedupe_key")
        next_state = (
            parameter_preview.get("next_review_state")
            or statement.get("next_review_state")
        )
        current_state = (
            parameter_preview.get("expected_current_review_state")
            or statement.get("expected_current_review_state")
        )
        if dedupe_key:
            updates.append(
                {
                    "dedupe_key": str(dedupe_key),
                    "expected_current_review_state": current_state,
                    "expected_review_state": next_state,
                    "idempotency_key": statement.get("idempotency_key"),
                    "parameter_payload_hash": statement.get(
                        "parameter_payload_hash"
                    ),
                }
            )
    return updates


def _row_summaries(postwrite_smoke):
    rows = []
    for row in _as_list(_as_dict(postwrite_smoke).get("row_summaries")):
        row = _as_dict(row)
        rows.append(
            {
                "dedupe_key": row.get("dedupe_key"),
                "review_state": row.get("review_state"),
                "priority_lane": row.get("priority_lane"),
                "threshold_level": row.get("threshold_level"),
                "total_score": row.get("total_score"),
                "evidence_bundle_id": row.get("evidence_bundle_id"),
                "source_batch_id": row.get("source_batch_id"),
                "reviewed_at": row.get("reviewed_at"),
                "created_at": row.get("created_at"),
                "updated_at": row.get("updated_at"),
            }
        )
    return rows


def _alert_table_status(live_db_inventory):
    for item in _as_list(_as_dict(live_db_inventory).get("table_statuses")):
        item = _as_dict(item)
        if item.get("table") == TARGET_TABLE:
            return {
                "exists": bool(item.get("exists")),
                "row_count": item.get("row_count"),
                "status": item.get("status"),
            }
    return {"exists": False, "row_count": None, "status": "not_reported"}


def _operator_summary(operator_evidence):
    operator_evidence = _as_dict(operator_evidence)
    return {
        "provided_keys": sorted(operator_evidence.keys()),
        "operator_confirmed_post_closeout_inventory_read_only": bool(
            operator_evidence.get("operator_confirmed_post_closeout_inventory_read_only")
            or operator_evidence.get("operator_confirmed_inventory_read_only")
        ),
        "operator_confirmed_review_state_closeout_next": bool(
            operator_evidence.get("operator_confirmed_review_state_closeout_next")
            or operator_evidence.get("operator_confirmed_queue_review_next")
        ),
        "operator_confirmed_no_scheduler_attach": bool(
            operator_evidence.get("operator_confirmed_no_scheduler_attach")
        ),
        "operator_confirmed_no_api_db_write": bool(
            operator_evidence.get("operator_confirmed_no_api_db_write")
        ),
        "approval_token_submitted_to_api": _contains_forbidden_token_key(
            operator_evidence
        ),
    }


def _side_effects_clear(*payloads):
    blocked_keys = (
        "api_executes_cli",
        "api_writes_database",
        "api_updates_review_state",
        "database_write_executed",
        "database_commit_executed",
        "migration_executed",
        "external_network_executed",
        "scheduler_attached",
        "review_state_update_executed",
        "writes_executed",
        "would_write_database",
    )
    return all(
        not _as_dict(payload).get(key)
        for payload in payloads
        for key in blocked_keys
    )


def _closeout_summary(run_closeout):
    run_closeout = _as_dict(run_closeout)
    promotion_gate = _as_dict(run_closeout.get("promotion_gate"))
    receipt_summary = _as_dict(run_closeout.get("receipt_summary"))
    return {
        "provided": bool(run_closeout),
        "mode": run_closeout.get("mode"),
        "closeout_passed": bool(run_closeout.get("closeout_passed")),
        "ready_for_next_manual_phase": bool(
            run_closeout.get("ready_for_next_manual_phase")
        ),
        "ready_for_review_inventory": bool(
            run_closeout.get("ready_for_review_inventory")
        ),
        "promotion_allowed": bool(promotion_gate.get("allowed")),
        "next_manual_phase": promotion_gate.get("next_manual_phase"),
        "receipt_passed": bool(receipt_summary.get("receipt_passed")),
        "expected_review_state_update_count": int(
            receipt_summary.get("expected_review_state_update_count") or 0
        ),
        "safe_boundaries_complete": bool(
            receipt_summary.get("safe_boundaries_complete")
        ),
        "ready_for_api_review_state_update": bool(
            run_closeout.get("ready_for_api_review_state_update")
        ),
        "ready_for_api_database_write": bool(
            run_closeout.get("ready_for_api_database_write")
        ),
        "ready_for_scheduler_attach": bool(run_closeout.get("ready_for_scheduler_attach")),
        "api_executes_cli": bool(run_closeout.get("api_executes_cli")),
        "api_reads_approval_token": bool(run_closeout.get("api_reads_approval_token")),
        "api_writes_file": bool(run_closeout.get("api_writes_file")),
        "api_writes_database": bool(run_closeout.get("api_writes_database")),
        "api_updates_review_state": bool(run_closeout.get("api_updates_review_state")),
        "database_connection_opened": bool(
            run_closeout.get("database_connection_opened")
        ),
        "database_write_executed": bool(run_closeout.get("database_write_executed")),
        "database_commit_executed": bool(run_closeout.get("database_commit_executed")),
        "review_state_update_executed": bool(
            run_closeout.get("review_state_update_executed")
        ),
        "scheduler_attached": bool(run_closeout.get("scheduler_attached")),
    }


def _state_mismatches(rows, expected_updates):
    expected_by_key = {
        item["dedupe_key"]: item.get("expected_review_state")
        for item in expected_updates
        if item.get("dedupe_key")
    }
    mismatches = []
    for row in rows:
        dedupe_key = row.get("dedupe_key")
        expected_state = expected_by_key.get(dedupe_key)
        if expected_state and row.get("review_state") != expected_state:
            mismatches.append(
                {
                    "dedupe_key": dedupe_key,
                    "expected_review_state": expected_state,
                    "actual_review_state": row.get("review_state"),
                }
            )
    return mismatches


def _inventory_gates(
    *,
    closeout_summary,
    postwrite_smoke,
    live_db_inventory,
    operator_summary,
    expected_updates,
    expected_keys,
    found_keys,
    missing_keys,
    rows,
    state_mismatches,
    table_status,
):
    read_only_executed = bool(
        postwrite_smoke.get("read_only_query_executed")
        or live_db_inventory.get("read_only_query_executed")
    )
    return [
        {
            "key": "closeout_preview_provided",
            "label": "必須提供 review_state writer closeout preview",
            "passed": bool(
                closeout_summary["provided"]
                and closeout_summary["mode"]
                == "candidate_queue_review_decision_writer_run_closeout_preview"
            ),
        },
        {
            "key": "closeout_passed",
            "label": "closeout 必須已通過才可做 post-closeout inventory",
            "passed": closeout_summary["closeout_passed"],
        },
        {
            "key": "closeout_promotes_read_only_inventory",
            "label": "closeout 只能放行到後續人工/只讀 inventory",
            "passed": bool(
                closeout_summary["promotion_allowed"]
                and closeout_summary["ready_for_review_inventory"]
                and closeout_summary["next_manual_phase"]
                == "review_state_post_closeout_read_only_inventory"
            ),
        },
        {
            "key": "expected_review_state_updates_present",
            "label": "必須有 expected review_state update 才能比對",
            "passed": bool(expected_updates and expected_keys),
        },
        {
            "key": "inventory_probe_is_read_only",
            "label": "inventory / smoke 只能只讀，不得寫 DB、更新狀態或掛 scheduler",
            "passed": _side_effects_clear(
                closeout_summary,
                postwrite_smoke,
                live_db_inventory,
            ),
        },
        {
            "key": "operator_confirmed_post_closeout_inventory_read_only",
            "label": "操作員確認 closeout 後 inventory 仍只讀",
            "passed": bool(
                operator_summary["operator_confirmed_post_closeout_inventory_read_only"]
                and operator_summary["operator_confirmed_no_api_db_write"]
                and operator_summary["operator_confirmed_no_scheduler_attach"]
            ),
        },
        {
            "key": "post_closeout_inventory_no_approval_token_submitted_to_api",
            "label": "payload 不得包含一次性 approval token key",
            "passed": not operator_summary["approval_token_submitted_to_api"],
        },
        {
            "key": "read_only_inventory_executed",
            "label": "需執行只讀 post-write smoke 或 live inventory",
            "passed": read_only_executed,
        },
        {
            "key": "alert_review_queue_table_exists",
            "label": "market_alert_review_queue 必須存在於只讀 inventory",
            "passed": bool(table_status["exists"]),
        },
        {
            "key": "dedupe_keys_found_after_review_state_write",
            "label": "所有 expected dedupe key 都必須在 queue 中找到",
            "passed": bool(expected_keys and found_keys and not missing_keys),
        },
        {
            "key": "review_state_matches_expected",
            "label": "找到的 row review_state 必須符合人工 decision transaction",
            "passed": bool(rows and not state_mismatches),
        },
    ]


def build_candidate_queue_review_decision_post_closeout_inventory(
    *,
    transaction_preview,
    run_closeout,
    postwrite_smoke,
    live_db_inventory,
    operator_evidence=None,
    execute_requested=False,
):
    """建立 review_state closeout 後 inventory preview；不執行任何副作用。"""
    postwrite_smoke = _as_dict(postwrite_smoke)
    live_db_inventory = _as_dict(live_db_inventory)
    expected_updates = _expected_updates_from_transaction(transaction_preview)
    expected_keys = sorted({item["dedupe_key"] for item in expected_updates})
    found_keys = _as_list(postwrite_smoke.get("found_dedupe_keys"))
    missing_keys = _as_list(postwrite_smoke.get("missing_dedupe_keys"))
    rows = _row_summaries(postwrite_smoke)
    state_mismatches = _state_mismatches(rows, expected_updates)
    table_status = _alert_table_status(live_db_inventory)
    closeout = _closeout_summary(run_closeout)
    operator_summary = _operator_summary(operator_evidence)
    gates = _inventory_gates(
        closeout_summary=closeout,
        postwrite_smoke=postwrite_smoke,
        live_db_inventory=live_db_inventory,
        operator_summary=operator_summary,
        expected_updates=expected_updates,
        expected_keys=expected_keys,
        found_keys=found_keys,
        missing_keys=missing_keys,
        rows=rows,
        state_mismatches=state_mismatches,
        table_status=table_status,
    )
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    inventory_ready = bool(not blocked_reasons)

    return {
        "mode": "candidate_queue_review_decision_post_closeout_inventory_preview",
        "target_table": TARGET_TABLE,
        "target_operation": "verify_review_state_after_closeout",
        "execute_requested": bool(execute_requested),
        "post_closeout_inventory_ready": inventory_ready,
        "ready_for_next_manual_phase": inventory_ready,
        "ready_for_review_completion_archive": inventory_ready,
        "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,
        "read_only_query_executed": bool(
            postwrite_smoke.get("read_only_query_executed")
            or live_db_inventory.get("read_only_query_executed")
        ),
        "database_connection_opened": bool(
            postwrite_smoke.get("database_connection_opened")
            or live_db_inventory.get("database_connection_opened")
        ),
        "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": expected_keys,
        "found_dedupe_keys": found_keys,
        "missing_dedupe_keys": missing_keys,
        "expected_review_state_updates": expected_updates,
        "row_summaries": rows,
        "state_mismatches": state_mismatches,
        "alert_review_queue_table": table_status,
        "live_inventory_summary": {
            "mode": live_db_inventory.get("mode"),
            "summary_ready": bool(live_db_inventory.get("summary_ready")),
            "total_rows": live_db_inventory.get("total_rows"),
            "alert_review_state_breakdown": _as_list(
                live_db_inventory.get("alert_review_state_breakdown")
            ),
        },
        "postwrite_smoke_summary": {
            "mode": postwrite_smoke.get("mode"),
            "postwrite_smoke_passed": bool(
                postwrite_smoke.get("postwrite_smoke_passed")
            ),
            "review_state_update_verified": bool(
                postwrite_smoke.get("review_state_update_verified")
            ),
            "found_count": postwrite_smoke.get("found_count"),
            "missing_count": postwrite_smoke.get("missing_count"),
            "state_mismatch_count": postwrite_smoke.get("state_mismatch_count"),
        },
        "closeout_summary": closeout,
        "operator_inventory_summary": operator_summary,
        "blocked_reasons": blocked_reasons,
        "gates": gates,
        "next_operator_steps": [
            "確認 expected / found dedupe key 完全一致",
            "確認每個 row review_state 符合 confirmed / rejected / deferred 決策",
            "保存 post-closeout inventory artifact 與 live inventory 摘要",
            "若 row 缺失或狀態不符，停回 review_state writer receipt / closeout",
        ],
        "safe_boundaries": [
            "do_not_update_review_state_from_post_closeout_inventory",
            "do_not_insert_missing_queue_row_from_post_closeout_inventory",
            "do_not_read_approval_token_from_post_closeout_inventory",
            "do_not_execute_cli_from_post_closeout_inventory",
            "do_not_attach_scheduler_from_post_closeout_inventory",
            "post_closeout_inventory_read_only",
            "no_remove_orphans",
            "no_momo_db_lifecycle_change",
        ],
    }
