"""市場情報 MCP fetch candidate queue writer run readiness preview。

本模組只審核 run package review 後的 operator readiness 證據；API/UI
不建立 artifact、不寫檔、不執行 CLI、不讀 approval token、不開 DB、不寫
queue、不掛 scheduler。
"""

from services.market_intel.mcp_fetch_candidate_queue_writer_preflight import TARGET_TABLE
from services.market_intel.mcp_fetch_candidate_queue_writer_run_package_review import (
    build_mcp_fetch_candidate_queue_writer_run_package_review_preview,
)


MAX_READY_PAYLOAD_ROWS = 80
ARTIFACT_PREFIX = "artifacts/market_intel/"
BACKUP_PREFIX = "scripts/tools/backups/"

FORBIDDEN_SECRET_KEYS = (
    "approval_token",
    "approval-token",
    "api_key",
    "authorization",
    "bearer",
    "client_secret",
    "cookie",
    "password",
    "secret",
    "session_cookie",
    "token",
)

SAFE_SECRET_METADATA_KEYS = {
    "approval_token_shell_only_required",
    "no_approval_token_payload",
    "operator_confirmed_no_approval_token_payload",
    "operator_confirmed_one_time_token_shell_only",
    "one_time_token_shell_only_confirmed",
}

_BLOCKED_SIDE_EFFECT_KEYS = (
    "allow_api_execution",
    "allow_cli_execution",
    "allow_database_write",
    "allow_external_network_in_api",
    "allow_scheduler_attach",
    "api_execution_allowed",
    "api_executed_cli",
    "api_executes",
    "api_executes_cli",
    "api_opens_database_connection",
    "api_reads_approval_token",
    "api_uses_external_network",
    "api_writes_database",
    "api_writes_file",
    "apply_real_write",
    "attach_scheduler",
    "candidate_queue_created",
    "candidate_queue_persisted",
    "candidate_review_state_updated",
    "cli_executed",
    "command_executed",
    "database_commit_executed",
    "database_connection_opened",
    "database_session_created",
    "database_write_executed",
    "execute_requested",
    "executes_now",
    "external_network_executed",
    "file_written",
    "network_request_allowed",
    "opens_database_connection",
    "package_artifact_created",
    "payload_persisted",
    "ready_for_api_database_write",
    "ready_for_real_write",
    "real_write_allowed",
    "review_state_update_executed",
    "run_readiness_artifact_created",
    "run_readiness_file_written",
    "run_readiness_persisted",
    "scheduler_attach",
    "scheduler_attached",
    "write_database",
    "writes_database",
    "writes_executed",
    "would_write_database",
)


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 _safe_int(value):
    try:
        return int(value or 0)
    except (TypeError, ValueError):
        return 0


def _safe_text(value, limit=500):
    if value is None:
        return None
    text = str(value).strip()
    return text[:limit] if text else None


def _safe_path(value, *, prefixes, suffixes):
    if not isinstance(value, str):
        return False
    normalized = value.strip().replace("\\", "/")
    if not normalized or normalized.startswith("/"):
        return False
    parts = [part for part in normalized.split("/") if part]
    if any(part in (".", "..") for part in parts):
        return False
    return normalized.startswith(prefixes) and normalized.endswith(suffixes)


def _contains_forbidden_key(value, forbidden_keys, *, safe_keys=None):
    safe_keys = safe_keys or set()
    if isinstance(value, dict):
        for key, nested in value.items():
            normalized_key = str(key).lower()
            if normalized_key in safe_keys and isinstance(nested, bool):
                continue
            if any(forbidden_key in normalized_key for forbidden_key in forbidden_keys):
                return True
            if _contains_forbidden_key(nested, forbidden_keys, safe_keys=safe_keys):
                return True
    elif isinstance(value, list):
        return any(
            _contains_forbidden_key(item, forbidden_keys, safe_keys=safe_keys)
            for item in value
        )
    return False


def _blocked_side_effects(payload):
    found = []

    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 _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 found


def _run_package_review_from_inputs(review_package, review_result, phase):
    if isinstance(review_result, dict) and review_result:
        return review_result

    review_package = _as_dict(review_package)
    return build_mcp_fetch_candidate_queue_writer_run_package_review_preview(
        writer_cli_review_package=(
            review_package.get("writer_cli_review_package")
            or review_package.get("candidate_queue_writer_cli_review")
            or review_package.get("writer_cli_review")
            or review_package.get("cli_review_package")
            or {}
        ),
        writer_cli_review_result=(
            review_package.get("writer_cli_review_result")
            or review_package.get("mcp_fetch_candidate_queue_writer_cli_review")
        ),
        writer_run_package_review=(
            review_package.get("writer_run_package_review")
            or review_package.get("candidate_queue_writer_run_package_review")
            or review_package.get("run_package_review")
            or review_package.get("package_review")
            or review_package.get("review_payload")
        ),
        phase=phase,
    )


def _sample_run_readiness_package():
    review_preview = build_mcp_fetch_candidate_queue_writer_run_package_review_preview()
    review_package = review_preview["sample_writer_run_package_review_package"]
    review_result = build_mcp_fetch_candidate_queue_writer_run_package_review_preview(
        writer_cli_review_package=review_package["writer_cli_review_package"],
        writer_cli_review_result=review_package["writer_cli_review_result"],
        writer_run_package_review=review_package["writer_run_package_review"],
    )
    operator_readiness = {
        "run_readiness_artifact_path": (
            ARTIFACT_PREFIX + "candidate-queue-writer-run-readiness-sample.json"
        ),
        "reviewed_sample_json_path": (
            ARTIFACT_PREFIX + "candidate-queue-reviewed-sample.json"
        ),
        "backup_artifact_path": BACKUP_PREFIX + "momo_pro_system_backup_sample.zip",
        "read_only_preflight_output_path": (
            ARTIFACT_PREFIX + "candidate-queue-writer-preflight-sample.json"
        ),
        "postwrite_smoke_plan_path": (
            ARTIFACT_PREFIX + "candidate-queue-writer-postwrite-smoke-plan.json"
        ),
        "run_package_reviewed": True,
        "artifact_manifest_reviewed": True,
        "command_bundle_reviewed": True,
        "payload_count_reviewed": True,
        "target_table_reviewed": True,
        "backup_artifact_reviewed": True,
        "read_only_preflight_reviewed": True,
        "postwrite_smoke_required": True,
        "one_time_token_shell_only_confirmed": True,
        "operator_confirmed_no_approval_token_payload": True,
        "operator_confirmed_no_api_cli_execution": True,
        "operator_confirmed_no_api_database_write": True,
        "operator_confirmed_no_api_file_write": True,
        "operator_confirmed_no_external_network": True,
        "operator_confirmed_no_scheduler_attach": True,
        "operator_confirmed_no_persistence": True,
        "api_execution_allowed": False,
        "real_write_allowed": False,
    }
    return {
        "writer_run_package_review_package": review_package,
        "writer_run_package_review_result": review_result,
        "operator_readiness": operator_readiness,
    }


def _run_package_review_summary(review_result):
    review_result = _as_dict(review_result)
    package = _as_dict(review_result.get("writer_run_package_review_summary"))
    required_artifacts = [
        item for item in _as_list(package.get("required_artifacts"))
        if isinstance(item, dict)
    ]
    command_bundle = [
        item for item in _as_list(package.get("command_bundle"))
        if isinstance(item, dict)
    ]
    side_effects_clear = bool(
        not review_result.get("network_request_allowed")
        and not review_result.get("api_executes_cli")
        and not review_result.get("api_reads_approval_token")
        and not review_result.get("api_opens_database_connection")
        and not review_result.get("api_writes_database")
        and not review_result.get("api_uses_external_network")
        and not review_result.get("database_write_executed")
        and not review_result.get("cli_executed")
        and not review_result.get("file_written")
        and not review_result.get("scheduler_attached")
        and not review_result.get("candidate_queue_created")
        and not review_result.get("candidate_queue_persisted")
        and not package.get("blocked_side_effects")
    )
    return {
        "mode": review_result.get("mode"),
        "accepted": bool(
            review_result.get(
                "mcp_fetch_candidate_queue_writer_run_package_review_accepted"
            )
        ),
        "ready_for_run_readiness_review": bool(
            review_result.get("ready_for_candidate_queue_writer_run_readiness_review")
        ),
        "run_package_id": _safe_text(package.get("run_package_id"), 160),
        "package_mode": _safe_text(package.get("package_mode"), 160),
        "target_table": _safe_text(package.get("target_table"), 160),
        "payload_row_count": _safe_int(package.get("expected_payload_row_count")),
        "candidate_keys": sorted(
            key for key in _as_list(package.get("expected_candidate_keys")) if key
        ),
        "dedupe_keys": sorted(
            key for key in _as_list(package.get("expected_dedupe_keys")) if key
        ),
        "required_artifact_count": len(required_artifacts),
        "command_count": len(command_bundle),
        "artifacts_operator_created": bool(
            package.get("artifacts_operator_created")
        ),
        "command_bundle_api_safe": bool(package.get("command_bundle_api_safe")),
        "operator_boundaries_confirmed": bool(
            package.get("operator_boundaries_confirmed")
        ),
        "promotion_next_gate": _safe_text(package.get("promotion_next_gate"), 160),
        "side_effects_clear": side_effects_clear,
        "blocked_reasons": review_result.get("blocked_reasons", []),
        "required_artifacts": required_artifacts,
        "command_bundle": command_bundle,
    }


def _operator_summary(operator_readiness):
    operator_readiness = _as_dict(operator_readiness)
    artifact_paths = {
        "run_readiness_artifact_path": _safe_text(
            operator_readiness.get("run_readiness_artifact_path")
        ),
        "reviewed_sample_json_path": _safe_text(
            operator_readiness.get("reviewed_sample_json_path")
        ),
        "backup_artifact_path": _safe_text(
            operator_readiness.get("backup_artifact_path")
        ),
        "read_only_preflight_output_path": _safe_text(
            operator_readiness.get("read_only_preflight_output_path")
            or operator_readiness.get("preflight_artifact_path")
        ),
        "postwrite_smoke_plan_path": _safe_text(
            operator_readiness.get("postwrite_smoke_plan_path")
            or operator_readiness.get("postwrite_smoke_artifact_path")
        ),
    }
    confirmations = {
        "run_package_reviewed": bool(operator_readiness.get("run_package_reviewed")),
        "artifact_manifest_reviewed": bool(
            operator_readiness.get("artifact_manifest_reviewed")
        ),
        "command_bundle_reviewed": bool(
            operator_readiness.get("command_bundle_reviewed")
        ),
        "payload_count_reviewed": bool(
            operator_readiness.get("payload_count_reviewed")
        ),
        "target_table_reviewed": bool(
            operator_readiness.get("target_table_reviewed")
        ),
        "backup_artifact_reviewed": bool(
            operator_readiness.get("backup_artifact_reviewed")
        ),
        "read_only_preflight_reviewed": bool(
            operator_readiness.get("read_only_preflight_reviewed")
        ),
        "postwrite_smoke_required": bool(
            operator_readiness.get("postwrite_smoke_required")
        ),
        "one_time_token_shell_only_confirmed": bool(
            operator_readiness.get("one_time_token_shell_only_confirmed")
            or operator_readiness.get("operator_confirmed_one_time_token_shell_only")
        ),
        "operator_confirmed_no_approval_token_payload": bool(
            operator_readiness.get("operator_confirmed_no_approval_token_payload")
        ),
        "operator_confirmed_no_api_cli_execution": bool(
            operator_readiness.get("operator_confirmed_no_api_cli_execution")
        ),
        "operator_confirmed_no_api_database_write": bool(
            operator_readiness.get("operator_confirmed_no_api_database_write")
        ),
        "operator_confirmed_no_api_file_write": bool(
            operator_readiness.get("operator_confirmed_no_api_file_write")
        ),
        "operator_confirmed_no_external_network": bool(
            operator_readiness.get("operator_confirmed_no_external_network")
        ),
        "operator_confirmed_no_scheduler_attach": bool(
            operator_readiness.get("operator_confirmed_no_scheduler_attach")
        ),
        "operator_confirmed_no_persistence": bool(
            operator_readiness.get("operator_confirmed_no_persistence")
        ),
    }
    return {
        "provided_keys": sorted(operator_readiness.keys()),
        **artifact_paths,
        "run_readiness_artifact_path_safe": _safe_path(
            artifact_paths["run_readiness_artifact_path"],
            prefixes=(ARTIFACT_PREFIX,),
            suffixes=(".json",),
        ),
        "reviewed_sample_json_path_safe": _safe_path(
            artifact_paths["reviewed_sample_json_path"],
            prefixes=(ARTIFACT_PREFIX,),
            suffixes=(".json",),
        ),
        "backup_artifact_path_safe": _safe_path(
            artifact_paths["backup_artifact_path"],
            prefixes=(BACKUP_PREFIX,),
            suffixes=(".zip", ".tar.gz"),
        ),
        "read_only_preflight_output_path_safe": _safe_path(
            artifact_paths["read_only_preflight_output_path"],
            prefixes=(ARTIFACT_PREFIX,),
            suffixes=(".json",),
        ),
        "postwrite_smoke_plan_path_safe": _safe_path(
            artifact_paths["postwrite_smoke_plan_path"],
            prefixes=(ARTIFACT_PREFIX,),
            suffixes=(".json",),
        ),
        **confirmations,
        "api_execution_allowed": bool(operator_readiness.get("api_execution_allowed")),
        "real_write_allowed": bool(operator_readiness.get("real_write_allowed")),
        "secret_or_token_submitted_to_api": _contains_forbidden_key(
            operator_readiness,
            FORBIDDEN_SECRET_KEYS,
            safe_keys=SAFE_SECRET_METADATA_KEYS,
        ),
        "blocked_side_effects": _blocked_side_effects(operator_readiness),
    }


def _readiness_gates(*, review_received, package, operator):
    operator_reviewed_package = bool(
        operator["run_package_reviewed"]
        and operator["artifact_manifest_reviewed"]
        and operator["command_bundle_reviewed"]
        and operator["payload_count_reviewed"]
        and operator["target_table_reviewed"]
    )
    operator_reviewed_artifacts = bool(
        operator["backup_artifact_reviewed"]
        and operator["read_only_preflight_reviewed"]
        and operator["postwrite_smoke_required"]
    )
    operator_confirmed_boundaries = bool(
        operator["one_time_token_shell_only_confirmed"]
        and operator["operator_confirmed_no_approval_token_payload"]
        and operator["operator_confirmed_no_api_cli_execution"]
        and operator["operator_confirmed_no_api_database_write"]
        and operator["operator_confirmed_no_api_file_write"]
        and operator["operator_confirmed_no_external_network"]
        and operator["operator_confirmed_no_scheduler_attach"]
        and operator["operator_confirmed_no_persistence"]
    )
    return [
        {
            "key": "writer_run_package_review_payload_or_result_received",
            "label": "已提供 writer run package review package 或已審核結果",
            "passed": review_received,
        },
        {
            "key": "writer_run_package_review_accepted",
            "label": "writer run package review gate 必須已通過",
            "passed": package["accepted"],
        },
        {
            "key": "writer_run_package_review_ready_for_run_readiness",
            "label": "run package review 只放行到 run readiness review",
            "passed": package["ready_for_run_readiness_review"],
        },
        {
            "key": "writer_run_package_review_target_table_safe",
            "label": "target table 必須是 market_alert_review_queue",
            "passed": package["target_table"] == TARGET_TABLE,
        },
        {
            "key": "writer_run_package_review_payload_small_batch",
            "label": "payload row count 必須介於 1 與安全上限",
            "passed": bool(0 < package["payload_row_count"] <= MAX_READY_PAYLOAD_ROWS),
        },
        {
            "key": "writer_run_package_review_artifact_manifest_available",
            "label": "run package 必須包含操作員 artifact manifest",
            "passed": bool(
                package["required_artifact_count"] >= 3
                and package["artifacts_operator_created"]
            ),
        },
        {
            "key": "writer_run_package_review_command_bundle_available",
            "label": "run package 必須包含 API-safe command bundle",
            "passed": bool(package["command_count"] >= 3 and package["command_bundle_api_safe"]),
        },
        {
            "key": "writer_run_package_review_side_effect_free",
            "label": "run package review 未顯示 API 執行、寫 DB 或掛 scheduler",
            "passed": package["side_effects_clear"],
        },
        {
            "key": "operator_readiness_received",
            "label": "已提供操作員 readiness 證據",
            "passed": bool(operator["provided_keys"]),
        },
        {
            "key": "run_readiness_artifact_path_safe",
            "label": "run readiness artifact path 必須在 market intel artifact 目錄",
            "passed": operator["run_readiness_artifact_path_safe"],
        },
        {
            "key": "reviewed_sample_json_path_safe",
            "label": "reviewed sample JSON path 必須在 market intel artifact 目錄",
            "passed": operator["reviewed_sample_json_path_safe"],
        },
        {
            "key": "backup_artifact_path_safe",
            "label": "備份 artifact path 必須在 scripts/tools/backups 目錄",
            "passed": operator["backup_artifact_path_safe"],
        },
        {
            "key": "read_only_preflight_output_path_safe",
            "label": "read-only preflight output path 必須在 market intel artifact 目錄",
            "passed": operator["read_only_preflight_output_path_safe"],
        },
        {
            "key": "postwrite_smoke_plan_path_safe",
            "label": "post-write smoke plan path 必須在 market intel artifact 目錄",
            "passed": operator["postwrite_smoke_plan_path_safe"],
        },
        {
            "key": "operator_confirmed_package_review",
            "label": "操作員已覆核 run package、artifact manifest、command bundle 與 payload",
            "passed": operator_reviewed_package,
        },
        {
            "key": "operator_confirmed_artifacts_and_preflight",
            "label": "操作員已確認備份、read-only preflight 與 post-write smoke",
            "passed": operator_reviewed_artifacts,
        },
        {
            "key": "operator_confirmed_shell_only_boundaries",
            "label": "操作員確認 CLI-only、token shell-only、無 API/DB/scheduler 副作用",
            "passed": operator_confirmed_boundaries,
        },
        {
            "key": "operator_readiness_no_api_execution_or_real_write",
            "label": "readiness payload 不得允許 API execution 或 real write",
            "passed": bool(
                not operator["api_execution_allowed"]
                and not operator["real_write_allowed"]
            ),
        },
        {
            "key": "secret_or_token_not_submitted_to_api",
            "label": "readiness payload 不得包含 secret、cookie、password 或 token key",
            "passed": not operator["secret_or_token_submitted_to_api"],
        },
        {
            "key": "operator_readiness_side_effect_free",
            "label": "readiness payload 不得要求 API 寫檔、執行、寫 DB 或掛 scheduler",
            "passed": not operator["blocked_side_effects"],
        },
    ]


def build_mcp_fetch_candidate_queue_writer_run_readiness_preview(
    *,
    writer_run_package_review_package=None,
    writer_run_package_review_result=None,
    operator_readiness=None,
    phase=None,
):
    """建立 fetch candidate queue writer run readiness review；不執行寫入。"""
    writer_run_package_review_package = _as_dict(writer_run_package_review_package)
    review_result_received = bool(
        isinstance(writer_run_package_review_result, dict)
        and writer_run_package_review_result
    )
    operator_readiness = _as_dict(operator_readiness)
    review_result = _run_package_review_from_inputs(
        writer_run_package_review_package,
        writer_run_package_review_result,
        phase,
    )
    review_received = bool(
        writer_run_package_review_package or review_result_received
    )
    payload_received = bool(review_received or operator_readiness)
    package = _run_package_review_summary(review_result)
    operator = _operator_summary(operator_readiness)
    gates = _readiness_gates(
        review_received=review_received,
        package=package,
        operator=operator,
    )
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    accepted = bool(payload_received and not blocked_reasons)

    return {
        "mode": (
            "mcp_fetch_candidate_queue_writer_run_readiness_review"
            if payload_received
            else "mcp_fetch_candidate_queue_writer_run_readiness_preview"
        ),
        "phase": phase,
        "writer_run_readiness_payload_received": payload_received,
        "writer_run_package_review_received": review_received,
        "operator_readiness_received": bool(operator["provided_keys"]),
        "writer_run_package_review_accepted": package["accepted"],
        "mcp_fetch_candidate_queue_writer_run_readiness_accepted": accepted,
        "candidate_queue_writer_run_readiness_ready": accepted,
        "ready_for_candidate_queue_writer_operator_run": accepted,
        "ready_for_candidate_queue_writer_run_receipt_review": accepted,
        "ready_for_api_database_write": False,
        "ready_for_real_write": False,
        "ready_for_scheduler_attach": False,
        "network_request_allowed": False,
        "operator_shell_database_write_required": accepted,
        "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,
        "payload_row_count": package["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_run_package_review_summary": package,
        "operator_readiness_summary": operator,
        "sample_writer_run_readiness_package": _sample_run_readiness_package(),
        "next_operator_steps": [
            "Run readiness 通過後，操作員才可在 shell 依 run package 執行 writer CLI",
            "一次性 approval token 只能在 shell 注入，不得提交給 API/UI",
            "CLI 寫入後必須保存 writer output，再回貼到下一個 run receipt review gate",
            "API/UI 仍不得建立 artifact、寫檔、執行 CLI、讀 token、開 DB 或寫 queue",
        ],
        "payload_persisted": False,
        "run_readiness_persisted": False,
        "run_readiness_artifact_created": False,
        "run_readiness_file_written": False,
        "run_receipt_file_written": False,
        "package_artifact_created": 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,
    }
