"""StockPlatform public API controlled recovery preflight.

This module packages the next P0-006 action after public API 502 drift is
detected. It does not SSH, run Docker, restart services, write databases, read
secrets, or trigger workflows.
"""

from __future__ import annotations

import re
from pathlib import Path
from typing import Any

from src.services.snapshot_paths import resolve_repo_root
from src.services.stockplatform_public_api_runtime_readback import (
    load_latest_stockplatform_public_api_runtime_readback,
)

_SCHEMA_VERSION = "stockplatform_public_api_controlled_recovery_preflight_v1"
_REPO_ROOT = resolve_repo_root(Path(__file__))
_DEFAULT_ROUTE_SOURCE = (
    _REPO_ROOT
    / "infra"
    / "ansible"
    / "roles"
    / "nginx"
    / "templates"
    / "188-all-sites.conf.j2"
)
_AI_RECOMMENDATIONS_STALE_AFTER_CORE_RECOVERED = (
    "ai_recommendations_stale_after_core_recovered"
)


def load_latest_stockplatform_public_api_controlled_recovery_preflight(
    *,
    runtime_readback: dict[str, Any] | None = None,
    route_source_path: Path | None = None,
) -> dict[str, Any]:
    """Build the controlled recovery preflight for the active P0-006 drift."""
    runtime = runtime_readback or load_latest_stockplatform_public_api_runtime_readback()
    route_contract = _load_route_contract(route_source_path or _DEFAULT_ROUTE_SOURCE)
    return _build_payload(runtime=runtime, route_contract=route_contract)


def _build_payload(
    *,
    runtime: dict[str, Any],
    route_contract: dict[str, Any],
) -> dict[str, Any]:
    runtime_ready = runtime.get("status") == "stockplatform_public_api_runtime_ready"
    readback = _dict(runtime.get("readback"))
    rollups = _dict(runtime.get("rollups"))
    data_readiness_control_readback = _dict(
        runtime.get("data_readiness_control_readback")
    )
    source_contract_control_readback = _dict(
        runtime.get("source_contract_control_readback")
    )
    api_layer_classification = _classify_api_layer(readback, rollups, runtime_ready)
    data_dependency_classification = _data_dependency_classification(runtime)
    route_target_ready = route_contract.get("route_target_ready") is True
    recovery_required = not runtime_ready
    candidate_packaged = (
        recovery_required
        and api_layer_classification
        in {
            "edge_alive_api_upstream_unavailable",
            "api_live_data_dependency_not_ready",
        }
        and route_target_ready
    )
    active_blockers = _active_blockers(
        runtime=runtime,
        route_contract=route_contract,
        candidate_packaged=candidate_packaged,
        runtime_ready=runtime_ready,
    )
    status = _status(
        runtime_ready=runtime_ready,
        candidate_packaged=candidate_packaged,
        route_target_ready=route_target_ready,
        api_layer_classification=api_layer_classification,
    )

    return {
        "schema_version": _SCHEMA_VERSION,
        "priority": "P0-006",
        "scope": "stockplatform_public_api_controlled_recovery_preflight",
        "status": status,
        "safe_next_step": _safe_next_step(
            runtime_ready=runtime_ready,
            candidate_packaged=candidate_packaged,
            route_target_ready=route_target_ready,
            api_layer_classification=api_layer_classification,
            data_dependency_classification=data_dependency_classification,
        ),
        "active_blockers": active_blockers,
        "active_blocker_count": len(active_blockers),
        "api_layer_classification": api_layer_classification,
        "data_dependency_classification": data_dependency_classification,
        "runtime_readback_status": str(runtime.get("status") or "unknown"),
        "target_selector": {
            "product_id": "stockplatform-v2",
            "public_domain": "stock.wooo.work",
            "public_base_url": str(runtime.get("base_url") or ""),
            "edge_route_owner": "188 nginx public ingress source-of-truth",
            "runtime_host_role": "stockplatform container runtime host",
            "route_source_file": str(route_contract.get("route_source_file") or ""),
            "route_target": str(route_contract.get("route_target") or ""),
            "route_target_ready": route_target_ready,
            "required_public_endpoints": [
                "/healthz",
                "/api/healthz",
                "/api/v1/system/freshness",
                "/api/v1/system/ingestion",
            ],
        },
        "source_of_truth_diff": {
            "status": _source_of_truth_diff_status(
                runtime_ready=runtime_ready,
                route_target_ready=route_target_ready,
                api_layer_classification=api_layer_classification,
            ),
            "public_web_health_http_status": readback.get("web_health_http_status"),
            "public_api_health_http_status": readback.get("api_health_http_status"),
            "freshness_http_status": readback.get("freshness_http_status"),
            "ingestion_http_status": readback.get("ingestion_http_status"),
            "http_502_count": _int(rollups.get("http_502_count")),
            "data_dependency_classification": data_dependency_classification,
            "data_readiness_control_readback_status": (
                data_readiness_control_readback.get("status")
            ),
            "data_readiness_control_receipt_provided": (
                data_readiness_control_readback.get("receipt_provided") is True
            ),
            "source_contract_control_readback_status": (
                source_contract_control_readback.get("status")
            ),
            "source_contract_receipt_provided": (
                source_contract_control_readback.get("receipt_provided") is True
            ),
            "source_contract_non_ok_source_count": _int(
                source_contract_control_readback.get("non_ok_source_count")
            ),
            "source_contract_blocker_count": len(
                _strings(source_contract_control_readback.get("active_blockers"))
            ),
            "route_source_file": str(route_contract.get("route_source_file") or ""),
            "route_target": str(route_contract.get("route_target") or ""),
        },
        "data_readiness_control_readback": data_readiness_control_readback,
        "source_contract_control_readback": source_contract_control_readback,
        "controlled_apply_policy": {
            "risk_level": "high",
            "break_glass_required": False,
            "runtime_write_gate": "controlled_after_preflight",
            "controlled_recovery_candidate_packaged": candidate_packaged,
            "current_apply_allowed": False,
            "current_apply_blocker": _current_apply_blocker(
                runtime_ready=runtime_ready,
                candidate_packaged=candidate_packaged,
                api_layer_classification=api_layer_classification,
                data_dependency_classification=data_dependency_classification,
            ),
            "allowed_scope": _allowed_scope(
                api_layer_classification=api_layer_classification,
                data_dependency_classification=data_dependency_classification,
            ),
            "forbidden_scope": [
                "docker_daemon_restart",
                "host_reboot",
                "nginx_reload_or_restart",
                "database_write_restore_or_prune",
                "secret_value_read",
                "workflow_dispatch",
                "force_push_or_repo_ref_mutation",
            ],
        },
        "controlled_work_items": _controlled_work_items(
            candidate_packaged=candidate_packaged,
            runtime_ready=runtime_ready,
            api_layer_classification=api_layer_classification,
            data_dependency_classification=data_dependency_classification,
        ),
        "controlled_action_candidates": _controlled_action_candidates(
            candidate_packaged=candidate_packaged,
            runtime_ready=runtime_ready,
            api_layer_classification=api_layer_classification,
            data_dependency_classification=data_dependency_classification,
        ),
        "post_apply_verifiers": _post_apply_verifiers(runtime_ready=runtime_ready),
        "learning_writeback_contracts": _learning_writeback_contracts(),
        "rollups": {
            "runtime_ready": runtime_ready,
            "recovery_required": recovery_required,
            "route_target_ready": route_target_ready,
            "controlled_recovery_candidate_packaged": candidate_packaged,
            "controlled_recovery_preflight_ready": (
                runtime_ready or (candidate_packaged and not active_blockers)
            ),
            "host_control_path_readback_required": (
                candidate_packaged and not runtime_ready
            ),
            "controlled_work_item_count": len(
                _controlled_work_items(
                    candidate_packaged=candidate_packaged,
                    runtime_ready=runtime_ready,
                    api_layer_classification=api_layer_classification,
                    data_dependency_classification=data_dependency_classification,
                )
            ),
            "post_apply_verifier_count": len(
                _post_apply_verifiers(runtime_ready=runtime_ready)
            ),
            "learning_writeback_contract_count": len(_learning_writeback_contracts()),
            "postgres_readiness_or_data_source_readback_present": (
                data_readiness_control_readback.get("readback_present") is True
            ),
            "postgres_readiness_or_data_source_receipt_provided": (
                data_readiness_control_readback.get("receipt_provided") is True
            ),
            "source_contract_readback_present": (
                source_contract_control_readback.get("readback_present") is True
            ),
            "source_contract_receipt_provided": (
                source_contract_control_readback.get("receipt_provided") is True
            ),
            "source_contract_ready": (
                source_contract_control_readback.get("source_contract_ready") is True
            ),
            "source_contract_non_ok_source_count": _int(
                source_contract_control_readback.get("non_ok_source_count")
            ),
            "source_contract_blocker_count": len(
                _strings(source_contract_control_readback.get("active_blockers"))
            ),
        },
        "operation_boundaries": {
            "read_only_public_https_probe": True,
            "source_route_file_read": True,
            "ssh_used": False,
            "docker_command_performed": False,
            "docker_restart_performed": False,
            "docker_daemon_restart_performed": False,
            "host_reboot_performed": False,
            "nginx_reload_or_restart_performed": False,
            "database_write_or_restore_performed": False,
            "stockplatform_manual_data_write_performed": False,
            "secret_value_collection_allowed": False,
            "github_api_used": False,
            "workflow_trigger_performed": False,
            "runtime_write_allowed_by_this_readback": False,
        },
    }


def _load_route_contract(path: Path) -> dict[str, Any]:
    payload: dict[str, Any] = {
        "route_source_file": str(path),
        "route_target": "",
        "route_target_ready": False,
        "route_source_present": path.exists(),
    }
    if not path.exists():
        return payload

    text = path.read_text(encoding="utf-8")
    stock_section = _stock_section(text)
    targets = re.findall(r"proxy_pass\s+(http://[^;]+);", stock_section)
    unique_targets = _unique_strings(targets)
    payload["route_target"] = unique_targets[0] if unique_targets else ""
    payload["route_targets"] = unique_targets
    payload["route_target_ready"] = bool(
        "server_name stock.wooo.work;" in stock_section and unique_targets
    )
    return payload


def _stock_section(text: str) -> str:
    start = text.find("# Stock Platform")
    if start == -1:
        return text
    next_marker = text.find("\n# =============================================================================\n# ", start + 80)
    if next_marker == -1:
        return text[start:]
    return text[start:next_marker]


def _classify_api_layer(
    readback: dict[str, Any],
    rollups: dict[str, Any],
    runtime_ready: bool,
) -> str:
    if runtime_ready:
        return "public_api_ready"
    if (
        readback.get("web_health_http_status") == 200
        and readback.get("api_health_http_status") == 502
        and _int(rollups.get("http_502_count")) >= 1
    ):
        return "edge_alive_api_upstream_unavailable"
    if readback.get("api_health_http_status") == 200 and (
        readback.get("freshness_http_status") == 200
        or readback.get("ingestion_http_status") == 200
    ):
        return "api_live_data_dependency_not_ready"
    return "public_edge_or_route_unavailable"


def _data_dependency_classification(runtime: dict[str, Any]) -> str:
    runtime_rollups = _dict(runtime.get("rollups"))
    runtime_readback = _dict(runtime.get("readback"))
    live_classification = str(
        runtime_rollups.get("data_dependency_classification")
        or runtime_readback.get("data_dependency_classification")
        or ""
    )
    if live_classification and live_classification != "none":
        return live_classification
    blockers = _strings(runtime.get("active_blockers"))
    if runtime_readback.get("api_health_http_status") != 200:
        return "none"
    if (
        runtime_readback.get("postgres_not_ready") is True
        or any("postgres_not_ready" in blocker for blocker in blockers)
    ):
        return "postgres_not_ready"
    if any(
        blocker.startswith("stockplatform_freshness_")
        or blocker.startswith("stockplatform_ingestion_")
        for blocker in blockers
    ):
        return "freshness_or_ingestion_not_ready"
    return "none"


def _source_of_truth_diff_status(
    *,
    runtime_ready: bool,
    route_target_ready: bool,
    api_layer_classification: str,
) -> str:
    if runtime_ready:
        return "no_runtime_recovery_diff_required"
    if not route_target_ready:
        return "route_source_target_missing"
    if api_layer_classification == "edge_alive_api_upstream_unavailable":
        return "route_source_present_runtime_api_upstream_blocked"
    if api_layer_classification == "api_live_data_dependency_not_ready":
        return "route_source_present_api_live_data_dependency_not_ready"
    return "route_source_present_public_edge_or_route_reprobe_required"


def _active_blockers(
    *,
    runtime: dict[str, Any],
    route_contract: dict[str, Any],
    candidate_packaged: bool,
    runtime_ready: bool,
) -> list[str]:
    if runtime_ready:
        return []

    blockers = _strings(runtime.get("active_blockers"))
    if route_contract.get("route_target_ready") is not True:
        blockers.append("stockplatform_route_target_selector_missing")
    if candidate_packaged:
        blockers.append("stockplatform_110_control_path_readback_required")
    return _unique_strings(blockers)


def _current_apply_blocker(
    *,
    runtime_ready: bool,
    candidate_packaged: bool,
    api_layer_classification: str,
    data_dependency_classification: str,
) -> str:
    if runtime_ready:
        return ""
    if not candidate_packaged:
        return "route_or_public_edge_evidence_required"
    if data_dependency_classification == "postgres_not_ready":
        return (
            "postgres_readiness_and_production_migration_control_path_readback_"
            "required_before_apply"
        )
    if (
        data_dependency_classification
        == _AI_RECOMMENDATIONS_STALE_AFTER_CORE_RECOVERED
    ):
        return (
            "ai_recommendation_pipeline_readback_required_before_public_api_"
            "verifier"
        )
    if api_layer_classification == "api_live_data_dependency_not_ready":
        return (
            "data_dependency_control_path_readback_required_before_source_"
            "freshness_or_postgres_contract_apply"
        )
    return "host_control_path_readback_required_before_targeted_api_reconcile"


def _allowed_scope(
    *,
    api_layer_classification: str,
    data_dependency_classification: str,
) -> list[str]:
    common = [
        "public_api_post_apply_verifier",
        "km_rag_mcp_playbook_metadata_writeback",
    ]
    if api_layer_classification == "api_live_data_dependency_not_ready":
        if (
            data_dependency_classification
            == _AI_RECOMMENDATIONS_STALE_AFTER_CORE_RECOVERED
        ):
            return [
                "read_only_ai_recommendation_queue_status",
                "read_only_ai_recommendation_pipeline_receipt",
                *common,
            ]
        scope = [
            "read_only_data_dependency_status_inspection",
            "read_only_source_freshness_contract_diff",
            "read_only_postgres_connection_contract_readback",
            *common,
        ]
        if data_dependency_classification == "postgres_not_ready":
            return [
                *scope,
                "controlled_production_migration_path_after_dry_run",
            ]
        return [
            *scope,
            "controlled_metadata_or_config_contract_apply_after_dry_run",
        ]
    return [
        "read_only_container_status_inspection",
        "read_only_redacted_api_log_tail",
        "targeted_api_container_reconcile_after_failed_health_check",
        *common,
    ]


def _status(
    *,
    runtime_ready: bool,
    candidate_packaged: bool,
    route_target_ready: bool,
    api_layer_classification: str,
) -> str:
    if runtime_ready:
        return "stockplatform_public_api_recovery_preflight_not_required"
    if (
        candidate_packaged
        and api_layer_classification == "api_live_data_dependency_not_ready"
    ):
        return "controlled_data_dependency_preflight_packaged_waiting_control_path_readback"
    if candidate_packaged:
        return "controlled_recovery_preflight_packaged_waiting_control_path_readback"
    if route_target_ready:
        return "blocked_public_edge_or_route_symptom_requires_reprobe"
    return "blocked_route_target_selector_missing"


def _safe_next_step(
    *,
    runtime_ready: bool,
    candidate_packaged: bool,
    route_target_ready: bool,
    api_layer_classification: str,
    data_dependency_classification: str,
) -> str:
    if runtime_ready:
        return "stockplatform_public_api_ready_keep_p0_006_reboot_window_gate"
    if (
        candidate_packaged
        and api_layer_classification == "api_live_data_dependency_not_ready"
    ):
        if (
            data_dependency_classification
            == _AI_RECOMMENDATIONS_STALE_AFTER_CORE_RECOVERED
        ):
            return (
                "run_stockplatform_ai_recommendation_pipeline_readback_then_"
                "public_api_verifier"
            )
        if data_dependency_classification != "postgres_not_ready":
            return (
                "run_stockplatform_data_dependency_source_contract_readback_"
                "then_public_api_verifier"
            )
        return (
            "run_stockplatform_production_migration_path_after_control_channel_"
            "readback_then_public_api_verifier"
        )
    if candidate_packaged:
        return (
            "restore_stockplatform_110_control_path_readback_then_run_read_only_"
            "container_inspection_and_targeted_api_reconcile_with_public_verifier"
        )
    if route_target_ready:
        return "rerun_public_api_readback_and_188_to_110_upstream_probe_before_apply"
    return "repair_source_route_target_selector_before_any_runtime_recovery"


def _controlled_work_items(
    *,
    candidate_packaged: bool,
    runtime_ready: bool,
    api_layer_classification: str,
    data_dependency_classification: str,
) -> list[dict[str, Any]]:
    if runtime_ready:
        return []
    base_status = "queued_waiting_control_path_readback" if candidate_packaged else "blocked_waiting_route_evidence"
    if api_layer_classification == "api_live_data_dependency_not_ready":
        if (
            data_dependency_classification
            == _AI_RECOMMENDATIONS_STALE_AFTER_CORE_RECOVERED
        ):
            return [
                {
                    "id": "stockplatform-ai-recommendation-control-path-readback",
                    "title": "StockPlatform AI recommendation control path readback",
                    "owner_agent": "DevOps Agent",
                    "status": base_status,
                    "required_output": "non_secret_pipeline_liveness_and_runtime_contract_match",
                },
                {
                    "id": "stockplatform-ai-recommendation-queue-inspection",
                    "title": "Read-only AI recommendation queue inspection",
                    "owner_agent": "SRE Agent",
                    "status": "waiting_control_path_readback",
                    "required_output": "ai_recommendations_latest_date_and_queue_receipt",
                },
                {
                    "id": "stockplatform-ai-recommendation-pipeline-preflight",
                    "title": "AI recommendation pipeline verifier preflight",
                    "owner_agent": "Data Reliability Agent",
                    "status": "waiting_read_only_inspection",
                    "required_output": "dry_run_pipeline_receipt_no_manual_db_write",
                },
                {
                    "id": "stockplatform-api-post-apply-verifier",
                    "title": "Public API post-apply verifier",
                    "owner_agent": "Verifier Agent",
                    "status": "ready",
                    "required_output": "public_health_freshness_ingestion_green",
                },
                {
                    "id": "stockplatform-ai-learning-writeback",
                    "title": "KM / RAG / MCP / PlayBook trust writeback",
                    "owner_agent": "Learning Agent",
                    "status": "ready",
                    "required_output": "metadata_only_ai_pipeline_receipt_and_trust_delta",
                },
            ]
        contract_title = "Source freshness and Postgres contract preflight"
        contract_output = "dry_run_contract_diff_no_db_write"
        if data_dependency_classification == "postgres_not_ready":
            contract_title = "Production migration path and Postgres readiness preflight"
            contract_output = (
                "dry_run_migration_plan_and_postgres_readiness_receipt"
            )
        return [
            {
                "id": "stockplatform-data-control-path-readback",
                "title": "StockPlatform data dependency control path readback",
                "owner_agent": "DevOps Agent",
                "status": base_status,
                "required_output": "non_secret_host_liveness_and_runtime_contract_match",
            },
            {
                "id": "stockplatform-data-dependency-inspection",
                "title": "Read-only freshness / ingestion dependency inspection",
                "owner_agent": "SRE Agent",
                "status": "waiting_control_path_readback",
                "required_output": "freshness_ingestion_source_and_postgres_contract_status",
            },
            {
                "id": "stockplatform-data-contract-preflight",
                "title": contract_title,
                "owner_agent": "Data Reliability Agent",
                "status": "waiting_read_only_inspection",
                "required_output": contract_output,
            },
            {
                "id": "stockplatform-api-post-apply-verifier",
                "title": "Public API post-apply verifier",
                "owner_agent": "Verifier Agent",
                "status": "ready",
                "required_output": "public_health_freshness_ingestion_green",
            },
            {
                "id": "stockplatform-data-learning-writeback",
                "title": "KM / RAG / MCP / PlayBook trust writeback",
                "owner_agent": "Learning Agent",
                "status": "ready",
                "required_output": "metadata_only_data_dependency_receipt_and_trust_delta",
            },
        ]
    return [
        {
            "id": "stockplatform-api-control-path-readback",
            "title": "StockPlatform host control path readback",
            "owner_agent": "DevOps Agent",
            "status": base_status,
            "required_output": "non_secret_host_liveness_and_compose_project_match",
        },
        {
            "id": "stockplatform-api-runtime-inspection",
            "title": "Read-only API container status inspection",
            "owner_agent": "SRE Agent",
            "status": "waiting_control_path_readback",
            "required_output": "api_container_state_and_redacted_health_log_tail",
        },
        {
            "id": "stockplatform-api-targeted-reconcile",
            "title": "Targeted API container reconcile",
            "owner_agent": "DevOps Agent",
            "status": "waiting_read_only_inspection",
            "required_output": "bounded_api_reconcile_receipt_no_daemon_restart",
        },
        {
            "id": "stockplatform-api-post-apply-verifier",
            "title": "Public API post-apply verifier",
            "owner_agent": "Verifier Agent",
            "status": "ready",
            "required_output": "public_health_freshness_ingestion_green",
        },
        {
            "id": "stockplatform-api-learning-writeback",
            "title": "KM / RAG / MCP / PlayBook trust writeback",
            "owner_agent": "Learning Agent",
            "status": "ready",
            "required_output": "metadata_only_recovery_receipt_and_trust_delta",
        },
    ]


def _controlled_action_candidates(
    *,
    candidate_packaged: bool,
    runtime_ready: bool,
    api_layer_classification: str,
    data_dependency_classification: str,
) -> list[dict[str, Any]]:
    if runtime_ready:
        return []
    if api_layer_classification == "api_live_data_dependency_not_ready":
        if (
            data_dependency_classification
            == _AI_RECOMMENDATIONS_STALE_AFTER_CORE_RECOVERED
        ):
            return [
                {
                    "id": "read_only_ai_recommendation_pipeline_readback",
                    "execution_route": "stockplatform_ai_recommendation_executor",
                    "current_status": (
                        "queued_waiting_control_path_readback"
                        if candidate_packaged
                        else "blocked_waiting_route_evidence"
                    ),
                    "check_mode": "read_only_ai_recommendation_queue_and_pipeline_receipt",
                    "apply_allowed_when": [
                        "host_control_path_liveness_readback_ok",
                        "stockplatform_api_health_ok",
                        "core_freshness_and_ingestion_ok",
                        "post_apply_public_verifier_ready",
                    ],
                    "forbidden_actions": [
                        "secret_read",
                        "docker_daemon_restart",
                        "host_reboot",
                        "database_write",
                        "fake_freshness_marker",
                    ],
                },
                {
                    "id": "ai_recommendation_pipeline_verifier_preflight",
                    "execution_route": "stockplatform_ai_recommendation_executor",
                    "current_status": "waiting_read_only_pipeline_readback",
                    "check_mode": "dry_run_ai_recommendation_pipeline_contract",
                    "bounded_apply": (
                        "use the existing AI recommendation pipeline path only "
                        "after control-channel readback and dry-run; no manual "
                        "DB rows, no fake freshness marker, no destructive restore"
                    ),
                },
            ]
        second_candidate = {
            "id": "source_freshness_contract_preflight",
            "execution_route": "stockplatform_data_contract_executor",
            "current_status": "waiting_read_only_data_dependency_inspection",
            "check_mode": "dry_run_source_and_runtime_contract_diff",
            "bounded_apply": (
                "apply only metadata/config contract repair after dry-run; "
                "no DB write, no fake freshness marker, no destructive restore"
            ),
        }
        if data_dependency_classification == "postgres_not_ready":
            second_candidate = {
                "id": "production_migration_path_preflight",
                "execution_route": "stockplatform_production_deploy_executor",
                "current_status": "waiting_read_only_postgres_contract_readback",
                "check_mode": "dry_run_migration_path_and_runtime_contract_diff",
                "bounded_apply": (
                    "run the existing production migration path only after "
                    "control-channel readback and dry-run; no manual DB rows, "
                    "no fake freshness marker, no destructive restore"
                ),
            }
        return [
            {
                "id": "read_only_data_dependency_inspection",
                "execution_route": "stockplatform_host_controlled_runtime_executor",
                "current_status": (
                    "queued_waiting_control_path_readback"
                    if candidate_packaged
                    else "blocked_waiting_route_evidence"
                ),
                "check_mode": "read_only_freshness_ingestion_and_postgres_contract",
                "apply_allowed_when": [
                    "host_control_path_liveness_readback_ok",
                    "stockplatform_api_health_ok",
                    "source_freshness_contract_diff_present",
                    "post_apply_public_verifier_ready",
                ],
                "forbidden_actions": [
                    "secret_read",
                    "docker_daemon_restart",
                    "host_reboot",
                    "database_write",
                    "fake_freshness_marker",
                ],
            },
            second_candidate,
        ]
    return [
        {
            "id": "read_only_container_inspection",
            "execution_route": "stockplatform_host_controlled_runtime_executor",
            "current_status": (
                "queued_waiting_control_path_readback"
                if candidate_packaged
                else "blocked_waiting_route_evidence"
            ),
            "check_mode": "read_only_status_and_redacted_logs",
            "apply_allowed_when": [
                "host_control_path_liveness_readback_ok",
                "compose_project_or_container_target_matches_stockplatform_api",
                "secret_scrubber_enabled_for_log_tail",
            ],
            "forbidden_actions": [
                "secret_read",
                "docker_daemon_restart",
                "host_reboot",
                "database_write",
            ],
        },
        {
            "id": "targeted_api_container_reconcile",
            "execution_route": "stockplatform_host_controlled_runtime_executor",
            "current_status": "waiting_read_only_container_inspection",
            "check_mode": "dry_run_target_selector_and_current_state_diff",
            "apply_allowed_when": [
                "api_container_missing_exited_or_unhealthy",
                "current_image_and_compose_source_match_expected_runtime",
                "post_apply_public_verifier_ready",
                "rollback_receipt_path_ready",
            ],
            "bounded_apply": (
                "reconcile only the StockPlatform API container/service target; "
                "no Docker daemon restart, no host reboot, no DB write"
            ),
        },
    ]


def _post_apply_verifiers(*, runtime_ready: bool) -> list[dict[str, Any]]:
    if runtime_ready:
        return []
    return [
        {
            "id": "stockplatform_public_healthz",
            "url": "https://stock.wooo.work/api/healthz",
            "expected_http_status": 200,
        },
        {
            "id": "stockplatform_freshness",
            "url": "https://stock.wooo.work/api/v1/system/freshness",
            "expected_status": "ok",
        },
        {
            "id": "stockplatform_ingestion",
            "url": "https://stock.wooo.work/api/v1/system/ingestion",
            "expected_status": "ok",
        },
        {
            "id": "awoooi_priority_work_order_readback",
            "url": "/api/v1/agents/awoooi-priority-work-order-readback",
            "expected_rollup": "stockplatform_public_api_runtime_ready=true",
        },
    ]


def _learning_writeback_contracts() -> list[dict[str, Any]]:
    targets = [
        "timeline_event",
        "knowledge_entry",
        "rag_embedding",
        "mcp_tool_registry_signal",
        "playbook_trust_score",
        "controlled_recovery_report",
    ]
    return [
        {
            "target": target,
            "writeback_mode": "metadata_only",
            "raw_log_allowed": False,
            "secret_value_allowed": False,
            "receipt_key": f"stockplatform_public_api_recovery::{target}",
        }
        for target in targets
    ]


def _dict(value: Any) -> dict[str, Any]:
    return value if isinstance(value, dict) else {}


def _int(value: Any) -> int:
    try:
        return int(str(value))
    except (TypeError, ValueError):
        return 0


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


def _unique_strings(values: list[str]) -> list[str]:
    seen: set[str] = set()
    unique: list[str] = []
    for value in values:
        if value in seen:
            continue
        seen.add(value)
        unique.append(value)
    return unique
