"""市場情報 MCP fetch candidate queue writer review inventory。

本模組只審核 review handoff 後由 operator 完成的人工候選隊列只讀盤點；
API/UI 不讀 approval token、不執行 CLI、不開 DB、不寫 queue、不做 inventory query、
不更新 review_state、不掛 scheduler。
"""

from services.market_intel.mcp_fetch_candidate_queue_writer_preflight import TARGET_TABLE
from services.market_intel.mcp_fetch_candidate_queue_writer_run_readiness import (
    ARTIFACT_PREFIX,
)
from services.market_intel.mcp_fetch_candidate_queue_writer_post_closeout_inventory_review import (
    FORBIDDEN_SECRET_KEYS,
    SAFE_SECRET_METADATA_KEYS,
    _as_dict,
    _as_list,
    _blocked_side_effects,
    _contains_forbidden_key,
    _safe_int,
    _safe_path,
    _safe_text,
)
from services.market_intel.mcp_fetch_candidate_queue_writer_review_handoff import (
    build_mcp_fetch_candidate_queue_writer_review_handoff_preview,
)
from services.market_intel.mcp_fetch_candidate_queue_writer_review_inventory_gates import (
    build_review_inventory_gates,
)
from services.market_intel.mcp_fetch_candidate_queue_writer_review_inventory_sample import (
    build_sample_writer_review_inventory_package,
)


_REVIEW_INVENTORY_BLOCKED_SIDE_EFFECT_KEYS = (
    "allow_api_candidate_review_update",
    "allow_api_execution",
    "allow_api_file_write",
    "allow_api_inventory_query",
    "allow_api_queue_insert",
    "allow_api_queue_write",
    "allow_cli_execution",
    "allow_database_write",
    "api_candidate_review_update_executed",
    "api_created_review_inventory_file",
    "api_created_review_queue",
    "api_executed_candidate_review",
    "api_inventory_query_executed",
    "api_review_inventory_persisted",
    "api_review_state_update_executed",
    "api_updates_review_state",
    "api_writes_review_queue",
    "candidate_queue_review_created_by_api",
    "candidate_queue_review_inventory_file_written",
    "candidate_queue_review_inventory_persisted",
    "candidate_queue_review_started_by_api",
    "candidate_review_file_written",
    "candidate_review_queue_written",
    "inventory_file_written",
    "inventory_persisted",
    "manual_review_record_written",
    "queue_review_persisted",
    "review_inventory_file_written",
    "review_inventory_persisted",
    "review_queue_file_written",
    "review_queue_row_written",
    "review_state_update_executed",
)


def _blocked_review_inventory_side_effects(payload):
    found = list(_blocked_side_effects(payload))

    def visit(value, path):
        if isinstance(value, dict):
            for key, item in value.items():
                normalized_key = str(key).lower()
                key_path = f"{path}.{key}" if path else key
                if (
                    normalized_key in _REVIEW_INVENTORY_BLOCKED_SIDE_EFFECT_KEYS
                    and bool(item)
                ):
                    found.append(key_path)
                visit(item, key_path)
        elif isinstance(value, list):
            for index, item in enumerate(value):
                visit(item, f"{path}[{index}]")

    visit(payload, "")
    return sorted(set(found))


def _handoff_from_inputs(handoff_package, handoff_result, phase):
    if isinstance(handoff_result, dict) and handoff_result:
        return handoff_result

    handoff_package = _as_dict(handoff_package)
    return build_mcp_fetch_candidate_queue_writer_review_handoff_preview(
        writer_post_closeout_inventory_review_package=(
            handoff_package.get("writer_post_closeout_inventory_review_package")
            or handoff_package.get("candidate_queue_writer_post_closeout_inventory_review")
            or handoff_package.get("writer_post_closeout_inventory_review")
            or handoff_package.get("post_closeout_inventory_review_package")
            or handoff_package.get("post_closeout_inventory_review")
            or {}
        ),
        writer_post_closeout_inventory_review_result=(
            handoff_package.get("writer_post_closeout_inventory_review_result")
            or handoff_package.get(
                "mcp_fetch_candidate_queue_writer_post_closeout_inventory_review"
            )
        ),
        operator_handoff=(
            handoff_package.get("operator_handoff")
            or handoff_package.get("candidate_queue_review_handoff")
            or handoff_package.get("writer_review_handoff")
            or handoff_package.get("handoff_payload")
            or handoff_package.get("handoff")
        ),
        phase=phase,
    )


def _handoff_summary(handoff_result):
    handoff_result = _as_dict(handoff_result)
    handoff = _as_dict(handoff_result.get("operator_handoff_summary"))
    side_effects_clear = bool(
        not handoff_result.get("payload_persisted")
        and not handoff_result.get("review_handoff_persisted")
        and not handoff_result.get("writer_review_handoff_persisted")
        and not handoff_result.get("candidate_queue_review_handoff_persisted")
        and not handoff_result.get("candidate_queue_review_handoff_file_written")
        and not handoff_result.get("handoff_file_written")
        and not handoff_result.get("review_queue_file_written")
        and not handoff_result.get("candidate_review_file_written")
        and not handoff_result.get("package_artifact_created")
        and not handoff_result.get("network_request_allowed")
        and not handoff_result.get("api_executes_cli")
        and not handoff_result.get("api_reads_approval_token")
        and not handoff_result.get("api_opens_database_connection")
        and not handoff_result.get("api_writes_database")
        and not handoff_result.get("api_writes_file")
        and not handoff_result.get("api_uses_external_network")
        and not handoff_result.get("api_inventory_query_executed")
        and not handoff_result.get("api_candidate_review_update_executed")
        and not handoff_result.get("api_updates_review_state")
        and not handoff_result.get("database_write_executed")
        and not handoff_result.get("database_commit_executed")
        and not handoff_result.get("cli_executed")
        and not handoff_result.get("file_written")
        and not handoff_result.get("scheduler_attached")
        and not handoff_result.get("candidate_queue_created")
        and not handoff_result.get("candidate_queue_persisted")
        and not handoff_result.get("candidate_review_state_updated")
    )
    return {
        "mode": handoff_result.get("mode"),
        "accepted": bool(
            handoff_result.get(
                "mcp_fetch_candidate_queue_writer_review_handoff_accepted"
            )
        ),
        "ready_for_candidate_queue_review_inventory": bool(
            handoff_result.get("ready_for_candidate_queue_review_inventory")
        ),
        "handoff_id": _safe_text(handoff.get("handoff_id"), 160),
        "inventory_review_id": _safe_text(handoff.get("inventory_review_id"), 160),
        "closeout_id": _safe_text(handoff.get("closeout_id"), 160),
        "run_package_id": _safe_text(handoff.get("run_package_id"), 160),
        "receipt_id": _safe_text(handoff.get("receipt_id"), 160),
        "target_table": _safe_text(handoff.get("target_table"), 160),
        "payload_row_count": _safe_int(handoff.get("payload_row_count")),
        "expected_payload_row_count": _safe_int(
            handoff.get("expected_payload_row_count")
            or handoff.get("payload_row_count")
        ),
        "expected_review_state": _safe_text(
            handoff.get("expected_review_state"), 80
        ),
        "review_scope": _safe_text(handoff.get("review_scope"), 120),
        "next_queue": _safe_text(handoff.get("next_queue"), 120),
        "review_queue_artifact_path": _safe_text(
            handoff.get("review_queue_artifact_path")
        ),
        "inventory_artifact_path": _safe_text(handoff.get("inventory_artifact_path")),
        "handoff_artifact_path": _safe_text(handoff.get("handoff_artifact_path")),
        "review_queue_artifact_path_safe": bool(
            handoff.get("review_queue_artifact_path_safe")
        ),
        "inventory_artifact_path_safe": bool(
            handoff.get("inventory_artifact_path_safe")
        ),
        "handoff_artifact_path_safe": bool(handoff.get("handoff_artifact_path_safe")),
        "side_effects_clear": side_effects_clear,
        "blocked_reasons": handoff_result.get("blocked_reasons", []),
    }


def _operator_review_inventory_summary(operator_inventory):
    operator_inventory = _as_dict(operator_inventory)
    confirmations = _as_dict(operator_inventory.get("operator_confirmations"))
    query = _as_dict(operator_inventory.get("query_summary"))
    review_state_breakdown = {
        _safe_text(key, 80): _safe_int(value)
        for key, value in _as_dict(
            operator_inventory.get("review_state_breakdown")
        ).items()
        if _safe_text(key, 80)
    }
    sample_dedupe_keys = [
        _safe_text(item, 160)
        for item in _as_list(operator_inventory.get("sample_dedupe_keys"))
        if _safe_text(item, 160)
    ]
    found_row_count = _safe_int(operator_inventory.get("found_row_count"))
    return {
        "provided_keys": sorted(operator_inventory.keys()),
        "review_inventory_id": _safe_text(
            operator_inventory.get("review_inventory_id"), 160
        ),
        "handoff_id": _safe_text(operator_inventory.get("handoff_id"), 160),
        "inventory_review_id": _safe_text(
            operator_inventory.get("inventory_review_id"), 160
        ),
        "closeout_id": _safe_text(operator_inventory.get("closeout_id"), 160),
        "run_package_id": _safe_text(operator_inventory.get("run_package_id"), 160),
        "receipt_id": _safe_text(operator_inventory.get("receipt_id"), 160),
        "target_table": _safe_text(operator_inventory.get("target_table"), 160),
        "payload_row_count": _safe_int(operator_inventory.get("payload_row_count")),
        "expected_payload_row_count": _safe_int(
            operator_inventory.get("expected_payload_row_count")
            or operator_inventory.get("payload_row_count")
        ),
        "found_row_count": found_row_count,
        "missing_row_count": _safe_int(operator_inventory.get("missing_row_count")),
        "unexpected_duplicate_count": _safe_int(
            operator_inventory.get("unexpected_duplicate_count")
        ),
        "dedupe_key_count": _safe_int(operator_inventory.get("dedupe_key_count")),
        "sample_dedupe_keys": sample_dedupe_keys[:20],
        "review_state": _safe_text(operator_inventory.get("review_state"), 80),
        "review_state_breakdown": review_state_breakdown,
        "review_scope": _safe_text(operator_inventory.get("review_scope"), 120),
        "next_queue": _safe_text(operator_inventory.get("next_queue"), 120),
        "review_queue_artifact_path": _safe_text(
            operator_inventory.get("review_queue_artifact_path")
        ),
        "handoff_artifact_path": _safe_text(
            operator_inventory.get("handoff_artifact_path")
        ),
        "inventory_artifact_path": _safe_text(
            operator_inventory.get("inventory_artifact_path")
        ),
        "review_inventory_artifact_path": _safe_text(
            operator_inventory.get("review_inventory_artifact_path")
        ),
        "read_only_query_result_path": _safe_text(
            operator_inventory.get("read_only_query_result_path")
        ),
        "review_queue_artifact_path_safe": _safe_path(
            operator_inventory.get("review_queue_artifact_path"),
            prefixes=(ARTIFACT_PREFIX,),
            suffixes=(".json",),
        ),
        "handoff_artifact_path_safe": _safe_path(
            operator_inventory.get("handoff_artifact_path"),
            prefixes=(ARTIFACT_PREFIX,),
            suffixes=(".json",),
        ),
        "inventory_artifact_path_safe": _safe_path(
            operator_inventory.get("inventory_artifact_path"),
            prefixes=(ARTIFACT_PREFIX,),
            suffixes=(".json",),
        ),
        "review_inventory_artifact_path_safe": _safe_path(
            operator_inventory.get("review_inventory_artifact_path"),
            prefixes=(ARTIFACT_PREFIX,),
            suffixes=(".json",),
        ),
        "read_only_query_result_path_safe": _safe_path(
            operator_inventory.get("read_only_query_result_path"),
            prefixes=(ARTIFACT_PREFIX,),
            suffixes=(".json",),
        ),
        "query_type": _safe_text(query.get("query_type"), 80),
        "read_only_query_executed_by_operator": bool(
            query.get("read_only_query_executed_by_operator")
            or operator_inventory.get("read_only_query_executed_by_operator")
        ),
        "query_target_table": _safe_text(query.get("target_table"), 160),
        "expected_rows_found": bool(query.get("expected_rows_found")),
        "row_count_matches_handoff": bool(query.get("row_count_matches_handoff")),
        "review_state_only_needs_review": bool(
            query.get("review_state_only_needs_review")
        ),
        "no_missing_dedupe_keys": bool(query.get("no_missing_dedupe_keys")),
        "query_no_unexpected_duplicates": bool(
            query.get("no_unexpected_duplicates")
        ),
        "handoff_reviewed": bool(confirmations.get("handoff_reviewed")),
        "review_inventory_read_only": bool(
            confirmations.get("review_inventory_read_only")
        ),
        "candidate_queue_review_only": bool(
            confirmations.get("candidate_queue_review_only")
        ),
        "manual_review_required": bool(confirmations.get("manual_review_required")),
        "no_missing_rows": bool(confirmations.get("no_missing_rows")),
        "no_unexpected_duplicates": bool(
            confirmations.get("no_unexpected_duplicates")
        ),
        "no_approval_token_payload": bool(
            confirmations.get("no_approval_token_payload")
        ),
        "no_api_cli_execution": bool(confirmations.get("no_api_cli_execution")),
        "no_api_database_write": bool(confirmations.get("no_api_database_write")),
        "no_api_inventory_query": bool(confirmations.get("no_api_inventory_query")),
        "no_api_review_state_update": bool(
            confirmations.get("no_api_review_state_update")
        ),
        "no_api_queue_insert": bool(confirmations.get("no_api_queue_insert")),
        "no_api_file_write": bool(confirmations.get("no_api_file_write")),
        "no_scheduler_attach": bool(confirmations.get("no_scheduler_attach")),
        "api_execution_allowed": bool(operator_inventory.get("api_execution_allowed")),
        "real_write_allowed_by_api": bool(
            operator_inventory.get("real_write_allowed_by_api")
        ),
        "api_candidate_review_allowed": bool(
            operator_inventory.get("api_candidate_review_allowed")
        ),
        "api_updates_review_state": bool(
            operator_inventory.get("api_updates_review_state")
        ),
        "secret_or_token_submitted_to_api": _contains_forbidden_key(
            operator_inventory,
            FORBIDDEN_SECRET_KEYS,
            safe_keys=SAFE_SECRET_METADATA_KEYS,
        ),
        "blocked_side_effects": _blocked_review_inventory_side_effects(
            operator_inventory
        ),
    }


def build_mcp_fetch_candidate_queue_writer_review_inventory_preview(
    *,
    writer_review_handoff_package=None,
    writer_review_handoff_result=None,
    operator_review_inventory=None,
    phase=None,
):
    """建立 writer review inventory；不執行查詢、寫檔或寫入。"""
    writer_review_handoff_package = _as_dict(writer_review_handoff_package)
    handoff_result_received = bool(
        isinstance(writer_review_handoff_result, dict)
        and writer_review_handoff_result
    )
    inventory_valid_object = (
        isinstance(operator_review_inventory, dict)
        if operator_review_inventory is not None
        else True
    )
    inventory_payload = _as_dict(operator_review_inventory)
    handoff_received = bool(writer_review_handoff_package or handoff_result_received)
    handoff_result = (
        _handoff_from_inputs(
            writer_review_handoff_package,
            writer_review_handoff_result,
            phase,
        )
        if handoff_received
        else {}
    )
    payload_received = bool(
        handoff_received or inventory_payload or operator_review_inventory is not None
    )
    inventory_received = bool(inventory_payload)
    handoff = _handoff_summary(handoff_result)
    inventory = _operator_review_inventory_summary(inventory_payload)
    gates = build_review_inventory_gates(
        handoff_received=handoff_received,
        inventory_received=inventory_received and inventory_valid_object,
        handoff=handoff,
        inventory=inventory,
    )
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    if not inventory_valid_object:
        blocked_reasons.append("operator_review_inventory_payload_valid_object")
    accepted = bool(payload_received and not blocked_reasons)

    return {
        "mode": (
            "mcp_fetch_candidate_queue_writer_review_inventory"
            if payload_received
            else "mcp_fetch_candidate_queue_writer_review_inventory_preview"
        ),
        "phase": phase,
        "writer_review_inventory_payload_received": payload_received,
        "review_inventory_payload_received": payload_received,
        "writer_review_handoff_received": handoff_received,
        "operator_review_inventory_received": inventory_received,
        "operator_review_inventory_valid_object": inventory_valid_object,
        "writer_review_handoff_accepted": handoff["accepted"],
        "mcp_fetch_candidate_queue_writer_review_inventory_accepted": accepted,
        "candidate_queue_writer_review_inventory_ready": accepted,
        "ready_for_candidate_queue_human_review": accepted,
        "ready_for_candidate_queue_review_decision": accepted,
        "ready_for_api_database_write": False,
        "ready_for_real_write": False,
        "ready_for_scheduler_attach": False,
        "ready_for_candidate_queue_review_api_update": False,
        "ready_for_api_review_state_update": False,
        "network_request_allowed": False,
        "api_executes_cli": False,
        "api_reads_approval_token": False,
        "api_opens_database_connection": False,
        "api_writes_database": False,
        "api_writes_file": False,
        "api_uses_external_network": False,
        "api_inventory_query_executed": False,
        "api_candidate_review_update_executed": False,
        "api_updates_review_state": False,
        "post_closeout_query_executed_by_api": False,
        "review_inventory_query_executed_by_api": False,
        "payload_row_count": inventory["payload_row_count"],
        "gate_count": len(gates),
        "passed_gate_count": sum(1 for gate in gates if gate["passed"]),
        "blocked_reasons": blocked_reasons,
        "gates": gates,
        "writer_review_handoff_summary": handoff,
        "operator_review_inventory_summary": inventory,
        "sample_writer_review_inventory_package": (
            build_sample_writer_review_inventory_package()
        ),
        "next_operator_steps": [
            "Inventory 通過後，只代表可進入人工 candidate queue review decision",
            "API/UI 仍不得自動寫 review_state、補 queue row、讀 token 或掛 scheduler",
            "後續人工決策必須保留 false-positive 保護與 stronger existing match overwrite guard",
        ],
        "payload_persisted": False,
        "review_inventory_persisted": False,
        "writer_review_inventory_persisted": False,
        "candidate_queue_review_inventory_persisted": False,
        "candidate_queue_review_inventory_file_written": False,
        "review_inventory_file_written": False,
        "inventory_file_written": False,
        "review_queue_file_written": False,
        "candidate_review_file_written": False,
        "package_artifact_created": False,
        "database_connection_opened": False,
        "database_session_created": False,
        "database_commit_executed": False,
        "database_write_executed": False,
        "external_network_executed": False,
        "cli_executed": False,
        "file_written": False,
        "writes_executed": False,
        "would_write_database": False,
        "scheduler_attached": False,
        "candidate_queue_created": False,
        "candidate_queue_persisted": False,
        "candidate_review_state_updated": False,
    }
