"""候選審核 queue inventory 只讀檢查。

本模組只整理 handoff 後的人工審核庫存檢查結果；
不更新 review_state、不補寫 queue row、不讀 approval token、不掛 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 _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"),
                "total_score": row.get("total_score"),
                "source_batch_id": row.get("source_batch_id"),
                "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_queue_review_next": bool(
            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")
        ),
        "operator_confirmed_inventory_read_only": bool(
            operator_evidence.get("operator_confirmed_inventory_read_only")
        ),
        "approval_token_submitted_to_api": _contains_forbidden_token_key(
            operator_evidence
        ),
    }


def _side_effects_clear(postwrite_smoke, live_db_inventory):
    payloads = [_as_dict(postwrite_smoke), _as_dict(live_db_inventory)]
    blocked_keys = (
        "api_writes_database",
        "database_write_executed",
        "database_commit_executed",
        "migration_executed",
        "external_network_executed",
        "scheduler_attached",
        "writes_executed",
        "would_write_database",
    )
    return all(not payload.get(key) for payload in payloads for key in blocked_keys)


def _review_gates(
    *,
    handoff,
    postwrite_smoke,
    live_db_inventory,
    operator_summary,
    expected_keys,
    found_keys,
    missing_keys,
    rows,
    alert_table_status,
):
    read_only_executed = bool(
        postwrite_smoke.get("read_only_query_executed")
        or live_db_inventory.get("read_only_query_executed")
    )
    return [
        {
            "key": "handoff_ready",
            "label": "上一階段 handoff 必須通過",
            "passed": bool(handoff.get("handoff_ready")),
        },
        {
            "key": "expected_dedupe_keys_present",
            "label": "必須有 expected dedupe key 才能人工比對",
            "passed": bool(expected_keys),
        },
        {
            "key": "inventory_probe_is_read_only",
            "label": "inventory / smoke 只能做只讀查詢，不得寫 DB 或掛 scheduler",
            "passed": _side_effects_clear(postwrite_smoke, live_db_inventory),
        },
        {
            "key": "operator_confirmed_inventory_read_only",
            "label": "操作員確認本階段只讀，不由 API 寫入或更新 review_state",
            "passed": bool(
                operator_summary["operator_confirmed_inventory_read_only"]
                and operator_summary["operator_confirmed_no_api_db_write"]
                and operator_summary["operator_confirmed_no_scheduler_attach"]
            ),
        },
        {
            "key": "review_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": "正式人工審核前需執行只讀 inventory / post-write smoke",
            "passed": read_only_executed,
        },
        {
            "key": "alert_review_queue_table_exists",
            "label": "market_alert_review_queue 必須存在於只讀 inventory",
            "passed": bool(alert_table_status["exists"]),
        },
        {
            "key": "dedupe_keys_found",
            "label": "所有 expected dedupe key 都必須在 queue 中找到",
            "passed": bool(expected_keys and found_keys and not missing_keys),
        },
        {
            "key": "review_state_needs_review",
            "label": "找到的 queue row 必須維持 needs_review，後續由人工審核處理",
            "passed": bool(rows and all(row.get("review_state") == "needs_review" for row in rows)),
        },
    ]


def build_candidate_queue_review_inventory(
    *,
    review_handoff,
    postwrite_smoke,
    live_db_inventory,
    operator_evidence=None,
    execute_requested=False,
):
    """建立人工 queue review inventory；只整理只讀結果，不執行副作用。"""
    handoff = _as_dict(review_handoff)
    postwrite_smoke = _as_dict(postwrite_smoke)
    live_db_inventory = _as_dict(live_db_inventory)
    operator_summary = _operator_summary(operator_evidence)
    expected_keys = _as_list(handoff.get("expected_dedupe_keys"))
    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)
    table_status = _alert_table_status(live_db_inventory)
    gates = _review_gates(
        handoff=handoff,
        postwrite_smoke=postwrite_smoke,
        live_db_inventory=live_db_inventory,
        operator_summary=operator_summary,
        expected_keys=expected_keys,
        found_keys=found_keys,
        missing_keys=missing_keys,
        rows=rows,
        alert_table_status=table_status,
    )
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    review_inventory_ready = bool(not blocked_reasons)

    return {
        "mode": "candidate_queue_review_inventory_preview",
        "target_table": TARGET_TABLE,
        "execute_requested": bool(execute_requested),
        "review_inventory_ready": review_inventory_ready,
        "ready_for_human_decision_review": review_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,
        "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,
        "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,
        "row_summaries": rows,
        "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")),
            "found_count": postwrite_smoke.get("found_count"),
            "missing_count": postwrite_smoke.get("missing_count"),
        },
        "operator_inventory_summary": operator_summary,
        "blocked_reasons": blocked_reasons,
        "gates": gates,
        "next_operator_steps": [
            "確認 expected / found dedupe key 完全一致",
            "確認 row review_state 仍為 needs_review",
            "人工審核 evidence_json 後，在 API 外部審核流程記錄 confirmed / rejected / deferred",
            "若 row 缺失或狀態不符，停回 writer post-write smoke 與 closeout",
        ],
        "safe_boundaries": [
            "do_not_update_review_state_from_api",
            "do_not_insert_missing_queue_row_from_api",
            "do_not_read_approval_token_from_api",
            "do_not_execute_cli_from_review_inventory",
            "do_not_attach_scheduler_from_review_inventory",
            "read_only_inventory_only_when_operator_requested",
            "no_remove_orphans",
            "no_momo_db_lifecycle_change",
        ],
    }
