"""
IwoooS Wazuh runtime gate owner-review readback.

This service exposes a committed owner-review readiness contract and a
no-persist validator for redacted runtime-gate owner-review packets. It never
queries live Wazuh, reads host data, reads secrets, persists raw payloads, or
authorizes runtime actions.
"""

from __future__ import annotations

import json
import re
from pathlib import Path
from typing import Any

from src.services.snapshot_paths import default_security_dir

_DEFAULT_SECURITY_DIR = default_security_dir(Path(__file__))
_SNAPSHOT_FILE = "wazuh-runtime-gate-owner-review-readback.snapshot.json"
_EXPECTED_SCHEMA = "wazuh_runtime_gate_owner_review_readback_v1"

_REQUIRED_FALSE_BOUNDARIES = {
    "active_scan_authorized",
    "alertmanager_reload_authorized",
    "auto_block_authorized",
    "credentialed_scan_authorized",
    "firewall_change_authorized",
    "host_write_authorized",
    "kali_execute_authorized",
    "kali_scan_authorized",
    "nginx_reload_authorized",
    "production_write_authorized",
    "runtime_execution_authorized",
    "runtime_gate_open",
    "secret_value_collection_allowed",
    "telegram_send_authorized",
    "wazuh_active_response_authorized",
    "wazuh_api_live_query_authorized",
}

_SENSITIVE_TEXT_PATTERNS = {
    "internal_ip": re.compile(
        r"\b(?:10|127|172\.(?:1[6-9]|2\d|3[01])|192\.168)\.\d{1,3}\.\d{1,3}\b"
    ),
    "authorization_header": re.compile(r"Authorization\s*:", re.IGNORECASE),
    "bearer_token": re.compile(r"Bearer\s+[A-Za-z0-9._-]{10,}", re.IGNORECASE),
    "basic_auth": re.compile(r"Basic\s+[A-Za-z0-9+/=]{10,}", re.IGNORECASE),
    "password_assignment": re.compile(
        r"password\s*[:=]\s*['\"][^'\"]+['\"]", re.IGNORECASE
    ),
    "token_assignment": re.compile(r"token\s*[:=]\s*['\"][^'\"]+['\"]", re.IGNORECASE),
    "cookie_assignment": re.compile(
        r"cookie\s*[:=]\s*['\"][^'\"]+['\"]", re.IGNORECASE
    ),
    "client_keys": re.compile(r"client\.keys", re.IGNORECASE),
    "private_key": re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"),
    "raw_session_text": re.compile(
        r"(工作視窗|批准！繼續|source_thread_id|raw session)", re.IGNORECASE
    ),
}

_FORBIDDEN_KEY_FRAGMENTS = {
    "authorization_header",
    "basic_auth",
    "bearer_token",
    "client_keys",
    "cookie",
    "env_file",
    "full_cli_output",
    "full_journal",
    "hostname",
    "internal_ip",
    "password",
    "private_key",
    "raw_agent_identity",
    "raw_dashboard_request",
    "raw_env",
    "raw_hostname",
    "raw_log",
    "raw_runtime_volume",
    "raw_wazuh_payload",
    "session",
    "stored_api_password",
    "token",
    "unredacted_screenshot",
    "wazuh_api_password",
}

_RUNTIME_ACTION_KEYS = {
    "active_response_enable",
    "agent_reenroll",
    "agent_restart",
    "ansible_apply",
    "ansible_playbook_run",
    "apply_now",
    "argocd_sync",
    "credentialed_scan",
    "database_migration",
    "docker_restart",
    "execute_now",
    "exploit_attempt",
    "firewall_change",
    "force_push",
    "host_write",
    "k8s_apply",
    "kali_active_scan",
    "nginx_reload",
    "repo_ref_delete",
    "runtime_execution_authorized",
    "secret_rotation",
    "systemd_restart",
    "wazuh_active_response",
    "wazuh_agent_reenroll",
    "wazuh_agent_restart",
    "wazuh_api_live_query",
    "wazuh_manager_restart",
    "workflow_trigger",
}


def load_latest_iwooos_wazuh_runtime_gate_owner_review_readback(
    security_dir: Path | None = None,
) -> dict[str, Any]:
    """Load the public-safe Wazuh runtime gate owner-review contract."""
    directory = security_dir or _DEFAULT_SECURITY_DIR
    snapshot = _load_snapshot(directory)
    _require_boundaries(snapshot)

    summary = _summary(snapshot)
    merged_summary = {
        "expected_scope_alias_count": _int(summary.get("expected_scope_alias_count")),
        "target_selector_count": _int(summary.get("target_selector_count")),
        "source_of_truth_diff_count": _int(summary.get("source_of_truth_diff_count")),
        "check_mode_plan_count": _int(summary.get("check_mode_plan_count")),
        "dry_run_evidence_count": _int(summary.get("dry_run_evidence_count")),
        "rollback_plan_count": _int(summary.get("rollback_plan_count")),
        "post_apply_verifier_count": _int(summary.get("post_apply_verifier_count")),
        "km_playbook_writeback_count": _int(summary.get("km_playbook_writeback_count")),
        "maintenance_window_review_count": _int(
            summary.get("maintenance_window_review_count")
        ),
        "owner_review_packet_received_count": _int(
            summary.get("owner_review_packet_received_count")
        ),
        "owner_review_packet_review_ready_count": _int(
            summary.get("owner_review_packet_review_ready_count")
        ),
        "owner_review_packet_accepted_count": _int(
            summary.get("owner_review_packet_accepted_count")
        ),
        "owner_review_packet_supplement_required_count": _int(
            summary.get("owner_review_packet_supplement_required_count")
        ),
        "owner_review_packet_quarantined_count": _int(
            summary.get("owner_review_packet_quarantined_count")
        ),
        "owner_review_runtime_action_rejected_count": _int(
            summary.get("owner_review_runtime_action_rejected_count")
        ),
        "forbidden_payload_count": _int(summary.get("forbidden_payload_count")),
        "forbidden_action_count": _int(summary.get("forbidden_action_count")),
        "runtime_gate_count": _int(summary.get("runtime_gate_count")),
        "wazuh_api_live_query_authorized_count": _int(
            summary.get("wazuh_api_live_query_authorized_count")
        ),
        "wazuh_active_response_authorized_count": _int(
            summary.get("wazuh_active_response_authorized_count")
        ),
        "host_write_authorized_count": _int(summary.get("host_write_authorized_count")),
        "secret_value_collection_allowed_count": _int(
            summary.get("secret_value_collection_allowed_count")
        ),
    }

    return {
        "schema_version": "iwooos_wazuh_runtime_gate_owner_review_readback_v1",
        "source_schema_version": snapshot["schema_version"],
        "status": snapshot.get(
            "status", "runtime_gate_owner_review_packet_committed_no_runtime_action"
        ),
        "mode": snapshot.get(
            "mode", "committed_owner_review_readback_no_live_wazuh_no_secret_collection"
        ),
        "source_refs": [
            f"docs/security/{_SNAPSHOT_FILE}",
            "docs/security/wazuh-runtime-controlled-apply-preflight.snapshot.json",
        ],
        "owner_review_packet_validation_endpoint": (
            "/api/v1/iwooos/wazuh-runtime-gate-owner-review-readback/validate-owner-review-packet"
        ),
        "owner_review_packet_validation_mode": "no_persist_owner_review_readback_no_runtime_action",
        "summary": merged_summary,
        "target_selectors": _target_selectors(snapshot.get("target_selectors")),
        "required_owner_review_fields": _strings(
            snapshot.get("required_owner_review_fields")
        ),
        "review_items": _review_items(snapshot.get("review_items")),
        "outcome_lanes": _strings(snapshot.get("outcome_lanes")),
        "forbidden_payloads": _strings(snapshot.get("forbidden_payloads")),
        "forbidden_actions": _strings(snapshot.get("forbidden_actions")),
        "boundary_markers": _boundary_markers(merged_summary),
        "boundaries": {
            "payload_persisted": False,
            "wazuh_api_live_query_authorized": False,
            "wazuh_active_response_authorized": False,
            "wazuh_agent_reenroll_authorized": False,
            "wazuh_agent_restart_authorized": False,
            "wazuh_manager_restart_authorized": False,
            "host_write_authorized": False,
            "active_scan_authorized": False,
            "kali_execute_authorized": False,
            "nginx_reload_authorized": False,
            "secret_value_collection_allowed": False,
            "runtime_execution_authorized": False,
            "runtime_gate_open": False,
            "not_authorization": True,
        },
        "no_false_green_rules": _strings(snapshot.get("no_false_green_rules")),
    }


def validate_iwooos_wazuh_runtime_gate_owner_review_packet(
    owner_review_packet: dict[str, Any],
    security_dir: Path | None = None,
) -> dict[str, Any]:
    """Validate one redacted runtime-gate owner-review packet without applying it."""
    contract = load_latest_iwooos_wazuh_runtime_gate_owner_review_readback(security_dir)
    snapshot = _load_snapshot(security_dir or _DEFAULT_SECURITY_DIR)
    required_fields = _strings(snapshot.get("required_owner_review_fields"))
    expected_aliases = {
        item["node_alias"]
        for item in contract["target_selectors"]
        if item.get("node_alias")
    }

    findings: list[dict[str, Any]] = []
    if not isinstance(owner_review_packet, dict):
        findings.append(
            _finding(
                "ORG-01",
                "blocker",
                "request_runtime_gate_owner_review_supplement",
                "runtime gate owner-review packet must be a JSON object.",
                [],
            )
        )
        return _validation_result(
            contract, "request_runtime_gate_owner_review_supplement", findings
        )

    sensitive_hits = _collect_sensitive_hits(owner_review_packet)
    if sensitive_hits:
        findings.append(
            _finding(
                "ORG-04",
                "critical",
                "quarantine_sensitive_payload",
                "runtime gate owner-review packet contains forbidden or likely unredacted content; response omits raw values.",
                [hit["path"] for hit in sensitive_hits[:12]],
                {"categories": sorted({hit["category"] for hit in sensitive_hits})},
            )
        )
        return _validation_result(contract, "quarantine_sensitive_payload", findings)

    runtime_hits = _collect_runtime_action_hits(owner_review_packet)
    if runtime_hits:
        findings.append(
            _finding(
                "ORG-05",
                "critical",
                "reject_runtime_action_request",
                "runtime gate owner-review packet requested runtime execution; this validator only records review readiness.",
                runtime_hits[:12],
            )
        )
        return _validation_result(contract, "reject_runtime_action_request", findings)

    missing_fields = [
        field
        for field in required_fields
        if not _present(owner_review_packet.get(field))
    ]
    if missing_fields:
        findings.append(
            _finding(
                "ORG-01",
                "blocker",
                "request_runtime_gate_owner_review_supplement",
                "runtime gate owner-review packet is missing required fields.",
                missing_fields,
            )
        )

    alias_issue = _validate_aliases(
        owner_review_packet.get("target_selector_aliases"), expected_aliases
    )
    if alias_issue:
        findings.append(
            _finding(
                "ORG-02",
                "blocker",
                "request_target_selector_fix",
                alias_issue,
                ["target_selector_aliases"],
            )
        )

    if (
        owner_review_packet.get("owner_review_intent")
        != "commit_runtime_gate_owner_review_readback_only"
    ):
        findings.append(
            _finding(
                "ORG-03",
                "blocker",
                "request_runtime_gate_owner_review_decision_fix",
                "owner_review_intent must be commit_runtime_gate_owner_review_readback_only.",
                ["owner_review_intent"],
            )
        )

    if (
        owner_review_packet.get("owner_review_decision")
        != "accept_controlled_apply_review_readiness_only"
    ):
        findings.append(
            _finding(
                "ORG-06",
                "blocker",
                "request_runtime_gate_owner_review_decision_fix",
                "owner_review_decision must be accept_controlled_apply_review_readiness_only and must not claim runtime gate opening.",
                ["owner_review_decision"],
            )
        )

    if owner_review_packet.get("runtime_boundary_ack") != "runtime_gate_remains_closed":
        findings.append(
            _finding(
                "ORG-07",
                "blocker",
                "request_runtime_boundary_ack_fix",
                "runtime_boundary_ack must state runtime_gate_remains_closed.",
                ["runtime_boundary_ack"],
            )
        )

    if owner_review_packet.get("secret_boundary_ack") != "no_secret_value_collected":
        findings.append(
            _finding(
                "ORG-08",
                "blocker",
                "request_runtime_boundary_ack_fix",
                "secret_boundary_ack must state no_secret_value_collected.",
                ["secret_boundary_ack"],
            )
        )

    if (
        owner_review_packet.get("live_wazuh_query_boundary_ack")
        != "no_live_wazuh_query_performed"
    ):
        findings.append(
            _finding(
                "ORG-09",
                "blocker",
                "request_runtime_boundary_ack_fix",
                "live_wazuh_query_boundary_ack must state no_live_wazuh_query_performed.",
                ["live_wazuh_query_boundary_ack"],
            )
        )

    outcome = (
        _first_blocking_lane(findings)
        or "accepted_for_runtime_gate_owner_review_readback_only"
    )
    if outcome == "accepted_for_runtime_gate_owner_review_readback_only":
        findings.append(
            _finding(
                "ORG-10",
                "info",
                "runtime_gate_owner_review_readback_ready",
                "owner-review packet passed no-persist readiness validation; runtime gate remains closed.",
                [
                    "owner_review_decision",
                    "check_mode_plan_ref",
                    "post_apply_verifier_ref",
                ],
            )
        )
    return _validation_result(contract, outcome, findings)


def _load_snapshot(directory: Path) -> dict[str, Any]:
    path = directory / _SNAPSHOT_FILE
    if not path.is_file():
        raise FileNotFoundError(
            f"{path}: Wazuh runtime gate owner-review snapshot not found"
        )
    with path.open(encoding="utf-8") as handle:
        payload = json.load(handle)
    if not isinstance(payload, dict):
        raise ValueError(f"{path}: expected JSON object")
    if payload.get("schema_version") != _EXPECTED_SCHEMA:
        raise ValueError(f"{path}: expected schema_version={_EXPECTED_SCHEMA}")
    return payload


def _summary(payload: dict[str, Any]) -> dict[str, Any]:
    summary = payload.get("summary")
    return summary if isinstance(summary, dict) else {}


def _int(value: Any) -> int:
    return value if isinstance(value, int) else 0


def _strings(value: Any) -> list[str]:
    if not isinstance(value, list):
        return []
    return [item for item in value if isinstance(item, str)]


def _target_selectors(value: Any) -> list[dict[str, Any]]:
    if not isinstance(value, list):
        return []
    selectors: list[dict[str, Any]] = []
    for item in value:
        if not isinstance(item, dict):
            continue
        selectors.append(
            {
                "node_alias": str(item.get("node_alias", "")),
                "scope": str(item.get("scope", "")),
                "selector_kind": str(item.get("selector_kind", "")),
                "runtime_write_allowed": item.get("runtime_write_allowed") is True,
                "owner_review_scope": str(item.get("owner_review_scope", "")),
            }
        )
    return selectors


def _review_items(value: Any) -> list[dict[str, Any]]:
    if not isinstance(value, list):
        return []
    items: list[dict[str, Any]] = []
    for item in value:
        if not isinstance(item, dict):
            continue
        items.append(
            {
                "item_id": str(item.get("item_id", "")),
                "title": str(item.get("title", "")),
                "state_key": str(item.get("state_key", "")),
                "accepted": item.get("accepted") is True,
                "required_fields": _strings(item.get("required_fields")),
                "next_gate": str(item.get("next_gate", "")),
            }
        )
    return items


def _boundary_markers(summary: dict[str, int]) -> list[str]:
    return [
        "wazuh_runtime_gate_owner_review_visible=true",
        "wazuh_runtime_gate_owner_review_validation_api_available=true",
        f"wazuh_runtime_gate_owner_review_target_selector_count={summary['target_selector_count']}",
        f"wazuh_runtime_gate_owner_review_source_diff_count={summary['source_of_truth_diff_count']}",
        f"wazuh_runtime_gate_owner_review_check_mode_plan_count={summary['check_mode_plan_count']}",
        f"wazuh_runtime_gate_owner_review_dry_run_evidence_count={summary['dry_run_evidence_count']}",
        f"wazuh_runtime_gate_owner_review_packet_received_count={summary['owner_review_packet_received_count']}",
        f"wazuh_runtime_gate_owner_review_packet_accepted_count={summary['owner_review_packet_accepted_count']}",
        f"wazuh_runtime_gate_owner_review_runtime_gate_count={summary['runtime_gate_count']}",
        "wazuh_api_live_query_authorized=false",
        "wazuh_active_response_authorized=false",
        "host_write_authorized=false",
        "secret_value_collection_allowed=false",
        "not_authorization=true",
    ]


def _require_boundaries(payload: dict[str, Any]) -> None:
    summary = _summary(payload)
    for key in (
        "owner_review_packet_supplement_required_count",
        "owner_review_packet_quarantined_count",
        "owner_review_runtime_action_rejected_count",
        "runtime_gate_count",
        "wazuh_api_live_query_authorized_count",
        "wazuh_active_response_authorized_count",
        "host_write_authorized_count",
        "secret_value_collection_allowed_count",
    ):
        if _int(summary.get(key)) != 0:
            raise ValueError(
                f"Wazuh runtime gate owner-review summary.{key} must remain 0"
            )

    expected_alias_count = _int(summary.get("expected_scope_alias_count"))
    target_selector_count = _int(summary.get("target_selector_count"))
    target_selectors = _target_selectors(payload.get("target_selectors"))
    if (
        target_selector_count != expected_alias_count
        or len(target_selectors) != expected_alias_count
    ):
        raise ValueError(
            "Wazuh runtime gate owner-review target selectors must match expected alias count"
        )
    if any(item.get("runtime_write_allowed") is True for item in target_selectors):
        raise ValueError(
            "Wazuh runtime gate owner-review target selectors must not allow runtime writes"
        )

    readiness_keys = (
        "source_of_truth_diff_count",
        "check_mode_plan_count",
        "dry_run_evidence_count",
        "rollback_plan_count",
        "post_apply_verifier_count",
        "km_playbook_writeback_count",
        "maintenance_window_review_count",
        "owner_review_packet_received_count",
        "owner_review_packet_review_ready_count",
        "owner_review_packet_accepted_count",
    )
    if any(_int(summary.get(key)) <= 0 for key in readiness_keys):
        raise ValueError(
            "Wazuh runtime gate owner-review readiness counters must be positive"
        )

    boundaries = payload.get("execution_boundaries")
    if not isinstance(boundaries, dict):
        raise ValueError("Wazuh runtime gate owner-review execution_boundaries missing")
    for key in _REQUIRED_FALSE_BOUNDARIES:
        if boundaries.get(key) is not False:
            raise ValueError(
                f"Wazuh runtime gate owner-review execution_boundaries.{key} must remain false"
            )
    if boundaries.get("not_authorization") is not True:
        raise ValueError(
            "Wazuh runtime gate owner-review not_authorization must remain true"
        )


def _validation_result(
    contract: dict[str, Any],
    outcome_lane: str,
    findings: list[dict[str, Any]],
) -> dict[str, Any]:
    accepted = outcome_lane == "accepted_for_runtime_gate_owner_review_readback_only"
    quarantined = outcome_lane == "quarantine_sensitive_payload"
    rejected_runtime = outcome_lane == "reject_runtime_action_request"
    supplement_required = not accepted and not quarantined and not rejected_runtime
    return {
        "schema_version": "iwooos_wazuh_runtime_gate_owner_review_packet_validation_result_v1",
        "contract_schema_version": contract["schema_version"],
        "status": outcome_lane,
        "mode": "no_persist_runtime_gate_owner_review_no_runtime_no_secret_collection",
        "outcome_lane": outcome_lane,
        "accepted_for_runtime_gate_owner_review_readback_only": accepted,
        "quarantined": quarantined,
        "runtime_action_rejected": rejected_runtime,
        "summary": {
            "owner_review_packet_received_count": 1,
            "owner_review_packet_review_ready_count": 1 if accepted else 0,
            "owner_review_packet_accepted_count": 1 if accepted else 0,
            "owner_review_packet_supplement_required_count": 1
            if supplement_required
            else 0,
            "owner_review_packet_quarantined_count": 1 if quarantined else 0,
            "owner_review_runtime_action_rejected_count": 1 if rejected_runtime else 0,
            "runtime_gate_count": 0,
            "wazuh_api_live_query_authorized_count": 0,
            "wazuh_active_response_authorized_count": 0,
            "host_write_authorized_count": 0,
            "secret_value_collection_allowed_count": 0,
            "finding_count": len(findings),
        },
        "validation_findings": findings,
        "boundary_markers": [
            "wazuh_runtime_gate_owner_review_packet_validation_received_count=1",
            f"wazuh_runtime_gate_owner_review_packet_validation_accepted_count={1 if accepted else 0}",
            f"wazuh_runtime_gate_owner_review_packet_validation_quarantined_count={1 if quarantined else 0}",
            f"wazuh_runtime_gate_owner_review_packet_validation_runtime_action_rejected_count={1 if rejected_runtime else 0}",
            "wazuh_runtime_gate_owner_review_packet_validation_runtime_gate_count=0",
            "wazuh_runtime_gate_owner_review_packet_validation_no_persist=true",
            "wazuh_api_live_query_authorized=false",
            "wazuh_active_response_authorized=false",
            "host_write_authorized=false",
            "secret_value_collection_allowed=false",
            "not_authorization=true",
        ],
        "boundaries": {
            "payload_persisted": False,
            "wazuh_api_live_query_authorized": False,
            "wazuh_active_response_authorized": False,
            "wazuh_agent_reenroll_authorized": False,
            "wazuh_agent_restart_authorized": False,
            "wazuh_manager_restart_authorized": False,
            "host_write_authorized": False,
            "active_scan_authorized": False,
            "kali_execute_authorized": False,
            "nginx_reload_authorized": False,
            "secret_value_collection_allowed": False,
            "runtime_execution_authorized": False,
            "runtime_gate_open": False,
            "not_authorization": True,
        },
        "next_gate": "stage_allowlisted_check_mode_dry_run_before_runtime_gate"
        if accepted
        else "runtime_gate_owner_review_packet_fix_and_resubmit",
    }


def _finding(
    check_id: str,
    severity: str,
    lane: str,
    message: str,
    field_paths: list[str],
    extra: dict[str, Any] | None = None,
) -> dict[str, Any]:
    payload: dict[str, Any] = {
        "check_id": check_id,
        "severity": severity,
        "lane": lane,
        "message": message,
        "field_paths": field_paths,
    }
    if extra:
        payload.update(extra)
    return payload


def _present(value: Any) -> bool:
    if value is None:
        return False
    if isinstance(value, str):
        return bool(value.strip())
    if isinstance(value, list | dict | tuple | set):
        return bool(value)
    return True


def _validate_aliases(value: Any, expected_aliases: set[str]) -> str | None:
    aliases = value if isinstance(value, list) else []
    if not aliases or not all(isinstance(item, str) for item in aliases):
        return "target_selector_aliases must be an array of public alias strings."
    alias_set = set(aliases)
    if len(aliases) != len(alias_set):
        return "target_selector_aliases must not contain duplicates."
    if alias_set != expected_aliases:
        missing = sorted(expected_aliases - alias_set)
        extra = sorted(alias_set - expected_aliases)
        return f"target_selector_aliases must match expected public aliases; missing={missing} extra={extra}"
    return None


def _collect_sensitive_hits(value: Any, path: str = "$") -> list[dict[str, str]]:
    hits: list[dict[str, str]] = []
    if isinstance(value, dict):
        for key, item in value.items():
            key_text = str(key)
            key_lower = key_text.lower()
            for fragment in _FORBIDDEN_KEY_FRAGMENTS:
                if fragment in key_lower:
                    hits.append(
                        {
                            "path": f"{path}.{key_text}",
                            "category": f"forbidden_key:{fragment}",
                        }
                    )
            hits.extend(_collect_sensitive_hits(item, f"{path}.{key_text}"))
        return hits
    if isinstance(value, list):
        for index, item in enumerate(value):
            hits.extend(_collect_sensitive_hits(item, f"{path}[{index}]"))
        return hits
    if isinstance(value, str):
        for category, pattern in _SENSITIVE_TEXT_PATTERNS.items():
            if pattern.search(value):
                hits.append({"path": path, "category": category})
    return hits


def _collect_runtime_action_hits(value: Any, path: str = "$") -> list[str]:
    hits: list[str] = []
    if isinstance(value, dict):
        for key, item in value.items():
            key_text = str(key)
            normalized_key = key_text.lower().replace("-", "_").replace(" ", "_")
            if normalized_key in _RUNTIME_ACTION_KEYS and item not in (
                False,
                None,
                "",
                [],
                {},
            ):
                hits.append(f"{path}.{key_text}")
            hits.extend(_collect_runtime_action_hits(item, f"{path}.{key_text}"))
        return hits
    if isinstance(value, list):
        for index, item in enumerate(value):
            hits.extend(_collect_runtime_action_hits(item, f"{path}[{index}]"))
        return hits
    if isinstance(value, str):
        normalized = value.lower().replace("-", "_").replace(" ", "_")
        if normalized in _RUNTIME_ACTION_KEYS:
            hits.append(path)
    return hits


def _first_blocking_lane(findings: list[dict[str, Any]]) -> str | None:
    severity_order = {"critical": 0, "blocker": 1, "warn": 2, "info": 3}
    blocking = [
        finding
        for finding in findings
        if finding.get("severity") in {"critical", "blocker"}
    ]
    if not blocking:
        return None
    blocking.sort(
        key=lambda finding: severity_order.get(str(finding.get("severity")), 99)
    )
    return str(
        blocking[0].get("lane") or "request_runtime_gate_owner_review_supplement"
    )
