"""市場情報 MCP manual fetch result parser review preview。

本模組只審核操作員解析 dry-run fetch 結果後貼回的結構化摘要；
不讀 artifact、不執行 parser CLI、不發 HTTP request、不寫 DB、不掛 scheduler。
"""

import ipaddress
from urllib.parse import urlparse

from services.market_intel.mcp_fetch_run_package import RUN_ARTIFACT_DIR_PREFIX
from services.market_intel.mcp_fetch_run_receipt import (
    build_mcp_fetch_run_receipt_preview,
)


MAX_CANDIDATES_PER_SOURCE = 10

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

SAFE_SECRET_METADATA_KEYS = {
    "operator_confirmed_no_secret_payload",
}

SAFE_RAW_METADATA_KEYS = {
    "operator_confirmed_no_raw_html",
}

FORBIDDEN_RAW_PAYLOAD_KEYS = (
    "body_html",
    "document_html",
    "html",
    "page_html",
    "raw_body",
    "raw_html",
    "raw_snapshot",
    "response_body",
)

_BLOCKED_SIDE_EFFECT_KEYS = (
    "allow_api_execution",
    "allow_database_write",
    "allow_external_network_in_api",
    "allow_scheduler_attach",
    "api_executed_cli",
    "api_executes_cli",
    "api_executes_docker",
    "api_executes_health_check",
    "api_executes_ssh",
    "api_opens_database_connection",
    "api_uses_external_network",
    "api_writes_database",
    "attach_scheduler",
    "candidate_handoff_persisted",
    "cli_executed",
    "command_executed",
    "database_commit_executed",
    "database_session_created",
    "database_write_executed",
    "external_network_executed",
    "fetch_executed",
    "file_written",
    "manual_fetch_gate_opened_by_api",
    "network_request_allowed",
    "parser_artifact_written_by_api",
    "parser_executed_by_api",
    "payload_persisted",
    "result_parser_file_written",
    "result_parser_persisted",
    "scheduler_attached",
    "write_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 _has_text(value):
    return bool(isinstance(value, str) and value.strip())


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_artifact_path(value, *, require_json=False):
    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
    if not normalized.startswith(RUN_ARTIFACT_DIR_PREFIX):
        return False
    return not require_json or normalized.endswith(".json")


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 _is_public_http_url(value):
    if not isinstance(value, str):
        return False
    parsed = urlparse(value.strip())
    if parsed.scheme not in {"http", "https"} or not parsed.netloc:
        return False
    if parsed.username or parsed.password:
        return False
    host = (parsed.hostname or "").lower()
    if host in {"localhost", "127.0.0.1", "::1"}:
        return False
    try:
        ip = ipaddress.ip_address(host)
    except ValueError:
        return bool(host and "." in host)
    return not (
        ip.is_private
        or ip.is_loopback
        or ip.is_link_local
        or ip.is_reserved
        or ip.is_multicast
    )


def _run_receipt_from_inputs(run_receipt_package, run_receipt_result, phase):
    if isinstance(run_receipt_result, dict) and run_receipt_result:
        return run_receipt_result

    run_receipt_package = _as_dict(run_receipt_package)
    return build_mcp_fetch_run_receipt_preview(
        run_readiness_package=(
            run_receipt_package.get("run_readiness_package")
            or run_receipt_package.get("run_readiness")
            or run_receipt_package.get("readiness_package")
        ),
        run_readiness_result=(
            run_receipt_package.get("run_readiness_result")
            or run_receipt_package.get("mcp_fetch_run_readiness")
        ),
        manual_fetch_receipt=(
            run_receipt_package.get("manual_fetch_receipt")
            or run_receipt_package.get("fetch_receipt")
            or run_receipt_package.get("receipt")
        ),
        phase=phase,
    )


def _sample_parser_result_package():
    receipt_preview = build_mcp_fetch_run_receipt_preview()
    run_receipt_package = receipt_preview["sample_run_receipt_package"]
    run_receipt_result = build_mcp_fetch_run_receipt_preview(
        run_readiness_package=run_receipt_package["run_readiness_package"],
        run_readiness_result=run_receipt_package["run_readiness_result"],
        manual_fetch_receipt=run_receipt_package["manual_fetch_receipt"],
    )
    receipt_sources = (
        run_receipt_result.get("manual_fetch_receipt_summary", {}).get("sources")
        or []
    )
    parsed_sources = []
    for source in receipt_sources:
        platform_code = source.get("platform_code")
        source_key = source.get("source_key")
        receipt_path = source.get("receipt_path")
        parser_path = str(receipt_path or "").replace(
            "_receipt.json",
            "_parser_review.json",
        )
        campaign_key = f"{platform_code}:{source_key}:sample-campaign"
        product_id = f"{platform_code}-{source_key}-sample-product"
        parsed_sources.append(
            {
                "platform_code": platform_code,
                "source_key": source_key,
                "receipt_path": receipt_path,
                "parser_artifact_path": parser_path,
                "parser_status": "parsed_preview",
                "parser_executed_by": "operator_shell",
                "campaign_candidate_count": 1,
                "product_candidate_count": 1,
                "campaign_candidates": [
                    {
                        "candidate_type": "campaign",
                        "platform_code": platform_code,
                        "source_key": source_key,
                        "campaign_key": campaign_key,
                        "campaign_name": f"{source_key} sample campaign",
                        "campaign_url": source.get("source_url"),
                        "campaign_type": "manual_fetch_sample",
                        "confidence_band": "parser_preview",
                    }
                ],
                "product_candidates": [
                    {
                        "candidate_type": "product",
                        "platform_code": platform_code,
                        "source_key": source_key,
                        "platform_product_id": product_id,
                        "name": f"{source_key} sample product",
                        "product_url": source.get("source_url"),
                        "campaign_key": campaign_key,
                        "price": 100,
                        "currency": "TWD",
                        "confidence_band": "parser_preview",
                    }
                ],
                "api_executes_cli": False,
                "api_uses_external_network": False,
                "database_write_executed": False,
                "scheduler_attached": False,
            }
        )

    return {
        "run_receipt_package": run_receipt_package,
        "run_receipt_result": run_receipt_result,
        "parser_result": {
            "parser_run_id": "market-intel-parser-sample",
            "parser_artifact_path": (
                RUN_ARTIFACT_DIR_PREFIX
                + "sample_market_intel_manual_fetch/parser_review.json"
            ),
            "parser_executed_by": "operator_shell",
            "operator_confirmed_no_raw_html": True,
            "operator_confirmed_no_secret_payload": True,
            "operator_confirmed_no_api_execution": True,
            "operator_confirmed_no_database_write": True,
            "operator_confirmed_no_scheduler_attach": True,
            "summary": {
                "source_count": len(parsed_sources),
                "campaign_candidate_count": len(parsed_sources),
                "product_candidate_count": len(parsed_sources),
            },
            "parsed_sources": parsed_sources,
        },
    }


def _receipt_summary(run_receipt):
    run_receipt = _as_dict(run_receipt)
    receipt = _as_dict(run_receipt.get("manual_fetch_receipt_summary"))
    side_effects_clear = bool(
        not run_receipt.get("manual_fetch_gate_opened_by_api")
        and not run_receipt.get("network_request_allowed")
        and not run_receipt.get("api_executes_cli")
        and not run_receipt.get("api_opens_database_connection")
        and not run_receipt.get("api_writes_database")
        and not run_receipt.get("api_uses_external_network")
        and not run_receipt.get("database_write_executed")
        and not run_receipt.get("fetch_executed_by_api")
        and not run_receipt.get("file_written")
        and not run_receipt.get("scheduler_attached")
    )
    source_keys = sorted(
        tuple(item)
        for item in _as_list(receipt.get("source_keys"))
        if isinstance(item, (list, tuple)) and len(item) == 2
    )
    receipt_paths = sorted(
        path for path in _as_list(receipt.get("receipt_paths")) if path
    )
    return {
        "mode": run_receipt.get("mode"),
        "accepted": bool(run_receipt.get("mcp_fetch_run_receipt_accepted")),
        "ready_for_manual_fetch_result_parser_review": bool(
            run_receipt.get("ready_for_manual_fetch_result_parser_review")
        ),
        "source_count": _safe_int(run_receipt.get("receipt_source_count")),
        "request_count": _safe_int(run_receipt.get("request_count")),
        "error_count": _safe_int(run_receipt.get("error_count")),
        "source_keys": source_keys,
        "receipt_paths": receipt_paths,
        "side_effects_clear": side_effects_clear,
        "blocked_reasons": run_receipt.get("blocked_reasons", []),
    }


def _campaign_candidate_summary(candidate):
    candidate = _as_dict(candidate)
    return {
        "candidate_type": candidate.get("candidate_type"),
        "platform_code": _safe_text(candidate.get("platform_code"), 80),
        "source_key": _safe_text(candidate.get("source_key"), 160),
        "campaign_key": _safe_text(candidate.get("campaign_key"), 240),
        "campaign_name": _safe_text(candidate.get("campaign_name"), 300),
        "campaign_url": _safe_text(candidate.get("campaign_url"), 500),
        "campaign_type": _safe_text(candidate.get("campaign_type"), 120),
        "confidence_band": _safe_text(candidate.get("confidence_band"), 80),
        "url_public": _is_public_http_url(candidate.get("campaign_url")),
        "required_fields_present": bool(
            candidate.get("candidate_type") == "campaign"
            and _has_text(candidate.get("platform_code"))
            and _has_text(candidate.get("source_key"))
            and _has_text(candidate.get("campaign_key"))
            and _has_text(candidate.get("campaign_name"))
            and _has_text(candidate.get("campaign_url"))
        ),
    }


def _product_candidate_summary(candidate):
    candidate = _as_dict(candidate)
    price = candidate.get("price")
    price_ok = isinstance(price, (int, float)) and price >= 0
    return {
        "candidate_type": candidate.get("candidate_type"),
        "platform_code": _safe_text(candidate.get("platform_code"), 80),
        "source_key": _safe_text(candidate.get("source_key"), 160),
        "platform_product_id": _safe_text(candidate.get("platform_product_id"), 240),
        "name": _safe_text(candidate.get("name"), 300),
        "product_url": _safe_text(candidate.get("product_url"), 500),
        "campaign_key": _safe_text(candidate.get("campaign_key"), 240),
        "price": price,
        "currency": _safe_text(candidate.get("currency"), 20),
        "confidence_band": _safe_text(candidate.get("confidence_band"), 80),
        "url_public": _is_public_http_url(candidate.get("product_url")),
        "price_valid": price_ok,
        "required_fields_present": bool(
            candidate.get("candidate_type") == "product"
            and _has_text(candidate.get("platform_code"))
            and _has_text(candidate.get("source_key"))
            and _has_text(candidate.get("platform_product_id"))
            and _has_text(candidate.get("name"))
            and _has_text(candidate.get("product_url"))
            and price_ok
        ),
    }


def _parser_result_summary(parser_result):
    parser_result = _as_dict(parser_result)
    parsed_sources = [_as_dict(item) for item in _as_list(
        parser_result.get("parsed_sources")
    )]
    source_summaries = []
    campaign_candidates = []
    product_candidates = []
    for source in parsed_sources:
        campaigns = [
            _campaign_candidate_summary(item)
            for item in _as_list(source.get("campaign_candidates"))
        ]
        products = [
            _product_candidate_summary(item)
            for item in _as_list(source.get("product_candidates"))
        ]
        campaign_candidates.extend(campaigns)
        product_candidates.extend(products)
        source_summaries.append(
            {
                "platform_code": _safe_text(source.get("platform_code"), 80),
                "source_key": _safe_text(source.get("source_key"), 160),
                "receipt_path": _safe_text(source.get("receipt_path"), 500),
                "receipt_path_safe": _safe_artifact_path(
                    source.get("receipt_path"),
                    require_json=True,
                ),
                "parser_artifact_path": _safe_text(
                    source.get("parser_artifact_path"),
                    500,
                ),
                "parser_artifact_path_safe": _safe_artifact_path(
                    source.get("parser_artifact_path"),
                    require_json=True,
                ),
                "parser_status": _safe_text(source.get("parser_status"), 80),
                "parser_executed_by": _safe_text(source.get("parser_executed_by"), 80),
                "campaign_candidate_count": _safe_int(
                    source.get("campaign_candidate_count")
                ),
                "product_candidate_count": _safe_int(
                    source.get("product_candidate_count")
                ),
                "observed_campaign_candidate_count": len(campaigns),
                "observed_product_candidate_count": len(products),
                "campaign_candidates": campaigns,
                "product_candidates": products,
            }
        )

    summary = _as_dict(parser_result.get("summary"))
    campaign_count = len(campaign_candidates)
    product_count = len(product_candidates)
    return {
        "provided_keys": sorted(parser_result.keys()),
        "parser_run_id": _safe_text(parser_result.get("parser_run_id"), 160),
        "parser_artifact_path": _safe_text(parser_result.get("parser_artifact_path"), 500),
        "parser_artifact_path_safe": _safe_artifact_path(
            parser_result.get("parser_artifact_path"),
            require_json=True,
        ),
        "parser_executed_by": _safe_text(parser_result.get("parser_executed_by"), 80),
        "operator_confirmed_no_raw_html": bool(
            parser_result.get("operator_confirmed_no_raw_html")
        ),
        "operator_confirmed_no_secret_payload": bool(
            parser_result.get("operator_confirmed_no_secret_payload")
        ),
        "operator_confirmed_no_api_execution": bool(
            parser_result.get("operator_confirmed_no_api_execution")
        ),
        "operator_confirmed_no_database_write": bool(
            parser_result.get("operator_confirmed_no_database_write")
        ),
        "operator_confirmed_no_scheduler_attach": bool(
            parser_result.get("operator_confirmed_no_scheduler_attach")
        ),
        "source_count": len(source_summaries),
        "summary_source_count": _safe_int(summary.get("source_count")),
        "campaign_candidate_count": campaign_count,
        "summary_campaign_candidate_count": _safe_int(
            summary.get("campaign_candidate_count")
        ),
        "product_candidate_count": product_count,
        "summary_product_candidate_count": _safe_int(
            summary.get("product_candidate_count")
        ),
        "candidate_count": campaign_count + product_count,
        "source_keys": sorted(
            (
                item["platform_code"],
                item["source_key"],
            )
            for item in source_summaries
            if item["platform_code"] and item["source_key"]
        ),
        "receipt_paths": sorted(
            item["receipt_path"] for item in source_summaries if item["receipt_path"]
        ),
        "source_summaries": source_summaries,
        "campaign_candidates": campaign_candidates,
        "product_candidates": product_candidates,
        "all_parser_artifact_paths_safe": bool(
            source_summaries
            and all(item["parser_artifact_path_safe"] for item in source_summaries)
        ),
        "all_receipt_paths_safe": bool(
            source_summaries and all(item["receipt_path_safe"] for item in source_summaries)
        ),
        "all_status_parsed_preview": bool(
            source_summaries
            and all(item["parser_status"] == "parsed_preview" for item in source_summaries)
        ),
        "all_executed_by_operator_shell": bool(
            parser_result.get("parser_executed_by") == "operator_shell"
            and source_summaries
            and all(item["parser_executed_by"] == "operator_shell" for item in source_summaries)
        ),
        "all_candidate_urls_public": bool(
            campaign_candidates + product_candidates
            and all(item["url_public"] for item in campaign_candidates + product_candidates)
        ),
        "all_candidate_required_fields_present": bool(
            campaign_candidates + product_candidates
            and all(
                item["required_fields_present"]
                for item in campaign_candidates + product_candidates
            )
        ),
        "source_counts_match_candidates": bool(
            source_summaries
            and all(
                item["campaign_candidate_count"]
                == item["observed_campaign_candidate_count"]
                and item["product_candidate_count"]
                == item["observed_product_candidate_count"]
                for item in source_summaries
            )
        ),
        "summary_counts_match_candidates": bool(
            _safe_int(summary.get("source_count")) == len(source_summaries)
            and _safe_int(summary.get("campaign_candidate_count")) == campaign_count
            and _safe_int(summary.get("product_candidate_count")) == product_count
        ),
        "raw_payload_submitted_to_api": _contains_forbidden_key(
            parser_result,
            FORBIDDEN_RAW_PAYLOAD_KEYS,
            safe_keys=SAFE_RAW_METADATA_KEYS,
        ),
        "secret_or_token_submitted_to_api": _contains_forbidden_key(
            parser_result,
            FORBIDDEN_SECRET_KEYS,
            safe_keys=SAFE_SECRET_METADATA_KEYS,
        ),
        "blocked_side_effects": _blocked_side_effects(parser_result),
    }


def _parser_gates(
    *,
    run_receipt_received,
    parser_result_received,
    parser_result_valid_object,
    receipt,
    parser,
):
    receipt_source_keys = set(receipt["source_keys"])
    parser_source_keys = set(parser["source_keys"])
    receipt_paths = set(receipt["receipt_paths"])
    parser_receipt_paths = set(parser["receipt_paths"])
    max_candidates = max(1, receipt["source_count"]) * MAX_CANDIDATES_PER_SOURCE
    operator_boundaries_confirmed = bool(
        parser["operator_confirmed_no_raw_html"]
        and parser["operator_confirmed_no_secret_payload"]
        and parser["operator_confirmed_no_api_execution"]
        and parser["operator_confirmed_no_database_write"]
        and parser["operator_confirmed_no_scheduler_attach"]
    )
    return [
        {
            "key": "run_receipt_payload_or_result_received",
            "label": "已提供 run receipt package 或已審核結果",
            "passed": run_receipt_received,
        },
        {
            "key": "run_receipt_accepted",
            "label": "run receipt gate 必須已通過",
            "passed": receipt["accepted"],
        },
        {
            "key": "run_receipt_ready_for_parser_review",
            "label": "receipt 只放行到 result parser review",
            "passed": receipt["ready_for_manual_fetch_result_parser_review"],
        },
        {
            "key": "run_receipt_side_effect_free",
            "label": "receipt 結果未顯示 API 執行、連外、寫檔、寫 DB 或掛 scheduler",
            "passed": receipt["side_effects_clear"],
        },
        {
            "key": "parser_result_received",
            "label": "已提供 parser result 結構化摘要",
            "passed": parser_result_received,
        },
        {
            "key": "parser_result_valid_object",
            "label": "parser result payload 必須是 JSON object",
            "passed": parser_result_valid_object,
        },
        {
            "key": "parser_identity_recorded",
            "label": "parser result 必須記錄 parser_run_id 與 artifact path",
            "passed": bool(parser["parser_run_id"] and parser["parser_artifact_path_safe"]),
        },
        {
            "key": "parser_sources_match_receipt_sources",
            "label": "parser source 必須完全對齊 receipt platform/source",
            "passed": bool(receipt_source_keys and parser_source_keys == receipt_source_keys),
        },
        {
            "key": "parser_receipt_paths_match_receipt",
            "label": "parser 引用的 receipt path 必須完全對齊 receipt gate",
            "passed": bool(receipt_paths and parser_receipt_paths == receipt_paths),
        },
        {
            "key": "parser_artifact_paths_safe",
            "label": "parser artifact path 必須在 market intel manual fetch 相對目錄內",
            "passed": bool(
                parser["parser_artifact_path_safe"]
                and parser["all_parser_artifact_paths_safe"]
                and parser["all_receipt_paths_safe"]
            ),
        },
        {
            "key": "parser_status_parsed_preview",
            "label": "每個 source 都必須回報 parsed_preview",
            "passed": parser["all_status_parsed_preview"],
        },
        {
            "key": "parser_executed_by_operator_shell",
            "label": "parser result 必須標明由操作員 shell 產生，不是 API",
            "passed": parser["all_executed_by_operator_shell"],
        },
        {
            "key": "parser_candidate_counts_within_preview_limit",
            "label": "候選數需維持小批次 preview 上限",
            "passed": bool(0 < parser["candidate_count"] <= max_candidates),
        },
        {
            "key": "parser_candidate_counts_match_summary",
            "label": "summary / source count 必須與候選陣列數量一致",
            "passed": bool(
                parser["source_counts_match_candidates"]
                and parser["summary_counts_match_candidates"]
            ),
        },
        {
            "key": "parser_candidate_required_fields_present",
            "label": "活動/商品候選必須具備必要識別欄位",
            "passed": parser["all_candidate_required_fields_present"],
        },
        {
            "key": "parser_candidate_urls_public_http",
            "label": "活動/商品候選 URL 必須是公開 http(s) URL，且不含帳密",
            "passed": parser["all_candidate_urls_public"],
        },
        {
            "key": "parser_operator_boundaries_confirmed",
            "label": "操作員確認無 raw HTML、無 secret、無 API/DB/scheduler 副作用",
            "passed": operator_boundaries_confirmed,
        },
        {
            "key": "parser_no_raw_payload",
            "label": "parser result 不得回貼 raw HTML/body/snapshot",
            "passed": not parser["raw_payload_submitted_to_api"],
        },
        {
            "key": "parser_no_secret_or_token_key",
            "label": "parser result 不得包含 secret、cookie、password 或 token key",
            "passed": not parser["secret_or_token_submitted_to_api"],
        },
        {
            "key": "parser_side_effect_free",
            "label": "parser result 不得要求 API 執行、連外、寫檔、寫 DB 或掛 scheduler",
            "passed": not parser["blocked_side_effects"],
        },
    ]


def build_mcp_fetch_result_parser_review_preview(
    *,
    run_receipt_package=None,
    run_receipt_result=None,
    parser_result=None,
    phase=None,
):
    """建立 fetch result parser review；不讀 artifact 或執行 parser。"""
    run_receipt_package = _as_dict(run_receipt_package)
    run_receipt_result_received = bool(
        isinstance(run_receipt_result, dict) and run_receipt_result
    )
    parser_result_valid_object = isinstance(parser_result, dict) if (
        parser_result is not None
    ) else True
    parser_payload = _as_dict(parser_result)
    run_receipt = _run_receipt_from_inputs(
        run_receipt_package,
        run_receipt_result,
        phase,
    )
    run_receipt_received = bool(run_receipt_package or run_receipt_result_received)
    parser_payload_received = bool(
        run_receipt_received or parser_payload or parser_result is not None
    )
    parser_result_received = bool(parser_payload)
    receipt = _receipt_summary(run_receipt)
    parser = _parser_result_summary(parser_payload)
    gates = _parser_gates(
        run_receipt_received=run_receipt_received,
        parser_result_received=parser_result_received,
        parser_result_valid_object=parser_result_valid_object,
        receipt=receipt,
        parser=parser,
    )
    blocked_reasons = [gate["key"] for gate in gates if not gate["passed"]]
    accepted = bool(parser_payload_received and not blocked_reasons)

    return {
        "mode": (
            "mcp_fetch_result_parser_review"
            if parser_payload_received
            else "mcp_fetch_result_parser_review_preview"
        ),
        "phase": phase,
        "parser_payload_received": parser_payload_received,
        "run_receipt_received": run_receipt_received,
        "parser_result_received": parser_result_received,
        "parser_result_valid_object": parser_result_valid_object,
        "run_receipt_accepted": receipt["accepted"],
        "mcp_fetch_result_parser_review_accepted": accepted,
        "result_parser_review_ready": accepted,
        "ready_for_manual_fetch_candidate_handoff_review": accepted,
        "ready_for_api_database_write": False,
        "ready_for_scheduler_attach": False,
        "manual_fetch_gate_opened_by_api": False,
        "network_request_allowed": False,
        "parser_executed_by_api": False,
        "fetch_executed": False,
        "cli_executed": False,
        "database_write_executed": False,
        "scheduler_attached": False,
        "receipt_source_count": receipt["source_count"],
        "parser_source_count": parser["source_count"],
        "candidate_count": parser["candidate_count"],
        "campaign_candidate_count": parser["campaign_candidate_count"],
        "product_candidate_count": parser["product_candidate_count"],
        "gate_count": len(gates),
        "passed_gate_count": sum(1 for gate in gates if gate["passed"]),
        "blocked_reasons": blocked_reasons,
        "gates": gates,
        "run_receipt_summary": receipt,
        "parser_result_summary": parser,
        "sample_parser_result_package": _sample_parser_result_package(),
        "next_operator_steps": [
            "parser review 通過後，只代表可進候選 handoff review，不代表可寫 market_*",
            "候選 handoff、DB import、scheduler attach、AI/Telegram 摘要都必須另開獨立 gate",
            "API/UI 仍不得讀 artifact、不得執行 parser CLI、不得抓外站、不得寫 DB、不得掛 scheduler",
        ],
        "payload_persisted": False,
        "result_parser_persisted": False,
        "result_parser_file_written": False,
        "candidate_handoff_persisted": False,
        "api_executes_health_check": False,
        "api_executes_docker": False,
        "api_executes_ssh": False,
        "api_executes_cli": False,
        "api_opens_database_connection": False,
        "api_writes_database": False,
        "api_uses_external_network": False,
        "database_session_created": False,
        "database_commit_executed": False,
        "external_network_executed": False,
        "file_written": False,
        "writes_executed": False,
        "would_write_database": False,
    }
