from __future__ import annotations

from fastapi import FastAPI
from fastapi.testclient import TestClient

from src.api.v1.agents import router
from src.services.harbor_registry_controlled_recovery_receipt import (
    validate_harbor_registry_controlled_recovery_receipt,
)


def test_harbor_recovery_receipt_accepts_verified_repair() -> None:
    payload = validate_harbor_registry_controlled_recovery_receipt(
        {
            "ssh_local_repair_output": _ssh_local_apply_output(),
            "watchdog_check_output": _watchdog_check_output(ready=False, status=502),
            "watchdog_repair_output": _watchdog_check_output(ready=True, status=401),
            "public_registry_v2_http_status": 401,
            "internal_registry_v2_http_status": 401,
            "deploy_marker_readback": _deploy_marker_verified(),
        }
    )

    assert payload["schema_version"] == (
        "harbor_registry_controlled_recovery_receipt_v1"
    )
    assert payload["status"] == "harbor_registry_recovery_receipt_verified"
    assert payload["accepted"] is True
    assert payload["active_blockers"] == []
    assert payload["readback"]["ssh_local_repair"][
        "control_channel_metadata_ready"
    ] is True
    assert payload["readback"]["ssh_local_repair"]["account_metadata_ready"] is True
    assert payload["readback"]["ssh_local_repair"]["target_user_account_locked"] is False
    assert payload["readback"]["ssh_local_repair"]["target_user_shell_executable"] is True
    assert payload["readback"]["ssh_local_repair"]["sshd_pubkeyauthentication"] == "yes"
    assert (
        payload["readback"]["ssh_local_repair"][
            "sshd_authorized_keys_file_default"
        ]
        is True
    )
    assert payload["readback"]["watchdog_repair"]["harbor_ready"] is True
    assert payload["readback"]["post_apply_verifier"]["registry_v2_ready"] is True
    assert payload["readback"]["deploy_marker"]["deploy_marker_verified"] is True
    assert payload["readback"]["deploy_marker"]["raw_output_returned"] is False
    phase_readback = payload["local_console_phase_readback"]
    assert phase_readback["phase_count"] == 6
    assert phase_readback["completed_phase_count"] == 6
    assert phase_readback["blocked_phase_count"] == 0
    assert phase_readback["phase_ids"] == [
        "diagnose_ssh_publickey",
        "preflight_control_path_and_harbor",
        "repair_ssh_metadata_if_check_confirms_metadata_drift",
        "repair_harbor_once_if_v2_still_502",
        "verify_controlled_cd_lane",
        "verify_non110_runner_lane",
    ]
    assert all(phase["raw_output_returned"] is False for phase in phase_readback["phases"])
    assert payload["rollups"]["local_console_phase_count"] == 6
    assert payload["rollups"]["local_console_completed_phase_count"] == 6
    assert payload["rollups"]["local_console_blocked_phase_count"] == 0
    assert payload["rollups"]["deploy_marker_readback_seen"] is True
    assert payload["rollups"]["deploy_marker_verified"] is True
    assert payload["input_redaction"]["raw_output_returned"] is False
    assert payload["input_redaction"]["deploy_marker_readback"] == {
        "provided": True,
        "metadata_only": True,
        "raw_output_returned": False,
    }
    assert payload["operation_boundaries"]["ssh_used"] is False
    assert payload["operation_boundaries"]["docker_command_performed"] is False
    assert payload["operation_boundaries"]["host_reboot_performed"] is False
    assert payload["operation_boundaries"]["workflow_trigger_performed"] is False
    assert payload["learning_writeback_contracts"][0]["raw_log_allowed"] is False


def test_harbor_recovery_receipt_surfaces_ssh_local_metadata_blockers() -> None:
    ssh_local_output = (
        _ssh_local_apply_output()
        .replace(
            "account_locked=false shell=/bin/bash shell_exists=true shell_executable=true",
            "account_locked=true shell=/bin/false shell_exists=true shell_executable=false",
        )
        .replace(
            "AUTHORIZED_KEYS_STATUS path=/home/wooo/.ssh/authorized_keys exists=1 bytes=380 lines=1",
            "AUTHORIZED_KEYS_STATUS path=/home/wooo/.ssh/authorized_keys exists=0",
        )
        .replace(
            "pubkeyauthentication=yes passwordauthentication=no "
            "kbdinteractiveauthentication=no usepam=yes maxstartups=10:30:100 "
            "authorized_keys_file_default=true",
            "pubkeyauthentication=no passwordauthentication=no "
            "kbdinteractiveauthentication=no usepam=yes maxstartups=10:30:100 "
            "authorized_keys_file_default=false",
        )
    )

    payload = validate_harbor_registry_controlled_recovery_receipt(
        {"ssh_local_repair_output": ssh_local_output}
    )

    assert payload["status"] == (
        "ssh_local_repair_receipt_waiting_harbor_watchdog_check"
    )
    assert "ssh_local_repair_target_user_account_locked" in payload[
        "active_blockers"
    ]
    assert "ssh_local_repair_target_user_shell_not_executable" in payload[
        "active_blockers"
    ]
    assert "ssh_local_repair_authorized_keys_missing" in payload["active_blockers"]
    assert "ssh_local_repair_sshd_pubkeyauthentication_not_enabled" in payload[
        "active_blockers"
    ]
    assert "ssh_local_repair_sshd_authorized_keys_file_drift" in payload[
        "active_blockers"
    ]
    assert "ssh_local_repair_receipt_metadata_not_ready" in payload[
        "active_blockers"
    ]
    ssh_local = payload["readback"]["ssh_local_repair"]
    assert ssh_local["control_channel_metadata_ready"] is False
    assert ssh_local["account_metadata_ready"] is False
    assert ssh_local["target_user_account_locked"] is True
    assert ssh_local["target_user_shell_executable"] is False
    assert ssh_local["authorized_keys_metadata_present"] is False
    assert ssh_local["sshd_pubkeyauthentication"] == "no"
    assert ssh_local["sshd_passwordauthentication"] == "no"
    assert ssh_local["sshd_kbdinteractiveauthentication"] == "no"
    assert ssh_local["sshd_maxstartups"] == "10:30:100"
    assert ssh_local["sshd_authorized_keys_file_default"] is False
    assert payload["rollups"]["ssh_local_repair_account_metadata_ready"] is False
    assert (
        payload["rollups"]["ssh_local_repair_target_user_account_locked"] is True
    )
    assert (
        payload["rollups"]["ssh_local_repair_target_user_shell_executable"]
        is False
    )
    assert payload["rollups"]["ssh_local_repair_sshd_pubkeyauthentication"] == "no"
    assert (
        payload["rollups"]["ssh_local_repair_sshd_authorized_keys_file_default"]
        is False
    )
    assert payload["input_redaction"]["ssh_local_repair_output"]["line_count"] > 0
    assert "secret-token-like-content" not in str(payload)


def test_harbor_recovery_receipt_accepts_nonroot_sshd_syntax_unverified_check() -> None:
    ssh_local_output = _ssh_local_apply_output().replace(
        "SSHD_CONFIG_SYNTAX=ok",
        (
            "SSHD_CONFIG_SYNTAX=unverified_requires_root rc=1 "
            "reason=hostkeys_unavailable_or_permission"
        ),
    )

    payload = validate_harbor_registry_controlled_recovery_receipt(
        {"ssh_local_repair_output": ssh_local_output}
    )

    ssh_local = payload["readback"]["ssh_local_repair"]
    assert ssh_local["sshd_config_syntax_ok"] is True
    assert ssh_local["sshd_config_syntax_unverified_requires_root"] is True
    assert ssh_local["control_channel_metadata_ready"] is True
    assert "ssh_local_repair_sshd_config_syntax_not_ok" not in payload[
        "active_blockers"
    ]


def test_harbor_recovery_receipt_accepts_combined_local_console_output() -> None:
    payload = validate_harbor_registry_controlled_recovery_receipt(
        {
            "local_console_recovery_output": "\n".join(
                [
                    "AWOOOI_110_CONTROL_PATH_AND_HARBOR_LOCAL_RECOVERY mode=check requested_mode=--check target_user=wooo",
                    "operation_boundary_secret_value_read=false",
                    "operation_boundary_docker_daemon_restart_performed=false",
                    _ssh_local_apply_output(),
                ]
            )
        }
    )

    assert payload["status"] == (
        "ssh_local_repair_receipt_waiting_harbor_watchdog_check"
    )
    assert payload["readback"]["ssh_local_repair"]["receipt_seen"] is True
    assert payload["readback"]["ssh_local_repair"][
        "control_channel_metadata_ready"
    ] is True
    assert payload["input_redaction"]["ssh_local_repair_output"]["provided"] is False
    assert payload["input_redaction"]["local_console_recovery_output"][
        "provided"
    ] is True
    assert payload["input_redaction"]["raw_output_returned"] is False


def test_harbor_recovery_receipt_routes_unhealthy_check_to_repair_once() -> None:
    payload = validate_harbor_registry_controlled_recovery_receipt(
        {
            "watchdog_check_output": _watchdog_check_output(
                ready=False,
                status=502,
            ),
            "public_registry_v2_http_status": 502,
            "internal_registry_v2_http_status": 502,
        }
    )

    assert payload["status"] == (
        "harbor_watchdog_check_unhealthy_waiting_repair_once_receipt"
    )
    assert "harbor_watchdog_repair_once_receipt_missing" in payload[
        "active_blockers"
    ]
    assert payload["safe_next_step"] == (
        "run_harbor_watchdog_repair_once_then_submit_receipt_with_verifier"
    )
    phases = {
        phase["phase_id"]: phase
        for phase in payload["local_console_phase_readback"]["phases"]
    }
    assert phases["diagnose_ssh_publickey"]["status"] == (
        "blocked_waiting_ssh_publickey_diagnosis_receipt"
    )
    assert phases["preflight_control_path_and_harbor"]["status"] == "ready"
    assert phases["repair_ssh_metadata_if_check_confirms_metadata_drift"][
        "status"
    ] == "skipped_not_required"
    assert phases["repair_harbor_once_if_v2_still_502"]["status"] == (
        "blocked_waiting_harbor_repair_once_receipt"
    )
    assert payload["rollups"]["local_console_blocked_phase_count"] == 4
    assert payload["controlled_apply_policy"]["manual_end_state"] is False


def test_harbor_recovery_receipt_accepts_ssh_publickey_diagnosis() -> None:
    payload = validate_harbor_registry_controlled_recovery_receipt(
        {
            "ssh_publickey_diagnosis_output": _ssh_publickey_diagnosis_output(),
        }
    )

    assert payload["status"] == (
        "ssh_publickey_diagnosis_receipt_waiting_110_local_repair_or_harbor_watchdog_check"
    )
    assert payload["safe_next_step"] == (
        "run_110_local_ssh_metadata_check_then_harbor_watchdog_check_mode"
    )
    assert "ssh_publickey_server_accepts_key_then_timeout_on_wooo" in payload[
        "active_blockers"
    ]
    assert "runner_systemctl_show_timeout_on_110" in payload["active_blockers"]
    diagnosis = payload["readback"]["ssh_publickey_diagnosis"]
    assert diagnosis["diagnosis_ready"] is True
    assert diagnosis["node_exporter_ok"] is True
    assert diagnosis["ssh_port_tcp_open"] is True
    assert diagnosis["ssh_banner_seen"] is True
    assert diagnosis["wooo_publickey_classification"] == (
        "server_accepts_key_then_timeout"
    )
    assert diagnosis["server_accepts_key_then_timeout_seen"] is True
    assert diagnosis["runner_systemctl_show_timeout_seen"] is True
    assert diagnosis["node_load_classifier"] == "load_not_high"
    assert diagnosis["node_high_load_seen"] is False
    assert diagnosis["systemd_unit_signals"][0]["classifier"] == (
        "systemctl_show_timeout"
    )
    assert diagnosis["raw_output_returned"] is False
    phases = {
        phase["phase_id"]: phase
        for phase in payload["local_console_phase_readback"]["phases"]
    }
    assert phases["diagnose_ssh_publickey"]["status"] == "ready"
    assert phases["repair_ssh_metadata_if_check_confirms_metadata_drift"][
        "status"
    ] == "blocked_waiting_110_local_session_path_diagnosis_after_key_accept_timeout"
    assert payload["rollups"]["ssh_publickey_diagnosis_receipt_seen"] is True
    assert payload["rollups"]["ssh_publickey_wooo_publickey_classification"] == (
        "server_accepts_key_then_timeout"
    )
    assert (
        payload["rollups"]["ssh_publickey_runner_systemctl_show_timeout_seen"]
        is True
    )
    assert payload["rollups"]["ssh_publickey_node_high_load_seen"] is False
    assert (
        payload["rollups"]["ssh_publickey_node_load_classifier"]
        == "load_not_high"
    )
    assert payload["rollups"]["ssh_publickey_node_load1_per_cpu"] == 0.93
    assert payload["input_redaction"]["ssh_publickey_diagnosis_output"][
        "line_count"
    ] > 0


def test_harbor_recovery_receipt_command_path_ready_overrides_stale_timeout() -> None:
    payload = validate_harbor_registry_controlled_recovery_receipt(
        {
            "ssh_publickey_diagnosis_output": _ssh_publickey_command_path_ready_output(),
            "watchdog_check_output": _watchdog_check_output(ready=True, status=401),
            "public_registry_v2_http_status": 401,
            "internal_registry_v2_http_status": 401,
        }
    )

    assert payload["status"] == "harbor_registry_recovery_receipt_verified"
    assert payload["active_blockers"] == []
    diagnosis = payload["readback"]["ssh_publickey_diagnosis"]
    assert diagnosis["wooo_command_path_ready"] is True
    assert diagnosis["wooo_command_path_classification"] == "command_path_ready"
    assert diagnosis["server_accepts_key_then_timeout_seen"] is True
    assert diagnosis["server_accepts_key_then_timeout_effective_seen"] is False
    assert diagnosis["runner_systemctl_show_timeout_seen"] is True
    assert diagnosis["runner_systemctl_show_timeout_effective_seen"] is False
    readiness = payload["readback"]["control_path_readiness"]
    assert readiness["status"] == "ready"
    assert readiness["ssh_command_path_ready"] is True
    assert readiness["ssh_server_accepts_key_then_timeout_raw"] is True
    assert readiness["ssh_server_accepts_key_then_timeout"] is False
    assert readiness["runner_systemctl_show_timeout_raw"] is True
    assert readiness["runner_systemctl_show_timeout"] is False
    phases = {
        phase["phase_id"]: phase
        for phase in payload["local_console_phase_readback"]["phases"]
    }
    assert phases["repair_ssh_metadata_if_check_confirms_metadata_drift"][
        "status"
    ] == "skipped_not_required"
    assert payload["rollups"]["ssh_publickey_wooo_command_path_ready"] is True
    assert (
        payload["rollups"][
            "ssh_publickey_server_accepts_key_then_timeout_effective_seen"
        ]
        is False
    )


def test_harbor_recovery_receipt_local_receipt_supersedes_stale_gitea_queue() -> None:
    payload = validate_harbor_registry_controlled_recovery_receipt(
        {
            "ssh_publickey_diagnosis_output": _ssh_publickey_command_path_ready_output(),
            "local_console_recovery_output": "\n".join(
                [
                    _watchdog_check_output(ready=True, status=401),
                    _controlled_cd_lane_blocked_output(),
                ]
            ),
            "public_registry_v2_http_status": 401,
            "internal_registry_v2_http_status": 401,
            "gitea_actions_queue_readback": _gitea_queue_remote_control_timeout(),
        }
    )

    assert payload["status"] == "controlled_cd_lane_readiness_receipt_blocked"
    assert payload["safe_next_step"] == (
        "fix_controlled_cd_lane_guardrail_blockers_then_rerun_readiness_verifier"
    )
    assert "controlled_cd_lane_readiness:controlled_cd_lane_registration_missing" in (
        payload["active_blockers"]
    )
    assert "controlled_cd_lane_readiness:controlled_cd_lane_service_not_active" in (
        payload["active_blockers"]
    )
    assert not any(
        blocker.startswith("gitea_queue_harbor_110")
        for blocker in payload["active_blockers"]
    )
    assert not any(
        blocker.startswith("non110_runner_readiness:")
        for blocker in payload["active_blockers"]
    )
    assert payload["readback"]["non110_runner_readiness"]["receipt_seen"] is False
    queue = payload["readback"]["gitea_actions_queue"]
    assert queue["harbor_110_repair_remote_control_channel_unavailable"] is True
    assert queue["blocker_count"] == 2
    readiness = payload["readback"]["control_path_readiness"]
    assert readiness["status"] == "ready"
    assert readiness["ssh_command_path_ready"] is True
    assert readiness["harbor_110_repair_remote_control_channel_unavailable"] is False
    assert (
        readiness["harbor_110_repair_remote_control_channel_unavailable_raw"]
        is True
    )
    assert readiness["harbor_110_repair_jobs_stale_or_mismatched"] is False
    assert not any(
        signal.startswith("gitea_queue_harbor_110")
        for signal in readiness["signal_ids"]
    )
    assert payload["rollups"]["gitea_queue_blocker_count"] == 2
    assert (
        payload["rollups"][
            "gitea_queue_harbor_110_remote_control_channel_unavailable"
        ]
        is True
    )


def test_harbor_recovery_receipt_classifies_publickey_offer_timeout() -> None:
    diagnosis_output = _ssh_publickey_diagnosis_output().replace(
        "rc=124 classification=server_accepts_key_then_timeout",
        "rc=255 classification=publickey_offer_timeout",
    ).replace(
        "NODE_LOAD1_PER_CPU=0.93",
        "NODE_LOAD1_PER_CPU=1.87",
    ).replace(
        "NODE_LOAD_CLASSIFIER=load_not_high",
        "NODE_LOAD_CLASSIFIER=high_load",
    )

    payload = validate_harbor_registry_controlled_recovery_receipt(
        {
            "ssh_publickey_diagnosis_output": diagnosis_output,
        }
    )

    assert "ssh_publickey_offer_timeout_on_wooo" in payload["active_blockers"]
    assert "ssh_publickey_node_high_load_on_110" in payload["active_blockers"]
    diagnosis = payload["readback"]["ssh_publickey_diagnosis"]
    assert diagnosis["wooo_publickey_classification"] == "publickey_offer_timeout"
    assert diagnosis["publickey_offer_timeout_seen"] is True
    assert diagnosis["node_high_load_seen"] is True
    assert diagnosis["node_load1_per_cpu"] == 1.87
    assert payload["rollups"]["ssh_publickey_node_high_load_seen"] is True
    phases = {
        phase["phase_id"]: phase
        for phase in payload["local_console_phase_readback"]["phases"]
    }
    assert phases["repair_ssh_metadata_if_check_confirms_metadata_drift"][
        "status"
    ] == "blocked_waiting_ssh_metadata_repair_receipt_after_publickey_timeout"


def test_harbor_recovery_receipt_classifies_110_high_load() -> None:
    diagnosis_output = _ssh_publickey_diagnosis_output().replace(
        "NODE_LOAD_CLASSIFIER=load_not_high",
        "NODE_LOAD_CLASSIFIER=high_load",
    )

    payload = validate_harbor_registry_controlled_recovery_receipt(
        {
            "ssh_publickey_diagnosis_output": diagnosis_output,
        }
    )

    assert "ssh_publickey_node_high_load_on_110" in payload["active_blockers"]
    diagnosis = payload["readback"]["ssh_publickey_diagnosis"]
    assert diagnosis["node_load_classifier"] == "high_load"
    assert diagnosis["node_high_load_seen"] is True
    phases = {
        phase["phase_id"]: phase
        for phase in payload["local_console_phase_readback"]["phases"]
    }
    assert phases["preflight_control_path_and_harbor"]["status"] == (
        "blocked_waiting_110_load_to_normalize_before_harbor_preflight"
    )
    assert payload["rollups"]["ssh_publickey_node_load_classifier"] == "high_load"
    assert payload["rollups"]["ssh_publickey_node_high_load_seen"] is True


def test_harbor_recovery_receipt_surfaces_controlled_cd_lane_readiness() -> None:
    payload = validate_harbor_registry_controlled_recovery_receipt(
        {
            "controlled_cd_lane_readiness_output": _controlled_cd_lane_blocked_output(),
        }
    )

    assert payload["status"] == "controlled_cd_lane_readiness_receipt_blocked"
    assert payload["safe_next_step"] == (
        "fix_controlled_cd_lane_guardrail_blockers_then_rerun_readiness_verifier"
    )
    assert "controlled_cd_lane_readiness:controlled_cd_lane_service_not_active" in payload[
        "active_blockers"
    ]
    assert "controlled_cd_lane_readiness:controlled_cd_lane_registration_missing" in payload[
        "active_blockers"
    ]
    lane = payload["readback"]["controlled_cd_lane_readiness"]
    assert lane["receipt_seen"] is True
    assert lane["controlled_cd_lane_ready"] is False
    assert lane["registration_ready"] is False
    assert lane["service_ready"] is False
    assert lane["blocker_count"] == 2
    assert lane["safe_next_step"] == (
        "restore_or_register_awoooi_cd_lane_drain_registration_without_printing_token_then_rerun_this_verifier"
    )
    assert lane["raw_output_returned"] is False
    assert "secret-token-like-content" not in str(lane)
    phases = {
        phase["phase_id"]: phase
        for phase in payload["local_console_phase_readback"]["phases"]
    }
    assert phases["verify_controlled_cd_lane"]["status"] == (
        "blocked_controlled_cd_lane_readiness_receipt_not_ready"
    )
    assert payload["rollups"]["controlled_cd_lane_readiness_receipt_seen"] is True
    assert payload["rollups"]["controlled_cd_lane_ready"] is False
    assert payload["rollups"]["controlled_cd_lane_blocker_count"] == 2
    assert payload["input_redaction"]["controlled_cd_lane_readiness_output"][
        "line_count"
    ] > 0


def test_harbor_recovery_receipt_blocks_controlled_cd_lane_blocker_count() -> None:
    payload = validate_harbor_registry_controlled_recovery_receipt(
        {
            "controlled_cd_lane_readiness_output": """
AWOOOI_110_CONTROLLED_CD_LANE_READY=1
CONFIG_READY=1
BINARY_READY=1
REGISTRATION_READY=1
SERVICE_READY=1
LEGACY_FAILCLOSED=1
PRIMARY_LANE_FAILCLOSED=1
WARNING_COUNT=0
BLOCKER_COUNT=1
""",
        }
    )

    assert payload["status"] == "controlled_cd_lane_readiness_receipt_blocked"
    assert payload["readback"]["controlled_cd_lane_readiness"][
        "controlled_cd_lane_ready"
    ] is False
    assert payload["rollups"]["controlled_cd_lane_blocker_count"] == 1


def test_harbor_recovery_receipt_surfaces_non110_runner_readiness() -> None:
    payload = validate_harbor_registry_controlled_recovery_receipt(
        {
            "non110_runner_readiness_output": _non110_runner_blocked_output(),
            "gitea_actions_queue_readback": _gitea_queue_current_cd_waiting_non110(),
        }
    )

    assert payload["status"] == "non110_runner_readiness_receipt_blocked"
    assert payload["safe_next_step"] == (
        "fix_or_register_non110_runner_then_rerun_readiness_and_queue_verifiers"
    )
    assert "non110_runner_readiness:runner_registration_missing" in payload[
        "active_blockers"
    ]
    assert "non110_runner_readiness:runner_service_not_active" in payload[
        "active_blockers"
    ]
    runner = payload["readback"]["non110_runner_readiness"]
    assert runner["receipt_seen"] is True
    assert runner["non110_runner_ready"] is False
    assert runner["ready_config_count"] == 1
    assert runner["ready_binary_count"] == 1
    assert runner["ready_registration_count"] == 0
    assert runner["ready_service_count"] == 1
    assert runner["ready_active_service_count"] == 0
    assert runner["ready_autostart_path_count"] == 1
    assert runner["raw_runner_registration_read"] is False
    assert runner["runner_token_read"] is False
    assert runner["raw_output_returned"] is False
    readiness = payload["readback"]["control_path_readiness"]
    assert readiness["status"] == "blocked_non110_controlled_runner_unavailable"
    assert readiness["non110_runner_unavailable"] is True
    assert readiness["non110_runner_ready"] is False
    assert "non110_runner_readiness_receipt_not_ready" in readiness["signal_ids"]
    assert (
        "gitea_queue_controlled_profile_no_matching_runner_labels"
        in readiness["signal_ids"]
    )
    phases = {
        phase["phase_id"]: phase
        for phase in payload["local_console_phase_readback"]["phases"]
    }
    assert phases["verify_non110_runner_lane"]["status"] == (
        "blocked_non110_runner_readiness_receipt_not_ready"
    )
    assert payload["rollups"]["non110_runner_readiness_receipt_seen"] is True
    assert payload["rollups"]["non110_runner_ready"] is False
    assert payload["rollups"]["non110_runner_blocker_count"] == 2
    assert (
        payload["rollups"]["control_path_readiness_non110_runner_unavailable"]
        is True
    )
    assert payload["input_redaction"]["non110_runner_readiness_output"][
        "line_count"
    ] > 0


def test_harbor_recovery_receipt_surfaces_control_path_readiness_blocker() -> None:
    diagnosis_output = _ssh_publickey_diagnosis_output().replace(
        "rc=124 classification=server_accepts_key_then_timeout",
        "rc=255 classification=publickey_offer_timeout",
    ).replace(
        "NODE_LOAD1_PER_CPU=0.93",
        "NODE_LOAD1_PER_CPU=4.53",
    ).replace(
        "NODE_LOAD_CLASSIFIER=load_not_high",
        "NODE_LOAD_CLASSIFIER=high_load",
    )

    payload = validate_harbor_registry_controlled_recovery_receipt(
        {
            "ssh_publickey_diagnosis_output": diagnosis_output,
            "public_registry_v2_http_status": 502,
            "internal_registry_v2_http_status": 502,
            "gitea_actions_queue_readback": _gitea_queue_cd_jobs_head_sha_mismatch(),
        }
    )

    readiness = payload["readback"]["control_path_readiness"]
    assert readiness["status"] == (
        "blocked_110_high_load_and_awoooi_host_control_path_unavailable"
    )
    assert readiness["primary_blocker"] == "ssh_publickey_node_high_load_on_110"
    assert readiness["safe_next_action"] == (
        "hold_110_capacity_protection_then_rerun_readonly_awoooi_host_and_registry_verifiers"
    )
    assert readiness["node_high_load"] is True
    assert readiness["node_load_classifier"] == "high_load"
    assert readiness["node_load1_per_cpu"] == 4.53
    assert readiness["ssh_publickey_offer_timeout"] is True
    assert readiness["runner_systemctl_show_timeout"] is True
    assert readiness["awoooi_host_runner_unavailable"] is True
    assert readiness["harbor_110_repair_no_matching_runner"] is True
    assert readiness["harbor_110_repair_no_matching_runner_label"] == "awoooi-host"
    assert readiness["harbor_110_repair_jobs_stale_or_mismatched"] is True
    assert readiness["cd_jobs_head_sha_mismatch"] is True
    assert readiness["registry_v2_public_http_status"] == 502
    assert readiness["registry_v2_internal_http_status"] == 502
    assert readiness["registry_v2_ready"] is False
    assert readiness["metadata_only"] is True
    assert readiness["raw_output_returned"] is False
    assert readiness["signal_ids"] == [
        "ssh_publickey_node_high_load_on_110",
        "ssh_publickey_offer_timeout_on_wooo",
        "runner_systemctl_show_timeout_on_110",
        "gitea_queue_harbor_110_repair_no_matching_runner",
        "gitea_queue_harbor_110_repair_jobs_stale_or_mismatched",
        "gitea_queue_cd_jobs_head_sha_mismatch",
        "gitea_queue_cd_jobs_stale_or_mismatched",
        "public_registry_v2_verifier_not_green",
        "internal_registry_v2_verifier_not_green",
    ]
    assert payload["rollups"]["control_path_readiness_status"] == (
        "blocked_110_high_load_and_awoooi_host_control_path_unavailable"
    )
    assert payload["rollups"]["control_path_readiness_blocker_count"] == 9
    assert payload["rollups"]["control_path_readiness_node_high_load"] is True
    assert (
        payload["rollups"]["control_path_readiness_runner_systemctl_timeout"]
        is True
    )
    assert payload["rollups"]["control_path_readiness_awoooi_host_unavailable"] is True
    assert (
        payload["rollups"]["control_path_readiness_registry_v2_public_ready"]
        is False
    )
    assert (
        payload["rollups"]["control_path_readiness_registry_v2_internal_ready"]
        is False
    )


def test_harbor_recovery_receipt_surfaces_gitea_queue_blockers() -> None:
    payload = validate_harbor_registry_controlled_recovery_receipt(
        {
            "watchdog_check_output": _watchdog_check_output(
                ready=True,
                status=401,
            ),
            "public_registry_v2_http_status": 401,
            "internal_registry_v2_http_status": 401,
            "gitea_actions_queue_readback": _gitea_queue_no_matching_runner(),
        }
    )

    assert payload["status"] == (
        "harbor_registry_recovery_receipt_verified_waiting_gitea_queue_clearance"
    )
    assert payload["accepted"] is False
    assert payload["safe_next_step"] == (
        "clear_harbor_110_runner_queue_then_retry_cd_marker_readback"
    )
    assert payload["active_blockers"] == [
        "gitea_queue_harbor_110_repair_no_matching_runner",
        "gitea_queue_harbor_110_repair_jobs_stale_or_mismatched",
    ]
    queue = payload["readback"]["gitea_actions_queue"]
    assert queue["status"] == "blocked_harbor_110_repair_no_matching_runner"
    assert queue["harbor_110_repair_no_matching_runner_label"] == "awoooi-host"
    assert queue["harbor_110_repair_jobs_stale_or_mismatched"] is True
    assert queue["harbor_110_repair_jobs_unexpected_names"] == ["ai-code-review"]
    normalized = {
        item["field_id"]: item for item in queue["normalized_classifier_fields"]
    }
    assert queue["normalized_classifier_field_count"] == 3
    assert queue["normalized_classifier_field_ids"] == [
        "cd_run_jobs_payload_classifier",
        "harbor_110_repair_jobs_payload_classifier",
        "latest_visible_harbor_110_repair_no_matching_runner_label",
    ]
    assert normalized[
        "latest_visible_harbor_110_repair_no_matching_runner_label"
    ]["value"] == "awoooi-host"
    assert normalized[
        "latest_visible_harbor_110_repair_no_matching_runner_label"
    ]["blockers"] == ["gitea_queue_harbor_110_repair_no_matching_runner"]
    assert all(
        item["metadata_only"] is True and item["raw_output_returned"] is False
        for item in normalized.values()
    )
    assert queue["raw_output_returned"] is False
    assert queue["top_visible_runs_returned"] is False
    assert payload["rollups"]["gitea_queue_blocker_count"] == 2
    assert payload["rollups"]["gitea_queue_harbor_110_no_matching_runner"] is True
    assert (
        payload["rollups"]["gitea_queue_harbor_110_jobs_stale_or_mismatched"]
        is True
    )
    assert payload["input_redaction"]["gitea_actions_queue_readback"] == {
        "provided": True,
        "metadata_only": True,
        "raw_output_returned": False,
        "top_visible_runs_returned": False,
    }


def test_harbor_recovery_receipt_surfaces_cross_workflow_queue_payload() -> None:
    payload = validate_harbor_registry_controlled_recovery_receipt(
        {
            "watchdog_check_output": _watchdog_check_output(
                ready=True,
                status=401,
            ),
            "public_registry_v2_http_status": 401,
            "internal_registry_v2_http_status": 401,
            "gitea_actions_queue_readback": _gitea_queue_cross_workflow_jobs(),
        }
    )

    assert "gitea_queue_harbor_110_repair_jobs_cross_workflow_mismatch" in payload[
        "active_blockers"
    ]
    assert "gitea_queue_harbor_110_repair_jobs_stale_or_mismatched" in payload[
        "active_blockers"
    ]
    queue = payload["readback"]["gitea_actions_queue"]
    assert queue["harbor_110_repair_jobs_cross_workflow_mismatch"] is True
    assert queue["harbor_110_repair_jobs_payload_classifier"] == (
        "cd_workflow_jobs_returned_for_harbor_110_repair_run"
    )
    assert queue["harbor_110_repair_jobs_expected_names"] == [
        "harbor-110-local-repair",
        "workflow-shape",
    ]
    assert payload["rollups"][
        "gitea_queue_harbor_110_jobs_cross_workflow_mismatch"
    ] is True
    assert payload["rollups"]["gitea_queue_harbor_110_jobs_payload_classifier"] == (
        "cd_workflow_jobs_returned_for_harbor_110_repair_run"
    )
    normalized = {
        item["field_id"]: item
        for item in payload["readback"]["gitea_actions_queue"][
            "normalized_classifier_fields"
        ]
    }
    assert normalized["harbor_110_repair_jobs_payload_classifier"]["value"] == (
        "cd_workflow_jobs_returned_for_harbor_110_repair_run"
    )
    assert normalized["harbor_110_repair_jobs_payload_classifier"]["blockers"] == [
        "gitea_queue_harbor_110_repair_jobs_cross_workflow_mismatch",
        "gitea_queue_harbor_110_repair_jobs_stale_or_mismatched",
    ]


def test_harbor_recovery_receipt_surfaces_stale_harbor_running_blocker() -> None:
    payload = validate_harbor_registry_controlled_recovery_receipt(
        {
            "public_registry_v2_http_status": 502,
            "internal_registry_v2_http_status": 502,
            "gitea_actions_queue_readback": (
                _gitea_queue_cd_waiting_behind_stale_harbor_running()
            ),
        }
    )

    assert "gitea_queue_harbor_110_repair_blocked" not in payload[
        "active_blockers"
    ]
    assert (
        "gitea_queue_harbor_110_repair_visible_running_jobs_api_stale"
        in payload["active_blockers"]
    )
    assert (
        "gitea_queue_current_cd_waiting_behind_harbor_110_repair_running"
        in payload["active_blockers"]
    )
    queue = payload["readback"]["gitea_actions_queue"]
    assert queue["status"] == (
        "blocked_current_cd_waiting_behind_stale_harbor_110_repair_readback"
    )
    assert queue["harbor_110_repair_no_matching_runner"] is False
    assert queue["harbor_110_repair_visible_running_jobs_api_stale"] is True
    assert queue["current_cd_waiting_behind_harbor_110_repair_running"] is True
    readiness = payload["readback"]["control_path_readiness"]
    assert readiness["status"] == "blocked_awoooi_host_runner_queue_unavailable"
    assert readiness["harbor_110_repair_visible_running_jobs_api_stale"] is True
    assert (
        readiness["current_cd_waiting_behind_harbor_110_repair_running"] is True
    )
    assert (
        "gitea_queue_harbor_110_repair_visible_running_jobs_api_stale"
        in readiness["signal_ids"]
    )
    assert (
        "gitea_queue_current_cd_waiting_behind_harbor_110_repair_running"
        in readiness["signal_ids"]
    )
    assert (
        payload["rollups"][
            "gitea_queue_harbor_110_repair_visible_running_jobs_api_stale"
        ]
        is True
    )
    assert (
        payload["rollups"][
            "gitea_queue_current_cd_waiting_behind_harbor_110_repair_running"
        ]
        is True
    )
    normalized = {
        item["field_id"]: item for item in queue["normalized_classifier_fields"]
    }
    assert normalized["harbor_110_repair_visible_running_jobs_api_stale"][
        "blockers"
    ] == ["gitea_queue_harbor_110_repair_visible_running_jobs_api_stale"]
    assert normalized["current_cd_waiting_behind_harbor_110_repair_running"][
        "blockers"
    ] == ["gitea_queue_current_cd_waiting_behind_harbor_110_repair_running"]


def test_harbor_recovery_receipt_surfaces_remote_control_timeout_queue_payload() -> None:
    payload = validate_harbor_registry_controlled_recovery_receipt(
        {
            "watchdog_check_output": _watchdog_check_output(
                ready=True,
                status=401,
            ),
            "public_registry_v2_http_status": 401,
            "internal_registry_v2_http_status": 401,
            "gitea_actions_queue_readback": _gitea_queue_remote_control_timeout(),
        }
    )

    assert payload["status"] == (
        "harbor_registry_recovery_receipt_verified_waiting_gitea_queue_clearance"
    )
    assert payload["active_blockers"] == [
        "gitea_queue_harbor_110_remote_control_channel_unavailable",
        "gitea_queue_harbor_110_repair_jobs_stale_or_mismatched",
    ]
    queue = payload["readback"]["gitea_actions_queue"]
    assert queue["status"] == "blocked_harbor_110_remote_control_channel_unavailable"
    assert queue["harbor_110_repair_failure_classifier"] == (
        "harbor_110_remote_control_channel_unavailable"
    )
    assert queue["harbor_110_repair_remote_control_channel_unavailable"] is True
    assert queue["harbor_110_repair_remote_ssh_reachable"] is False
    assert queue["harbor_110_repair_bounded_ssh_timeout_seen"] is True
    assert payload["rollups"][
        "gitea_queue_harbor_110_remote_control_channel_unavailable"
    ] is True
    assert payload["rollups"]["gitea_queue_harbor_110_repair_failure_classifier"] == (
        "harbor_110_remote_control_channel_unavailable"
    )
    normalized = {
        item["field_id"]: item for item in queue["normalized_classifier_fields"]
    }
    assert normalized["harbor_110_repair_failure_classifier"]["value"] == (
        "harbor_110_remote_control_channel_unavailable"
    )
    assert normalized["harbor_110_repair_failure_classifier"]["blockers"] == [
        "gitea_queue_harbor_110_remote_control_channel_unavailable"
    ]
    readiness = payload["readback"]["control_path_readiness"]
    assert readiness["status"] == "blocked_110_ssh_or_runner_control_path_timeout"
    assert (
        "gitea_queue_harbor_110_remote_control_channel_unavailable"
        in readiness["signal_ids"]
    )
    assert (
        readiness["harbor_110_repair_remote_control_channel_unavailable"] is True
    )


def test_harbor_recovery_receipt_surfaces_cd_jobs_payload_classifier() -> None:
    payload = validate_harbor_registry_controlled_recovery_receipt(
        {
            "watchdog_check_output": _watchdog_check_output(
                ready=True,
                status=401,
            ),
            "public_registry_v2_http_status": 401,
            "internal_registry_v2_http_status": 401,
            "gitea_actions_queue_readback": _gitea_queue_cd_jobs_head_sha_mismatch(),
        }
    )

    assert "gitea_queue_cd_jobs_head_sha_mismatch" in payload["active_blockers"]
    assert "gitea_queue_cd_jobs_stale_or_mismatched" in payload["active_blockers"]
    queue = payload["readback"]["gitea_actions_queue"]
    assert queue["cd_run_jobs_stale_or_mismatched"] is True
    assert queue["cd_run_jobs_head_sha_mismatch"] is True
    assert queue["cd_run_jobs_run_id_mismatch"] is False
    assert queue["cd_run_jobs_payload_classifier"] == (
        "cd_jobs_api_head_sha_mismatch_for_visible_cd_run"
    )
    assert queue["cd_run_jobs_expected_run_id"] == "4175"
    assert queue["cd_run_jobs_head_shas"] == [
        "26b67d11f7b7de4f9c9d95c01bb1dacf4000e887"
    ]
    assert payload["rollups"]["gitea_queue_cd_jobs_stale_or_mismatched"] is True
    assert payload["rollups"]["gitea_queue_cd_jobs_head_sha_mismatch"] is True
    assert payload["rollups"]["gitea_queue_cd_jobs_run_id_mismatch"] is False
    assert payload["rollups"]["gitea_queue_cd_jobs_payload_classifier"] == (
        "cd_jobs_api_head_sha_mismatch_for_visible_cd_run"
    )
    assert payload["rollups"]["gitea_queue_normalized_classifier_field_count"] == 3
    assert payload["rollups"]["gitea_queue_normalized_classifier_field_ids"] == [
        "cd_run_jobs_payload_classifier",
        "harbor_110_repair_jobs_payload_classifier",
        "latest_visible_harbor_110_repair_no_matching_runner_label",
    ]
    normalized = {
        item["field_id"]: item for item in queue["normalized_classifier_fields"]
    }
    assert normalized["cd_run_jobs_payload_classifier"]["value"] == (
        "cd_jobs_api_head_sha_mismatch_for_visible_cd_run"
    )
    assert normalized["cd_run_jobs_payload_classifier"]["blockers"] == [
        "gitea_queue_cd_jobs_head_sha_mismatch",
        "gitea_queue_cd_jobs_stale_or_mismatched",
    ]


def test_harbor_recovery_receipt_classifies_cd_jobs_only_readback_mismatch() -> None:
    payload = validate_harbor_registry_controlled_recovery_receipt(
        {
            "watchdog_check_output": _watchdog_check_output(
                ready=True,
                status=401,
            ),
            "public_registry_v2_http_status": 401,
            "internal_registry_v2_http_status": 401,
            "gitea_actions_queue_readback": _gitea_queue_cd_jobs_head_sha_mismatch_only(),
        }
    )

    readiness = payload["readback"]["control_path_readiness"]
    assert readiness["status"] == (
        "blocked_gitea_cd_jobs_readback_stale_or_mismatched"
    )
    assert readiness["safe_next_action"] == (
        "rerun_public_gitea_queue_and_deploy_marker_readback_before_cd_retry"
    )
    assert readiness["signal_ids"] == [
        "gitea_queue_cd_jobs_head_sha_mismatch",
        "gitea_queue_cd_jobs_stale_or_mismatched",
    ]


def test_harbor_recovery_receipt_surfaces_current_cd_runner_readiness() -> None:
    payload = validate_harbor_registry_controlled_recovery_receipt(
        {
            "gitea_actions_queue_readback": _gitea_queue_current_cd_waiting_non110(),
        }
    )

    assert "gitea_queue_current_cd_no_matching_runner" in payload["active_blockers"]
    assert (
        "gitea_queue_current_cd_waiting_for_runner_or_queue"
        in payload["active_blockers"]
    )
    queue = payload["readback"]["gitea_actions_queue"]
    assert queue["current_cd_waiting_for_runner_or_queue"] is True
    assert queue["current_cd_no_matching_runner_label"] == "awoooi-non110-ubuntu"
    assert queue["controlled_profile_no_matching_runner_labels"] == {
        "cd.yaml": "awoooi-non110-ubuntu",
        "harbor-110-local-repair.yaml": "awoooi-non110-host",
    }
    normalized = {
        item["field_id"]: item for item in queue["normalized_classifier_fields"]
    }
    assert normalized["current_cd_workflow_runner_readiness"]["value"] == (
        "awoooi-non110-ubuntu"
    )
    assert normalized["current_cd_workflow_runner_readiness"]["waiting"] is True
    assert normalized["current_cd_workflow_runner_readiness"]["blockers"] == [
        "gitea_queue_current_cd_no_matching_runner",
        "gitea_queue_current_cd_waiting_for_runner_or_queue",
    ]
    assert payload["rollups"][
        "gitea_queue_current_cd_waiting_for_runner_or_queue"
    ] is True
    assert payload["rollups"]["gitea_queue_current_cd_no_matching_runner_label"] == (
        "awoooi-non110-ubuntu"
    )
    assert (
        payload["rollups"][
            "gitea_queue_controlled_profile_no_matching_runner_label_count"
        ]
        == 2
    )


def test_harbor_recovery_receipt_waits_for_deploy_marker_readback() -> None:
    payload = validate_harbor_registry_controlled_recovery_receipt(
        {
            "watchdog_check_output": _watchdog_check_output(
                ready=True,
                status=401,
            ),
            "public_registry_v2_http_status": 401,
            "internal_registry_v2_http_status": 401,
            "deploy_marker_readback": _deploy_marker_stale(),
        }
    )

    assert payload["status"] == (
        "harbor_registry_recovery_receipt_verified_waiting_deploy_marker_readback"
    )
    assert payload["accepted"] is False
    assert payload["safe_next_step"] == (
        "rerun_gitea_cd_then_verify_deploy_marker_and_priority_readback"
    )
    assert payload["controlled_apply_policy"]["current_apply_blocker"] == (
        "deploy_marker_readback_required_after_registry_receipt"
    )
    assert payload["active_blockers"] == [
        "deploy_marker_closure_not_verified",
        "deploy_marker_production_image_not_current_main",
        "deploy_marker_latest_cd_run_not_success",
    ]
    deploy_marker = payload["readback"]["deploy_marker"]
    assert deploy_marker["deploy_marker_verified"] is False
    assert deploy_marker["expected_commit_sha"] == (
        "b72628914292a9988bdb6db187e47f70053c247c"
    )
    assert deploy_marker["production_image_matches_expected"] is False
    assert deploy_marker["latest_visible_cd_run_status"] == "Failure"
    assert deploy_marker["raw_output_returned"] is False
    assert payload["rollups"]["deploy_marker_blocker_count"] == 3
    assert payload["rollups"]["deploy_marker_latest_cd_run_status"] == "Failure"
    assert (
        payload["rollups"]["deploy_marker_production_image_matches_expected"]
        is False
    )


def test_harbor_recovery_receipt_requires_deploy_marker_http_readback() -> None:
    deploy_marker = _deploy_marker_verified()
    deploy_marker["readback"].pop("production_preflight_http_status")
    deploy_marker["readback"].pop("production_workbench_http_status")

    payload = validate_harbor_registry_controlled_recovery_receipt(
        {
            "watchdog_check_output": _watchdog_check_output(
                ready=True,
                status=401,
            ),
            "public_registry_v2_http_status": 401,
            "internal_registry_v2_http_status": 401,
            "deploy_marker_readback": deploy_marker,
        }
    )

    assert payload["status"] == (
        "harbor_registry_recovery_receipt_verified_waiting_deploy_marker_readback"
    )
    assert payload["readback"]["deploy_marker"]["deploy_marker_verified"] is False
    assert "deploy_marker_production_readback_http_not_green" in payload[
        "active_blockers"
    ]
    assert payload["rollups"]["deploy_marker_verified"] is False


def test_harbor_recovery_receipt_surfaces_inflight_cd_harbor_retry() -> None:
    payload = validate_harbor_registry_controlled_recovery_receipt(
        {
            "gitea_actions_queue_readback": _gitea_queue_no_matching_runner_with_cd_retry(),
        }
    )

    assert payload["status"] == "blocked_waiting_harbor_controlled_recovery_receipt"
    assert payload["safe_next_step"] == (
        "submit_non_secret_ssh_local_or_harbor_watchdog_receipt"
    )
    assert payload["active_blockers"] == [
        "harbor_watchdog_check_receipt_missing",
        "public_registry_v2_verifier_not_green",
        "internal_registry_v2_verifier_not_green",
        "gitea_queue_current_cd_harbor_retrying_unavailable",
        "gitea_queue_harbor_110_repair_no_matching_runner",
        "gitea_queue_harbor_110_repair_jobs_stale_or_mismatched",
    ]
    queue = payload["readback"]["gitea_actions_queue"]
    assert queue["latest_visible_cd_run_status"] == "Running"
    assert (
        queue["current_cd_inflight_classifier"]
        == "harbor_registry_public_route_unavailable_pending_retry"
    )
    assert queue["current_cd_harbor_latest_registry_v2_status"] == "502"
    assert queue["current_cd_harbor_retrying_unavailable"] is True
    assert (
        payload["rollups"]["gitea_queue_current_cd_inflight_classifier"]
        == "harbor_registry_public_route_unavailable_pending_retry"
    )
    assert (
        payload["rollups"][
            "gitea_queue_current_cd_harbor_latest_registry_v2_status"
        ]
        == "502"
    )
    assert (
        payload["rollups"]["gitea_queue_current_cd_harbor_retrying_unavailable"]
        is True
    )
    assert payload["rollups"]["gitea_queue_blocker_count"] == 3


def test_harbor_recovery_receipt_surfaces_non110_cd_repair_lane_blocker() -> None:
    payload = validate_harbor_registry_controlled_recovery_receipt(
        {
            "gitea_actions_queue_readback": (
                _gitea_queue_cd_harbor_repair_requires_110_lane()
            ),
        }
    )

    assert (
        "gitea_queue_cd_harbor_repair_blocked_by_no_matching_awoooi_host"
        in payload["active_blockers"]
    )
    assert (
        "gitea_queue_cd_harbor_repair_requires_110_controlled_lane"
        in payload["active_blockers"]
    )
    queue = payload["readback"]["gitea_actions_queue"]
    assert queue["current_cd_harbor_repair_requires_110_controlled_lane"] is True
    assert (
        queue["current_cd_harbor_repair_blocked_by_no_matching_awoooi_host"]
        is True
    )
    assert queue["current_cd_harbor_repair_lane_classifier"] == (
        "cd_harbor_repair_requires_110_controlled_lane_no_matching_awoooi_host"
    )
    readiness = payload["readback"]["control_path_readiness"]
    assert (
        "gitea_queue_cd_harbor_repair_blocked_by_no_matching_awoooi_host"
        in readiness["signal_ids"]
    )
    assert (
        "gitea_queue_cd_harbor_repair_requires_110_controlled_lane"
        in readiness["signal_ids"]
    )
    assert payload["rollups"][
        "gitea_queue_current_cd_harbor_repair_requires_110_controlled_lane"
    ] is True
    assert (
        payload["rollups"]["gitea_queue_current_cd_harbor_repair_lane_classifier"]
        == "cd_harbor_repair_requires_110_controlled_lane_no_matching_awoooi_host"
    )


def test_harbor_recovery_receipt_endpoint_redacts_raw_output() -> None:
    app = FastAPI()
    app.include_router(router, prefix="/api/v1")
    client = TestClient(app)

    response = client.post(
        "/api/v1/agents/harbor-registry-controlled-recovery-receipt",
        json={
            "watchdog_check_output": _watchdog_check_output(
                ready=True,
                status=401,
            ),
            "public_registry_v2_http_status": 401,
            "internal_registry_v2_http_status": 401,
        },
    )

    assert response.status_code == 200
    data = response.json()
    assert data["status"] == "harbor_registry_recovery_receipt_verified"
    assert data["accepted"] is True
    assert "watchdog_check_output" not in str(data["readback"])
    assert data["input_redaction"]["watchdog_check_output"]["line_count"] > 0


def _ssh_local_apply_output() -> str:
    return """
AWOOOI_110_SSH_PUBLICKEY_AUTH_LOCAL_REPAIR mode=apply target_user=wooo
SSH_SERVICE_ACTIVE=active
SSHD_CONFIG_SYNTAX=ok
USER_STATUS user=wooo exists=1 home=/home/wooo
ACCOUNT_METADATA user=wooo passwd_status=P account_locked=false shell=/bin/bash shell_exists=true shell_executable=true
PATH_STATUS path=/home/wooo mode=755 owner=wooo group=wooo type=directory
PATH_STATUS path=/home/wooo/.ssh mode=700 owner=wooo group=wooo type=directory
AUTHORIZED_KEYS_STATUS path=/home/wooo/.ssh/authorized_keys exists=1 bytes=380 lines=1
SSHD_EFFECTIVE_CONFIG available=true pubkeyauthentication=yes passwordauthentication=no kbdinteractiveauthentication=no usepam=yes maxstartups=10:30:100 authorized_keys_file_default=true
APPLIED permissions target_user=wooo home=/home/wooo
SSHD_CONFIG_SYNTAX_AFTER_APPLY=ok
SSH_RELOAD=skipped
"""


def _ssh_publickey_diagnosis_output() -> str:
    return """
AWOOOI_110_SSH_PUBLICKEY_AUTH_DIAGNOSIS
TARGET=192.168.0.110:22
NODE_EXPORTER=ok
NODE_LOAD1_PER_CPU=0.93
NODE_LOAD_CLASSIFIER=load_not_high
SSH_PORT=tcp_open
SSH_BANNER=SSH-2.0-OpenSSH_8.9p1
SSH_AUTH user=wooo mode=publickey rc=124 classification=server_accepts_key_then_timeout
SSH_AUTH user=root mode=publickey rc=255 classification=permission_denied
SSH_AUTH user=git mode=publickey rc=255 classification=preauth_timeout
SSH_AUTH user=ollama mode=publickey rc=255 classification=preauth_timeout
SSH_AUTH user=wooo mode=password_disabled rc=255 classification=permission_denied
SYSTEMD_UNIT unit=actions.runner.owenhytsai-awoooi.awoooi-110.service active_state=scrape_error classifier=systemctl_show_timeout
INTERPRETATION=server_accepts_key_then_timeout_on_wooo_means_check_110_session_pam_account_or_shell_path
"""


def _ssh_publickey_command_path_ready_output() -> str:
    return _ssh_publickey_diagnosis_output().replace(
        "SSH_AUTH user=wooo mode=password_disabled rc=255 classification=permission_denied",
        (
            "SSH_COMMAND_PATH user=wooo rc=0 classification=command_path_ready "
            "marker_seen=true remote_user_match=true\n"
            "SSH_AUTH user=wooo mode=password_disabled rc=255 "
            "classification=permission_denied"
        ),
    )


def _watchdog_check_output(*, ready: bool, status: int) -> str:
    ready_text = "true" if ready else "false"
    return f"""
AWOOOI_HARBOR_WATCHDOG_CHECK
mode=check
target=127.0.0.1:5000/v2/
expected_host_ip=192.168.0.110
expected_host_ip_present=true
harbor_dir=/home/wooo/harbor/harbor
harbor_dir_exists=true
harbor_compose_exists=true
docker_cli_available=true
docker_service_state=active
lockfile=/var/lock/harbor-repair.lock
lockfile_exists=false
harbor_local_v2_http_status={status}
harbor_ready={ready_text}
check_only=true
docker_compose_action_performed=false
container_remove_performed=false
service_restart_performed=false
host_reboot_performed=false
"""


def _controlled_cd_lane_blocked_output() -> str:
    return """
== audit metadata ==
read_only=true
secret_values_collected=false
runner_token_read=false
raw_runner_registration_read=false
== controlled lane registration metadata ==
CD_LANE_REGISTRATION path=/home/wooo/awoooi-cd-lane-drain/data/.runner present=0 content_read=false
BLOCKER controlled_cd_lane_registration_missing
== controlled lane service ==
CD_LANE_SERVICE_GUARDRAILS unit=awoooi-cd-lane-drain.service active=inactive main_pid=0 limits=1 target_match=1 registration_condition=1
BLOCKER controlled_cd_lane_service_not_active
== verdict ==
CONFIG_READY=1
BINARY_READY=1
REGISTRATION_READY=0
SERVICE_READY=0
LEGACY_FAILCLOSED=1
PRIMARY_LANE_FAILCLOSED=1
WARNING_COUNT=0
BLOCKER_COUNT=2
AWOOOI_110_CONTROLLED_CD_LANE_READY=0
safe_next_step=restore_or_register_awoooi_cd_lane_drain_registration_without_printing_token_then_rerun_this_verifier
"""


def _non110_runner_blocked_output() -> str:
    return """
== audit metadata ==
read_only=true
secret_values_collected=false
runner_token_read=false
raw_runner_registration_read=false
== non110 runner registration metadata ==
RUNNER_REGISTRATION path=/home/ollama/act-runner-awoooi/.runner present=0 content_read=false
BLOCKER runner_registration_missing
== non110 runner service ==
RUNNER_SERVICE unit=awoooi-non110-runner.service installed=1 active=inactive enabled=1
BLOCKER runner_service_not_active
== verdict ==
READY_CONFIG_COUNT=1
READY_BINARY_COUNT=1
READY_REGISTRATION_COUNT=0
READY_SERVICE_COUNT=1
READY_ACTIVE_SERVICE_COUNT=0
READY_AUTOSTART_PATH_COUNT=1
WARNING_COUNT=0
BLOCKER_COUNT=2
AWOOOI_NON110_RUNNER_READY=0
safe_next_step=run_register_awoooi_non110_runner_script_without_printing_token_then_autostart_path_will_enable_service_and_rerun_this_verifier
"""


def _gitea_queue_no_matching_runner() -> dict:
    return {
        "schema_version": "awoooi_public_gitea_actions_queue_readback_v1",
        "status": "blocked_harbor_110_repair_no_matching_runner",
        "operation_boundaries": {
            "public_gitea_read_only": True,
            "github_api_used": False,
            "host_write_performed": False,
            "runner_registration_performed": False,
            "runner_service_start_performed": False,
            "secret_or_runner_token_read": False,
            "workflow_dispatch_performed": False,
        },
        "readback": {
            "latest_visible_cd_run_id": "4110",
            "latest_visible_cd_run_status": "Running",
            "latest_visible_cd_run_commit_sha": (
                "5d10a9d1105757149b03373e35fc85a5aa772a96"
            ),
            "latest_visible_harbor_110_repair_run_id": "4108",
            "latest_visible_harbor_110_repair_run_status": "Waiting",
            "latest_visible_harbor_110_repair_no_matching_runner_label": (
                "awoooi-host"
            ),
            "latest_visible_harbor_110_repair_waiting": True,
            "latest_visible_harbor_110_repair_blocked": True,
            "harbor_110_repair_jobs_stale_or_mismatched": True,
            "harbor_110_repair_jobs_unexpected_names": ["ai-code-review"],
            "harbor_110_repair_jobs_labels": ["ubuntu-latest"],
            "harbor_110_repair_jobs_runner_names": ["wooo-runner"],
        },
        "rollups": {
            "harbor_110_repair_blocked": True,
            "harbor_110_repair_waiting": True,
            "harbor_110_repair_no_matching_runner_label": "awoooi-host",
            "harbor_110_repair_jobs_stale_or_mismatched": True,
        },
    }


def _gitea_queue_cross_workflow_jobs() -> dict:
    payload = _gitea_queue_no_matching_runner()
    payload["readback"].update(
        {
            "harbor_110_repair_jobs_cross_workflow_mismatch": True,
            "harbor_110_repair_jobs_payload_classifier": (
                "cd_workflow_jobs_returned_for_harbor_110_repair_run"
            ),
            "harbor_110_repair_jobs_expected_names": [
                "harbor-110-local-repair",
                "workflow-shape",
            ],
            "harbor_110_repair_jobs_unexpected_names": [
                "build-and-deploy",
                "post-deploy-checks",
                "tests",
            ],
            "harbor_110_repair_jobs_labels": ["awoooi-host"],
        }
    )
    payload["rollups"].update(
        {
            "harbor_110_repair_jobs_cross_workflow_mismatch": True,
            "harbor_110_repair_jobs_payload_classifier": (
                "cd_workflow_jobs_returned_for_harbor_110_repair_run"
            ),
        }
    )
    return payload


def _gitea_queue_cd_waiting_behind_stale_harbor_running() -> dict:
    payload = _gitea_queue_cross_workflow_jobs()
    payload["status"] = (
        "blocked_current_cd_waiting_behind_stale_harbor_110_repair_readback"
    )
    payload["readback"].update(
        {
            "latest_visible_cd_run_id": "4243",
            "latest_visible_cd_run_status": "Waiting",
            "latest_visible_cd_run_waiting": True,
            "latest_visible_harbor_110_repair_run_id": "4237",
            "latest_visible_harbor_110_repair_run_status": "Running",
            "latest_visible_harbor_110_repair_no_matching_runner_label": "",
            "latest_visible_harbor_110_repair_waiting": False,
            "latest_visible_harbor_110_repair_running": True,
            "latest_visible_harbor_110_repair_blocked": True,
            "harbor_110_repair_visible_running_jobs_api_stale": True,
            "current_cd_waiting_behind_harbor_110_repair_running": True,
        }
    )
    payload["rollups"].update(
        {
            "current_main_cd_run_waiting": True,
            "harbor_110_repair_waiting": False,
            "harbor_110_repair_running": True,
            "harbor_110_repair_no_matching_runner_label": "",
            "harbor_110_repair_visible_running_jobs_api_stale": True,
            "current_cd_waiting_behind_harbor_110_repair_running": True,
        }
    )
    return payload


def _gitea_queue_remote_control_timeout() -> dict:
    payload = _gitea_queue_no_matching_runner()
    payload["status"] = "blocked_harbor_110_remote_control_channel_unavailable"
    payload["readback"].update(
        {
            "latest_visible_harbor_110_repair_run_status": "Failure",
            "latest_visible_harbor_110_repair_no_matching_runner_label": "",
            "latest_visible_harbor_110_repair_waiting": False,
            "latest_visible_harbor_110_repair_blocked": True,
            "latest_visible_harbor_110_repair_failure_classifier": (
                "harbor_110_remote_control_channel_unavailable"
            ),
            "latest_visible_harbor_110_repair_remote_control_channel_unavailable": (
                True
            ),
            "latest_visible_harbor_110_repair_remote_ssh_reachable": False,
            "latest_visible_harbor_110_repair_bounded_ssh_timeout_seen": True,
        }
    )
    payload["rollups"].update(
        {
            "harbor_110_repair_blocked": True,
            "harbor_110_repair_waiting": False,
            "harbor_110_repair_no_matching_runner_label": "",
            "harbor_110_repair_failure_classifier": (
                "harbor_110_remote_control_channel_unavailable"
            ),
            "harbor_110_repair_remote_control_channel_unavailable": True,
            "harbor_110_repair_remote_ssh_reachable": False,
            "harbor_110_repair_bounded_ssh_timeout_seen": True,
        }
    )
    return payload


def _gitea_queue_cd_jobs_head_sha_mismatch() -> dict:
    payload = _gitea_queue_no_matching_runner()
    payload["readback"].update(
        {
            "latest_visible_cd_run_id": "4175",
            "latest_visible_cd_run_commit_sha": (
                "77f9bb0417543507a7540ace90bee9b33e9a8e31"
            ),
            "cd_run_jobs_expected_run_id": "4175",
            "cd_run_jobs_expected_head_sha": (
                "77f9bb0417543507a7540ace90bee9b33e9a8e31"
            ),
            "cd_run_jobs_head_shas": [
                "26b67d11f7b7de4f9c9d95c01bb1dacf4000e887"
            ],
            "cd_run_jobs_run_ids": ["4175"],
            "cd_run_jobs_head_sha_mismatch": True,
            "cd_run_jobs_run_id_mismatch": False,
            "cd_run_jobs_stale_or_mismatched": True,
            "cd_run_jobs_payload_classifier": (
                "cd_jobs_api_head_sha_mismatch_for_visible_cd_run"
            ),
        }
    )
    payload["rollups"].update(
        {
            "cd_run_jobs_head_sha_mismatch": True,
            "cd_run_jobs_run_id_mismatch": False,
            "cd_run_jobs_stale_or_mismatched": True,
            "cd_run_jobs_payload_classifier": (
                "cd_jobs_api_head_sha_mismatch_for_visible_cd_run"
            ),
        }
    )
    return payload


def _gitea_queue_cd_jobs_head_sha_mismatch_only() -> dict:
    payload = _gitea_queue_cd_jobs_head_sha_mismatch()
    payload["readback"].update(
        {
            "latest_visible_harbor_110_repair_no_matching_runner_label": "",
            "harbor_110_repair_jobs_stale_or_mismatched": False,
            "harbor_110_repair_jobs_unexpected_names": [],
            "harbor_110_repair_jobs_labels": [],
            "harbor_110_repair_jobs_runner_names": [],
        }
    )
    payload["rollups"].update(
        {
            "harbor_110_repair_no_matching_runner_label": "",
            "harbor_110_repair_jobs_stale_or_mismatched": False,
        }
    )
    return payload


def _gitea_queue_current_cd_waiting_non110() -> dict:
    payload = _gitea_queue_cd_jobs_head_sha_mismatch()
    payload["status"] = "blocked_current_cd_workflow_waiting_for_runner_or_queue"
    payload["readback"].update(
        {
            "latest_visible_cd_run_status": "Waiting",
            "latest_visible_cd_run_waiting": True,
            "latest_visible_cd_no_matching_runner_label": "awoooi-non110-ubuntu",
            "controlled_profile_no_matching_runner_labels": {
                "cd.yaml": "awoooi-non110-ubuntu",
                "harbor-110-local-repair.yaml": "awoooi-non110-host",
            },
            "controlled_profile_no_matching_runner_label_count": 2,
            "latest_visible_harbor_110_repair_no_matching_runner_label": (
                "awoooi-non110-host"
            ),
        }
    )
    payload["rollups"].update(
        {
            "current_main_cd_run_status": "Waiting",
            "current_main_cd_run_waiting": True,
            "current_main_cd_no_matching_runner_label": "awoooi-non110-ubuntu",
            "controlled_profile_no_matching_runner_label_count": 2,
            "controlled_profile_no_matching_runner_labels": {
                "cd.yaml": "awoooi-non110-ubuntu",
                "harbor-110-local-repair.yaml": "awoooi-non110-host",
            },
            "harbor_110_repair_no_matching_runner_label": "awoooi-non110-host",
        }
    )
    return payload


def _deploy_marker_verified() -> dict:
    return {
        "schema_version": "awoooi_production_deploy_readback_blocker_v1",
        "status": "closure_verified",
        "readback": {
            "observed_source_control_main_sha": (
                "b72628914292a9988bdb6db187e47f70053c247c"
            ),
            "deploy_marker_commit_sha": (
                "0123456789abcdef0123456789abcdef01234567"
            ),
            "production_image_tag_sha": (
                "b72628914292a9988bdb6db187e47f70053c247c"
            ),
            "production_preflight_http_status": 200,
            "production_workbench_http_status": 200,
            "latest_visible_cd_run_id": "4113",
            "latest_visible_cd_run_status": "Success",
        },
        "rollups": {
            "production_image_tag_matches_main": True,
            "hard_blocker_count": 0,
        },
        "operation_boundaries": {
            "deploy_trigger_allowed": False,
            "workflow_modification_allowed": False,
            "gitea_api_write_allowed": False,
            "host_write_allowed": False,
            "k8s_write_allowed": False,
            "secret_read_allowed": False,
            "github_api_allowed": False,
            "raw_session_or_sqlite_read_allowed": False,
        },
    }


def _deploy_marker_stale() -> dict:
    return {
        "schema_version": "awoooi_production_deploy_readback_blocker_v1",
        "status": "blocked_harbor_registry_public_route_unavailable",
        "expected_commit_sha": "b72628914292a9988bdb6db187e47f70053c247c",
        "readback": {
            "deploy_marker_commit_sha": (
                "0123456789abcdef0123456789abcdef01234567"
            ),
            "production_image_tag_sha": (
                "5d10a9d1105757149b03373e35fc85a5aa772a96"
            ),
            "production_preflight_http_status": 200,
            "production_workbench_http_status": 200,
            "latest_visible_cd_run_id": "4111",
            "latest_visible_cd_run_status": "Failure",
        },
        "rollups": {
            "production_image_tag_matches_main": False,
            "hard_blocker_count": 1,
        },
        "operation_boundaries": {
            "deploy_trigger_allowed": False,
            "workflow_modification_allowed": False,
            "gitea_api_write_allowed": False,
            "host_write_allowed": False,
            "k8s_write_allowed": False,
            "secret_read_allowed": False,
            "github_api_allowed": False,
            "raw_session_or_sqlite_read_allowed": False,
        },
    }


def _gitea_queue_no_matching_runner_with_cd_retry() -> dict:
    payload = _gitea_queue_no_matching_runner()
    payload["readback"].update(
        {
            "latest_visible_cd_run_status": "Running",
            "latest_visible_cd_inflight_classifier": (
                "harbor_registry_public_route_unavailable_pending_retry"
            ),
            "latest_visible_cd_harbor_latest_registry_v2_status": "502",
            "latest_visible_cd_harbor_public_route_retrying_unavailable": True,
        }
    )
    payload["rollups"].update(
        {
            "current_main_cd_inflight_classifier": (
                "harbor_registry_public_route_unavailable_pending_retry"
            ),
            "current_main_cd_harbor_latest_registry_v2_status": "502",
            "current_main_cd_harbor_public_route_retrying_unavailable": True,
        }
    )
    return payload


def _gitea_queue_cd_harbor_repair_requires_110_lane() -> dict:
    payload = _gitea_queue_no_matching_runner()
    payload["readback"].update(
        {
            "latest_visible_cd_harbor_repair_requires_110_controlled_lane": True,
            "latest_visible_cd_harbor_repair_blocked_by_no_matching_awoooi_host": True,
            "latest_visible_cd_harbor_repair_lane_classifier": (
                "cd_harbor_repair_requires_110_controlled_lane_no_matching_awoooi_host"
            ),
        }
    )
    payload["rollups"].update(
        {
            "current_main_cd_harbor_repair_requires_110_controlled_lane": True,
            "current_main_cd_harbor_repair_blocked_by_no_matching_awoooi_host": True,
            "current_main_cd_harbor_repair_lane_classifier": (
                "cd_harbor_repair_requires_110_controlled_lane_no_matching_awoooi_host"
            ),
        }
    )
    return payload
