from __future__ import annotations

from fastapi import FastAPI
from fastapi.testclient import TestClient

from src.api.v1.agents import router
from src.services.ai_agent_log_controlled_writeback_executor_readback import (
    load_latest_ai_agent_log_controlled_writeback_executor_readback,
)


def test_log_controlled_writeback_executor_loader_builds_batches():
    payload = load_latest_ai_agent_log_controlled_writeback_executor_readback()

    _assert_executor_readback(payload)


def test_log_controlled_writeback_executor_endpoint_returns_readback():
    app = FastAPI()
    app.include_router(router, prefix="/api/v1")
    client = TestClient(app)

    response = client.get("/api/v1/agents/agent-log-controlled-writeback-executor-readback")

    assert response.status_code == 200
    assert "192.168.0.110" not in response.text
    _assert_executor_readback(response.json(), public_endpoint=True)


def _assert_executor_readback(payload: dict, *, public_endpoint: bool = False):
    expected_runtime_sample_count = 3
    expected_target_count = 6
    expected_writeback_plan_count = expected_runtime_sample_count * expected_target_count

    assert payload["schema_version"] == "ai_agent_log_controlled_writeback_executor_readback_v1"
    assert payload["priority"] == "P1-LOG-KM-RAG-MCP-PLAYBOOK"
    assert payload["status"] == "controlled_writeback_executor_ready"
    assert payload["active_blockers"] == []
    assert payload["readback"]["source_status"] == "controlled_writeback_plan_ready"
    assert payload["readback"]["safe_next_step"] == (
        "dispatch_controlled_metadata_writeback_batches_then_post_apply_verify"
    )

    policy = payload["executor_policy"]
    assert policy["executor_route"] == "ai_agent_metadata_writeback_executor"
    assert policy["low_medium_high_controlled_apply_enabled"] is True
    assert policy["owner_review_required_for_low_medium_high"] is False
    assert policy["critical_break_glass_required"] is True
    assert policy["target_selector_required"] is True
    assert policy["source_of_truth_diff_required"] is True
    assert policy["check_mode_required"] is True
    assert policy["rollback_required"] is True
    assert policy["post_apply_verifier_required"] is True

    assert payload["rollups"]["source_writeback_plan_count"] == expected_writeback_plan_count
    assert payload["rollups"]["execution_batch_count"] == expected_target_count
    assert payload["rollups"]["ready_execution_batch_count"] == expected_target_count
    assert payload["rollups"]["target_count"] == expected_target_count
    assert payload["rollups"]["target_selector_count"] == expected_writeback_plan_count
    assert payload["rollups"]["source_of_truth_diff_count"] == expected_writeback_plan_count
    assert payload["rollups"]["check_mode_ready_count"] == expected_target_count
    assert payload["rollups"]["rollback_ready_count"] == expected_target_count
    assert payload["rollups"]["post_apply_verifier_ready_count"] == expected_target_count
    assert payload["rollups"]["log_source_tagging_contract_count"] == 10
    assert payload["rollups"]["log_source_grouping_key_count"] == 10
    assert payload["rollups"]["metadata_only_log_source_tagging_ready"] is True
    assert payload["rollups"]["controlled_executor_dispatch_ready"] is True
    assert payload["rollups"]["controlled_apply_enabled_by_policy"] is True
    assert payload["rollups"]["current_blocker_execution_queue_count"] == 1
    assert payload["rollups"]["current_blocker_control_path_blocked_count"] == 0
    assert (
        payload["rollups"]["current_blocker_control_path_pressure_blocked_count"]
        == 0
    )
    assert payload["rollups"]["current_blocker_local_recovery_package_count"] == 1
    assert (
        payload["rollups"]["current_blocker_harbor_recovery_receipt_input_count"]
        == 11
    )
    assert (
        payload["rollups"][
            "current_blocker_harbor_recovery_receipt_output_contract_count"
        ]
        == 8
    )
    assert payload["rollups"]["current_blocker_registry_v2_ready_count"] == 1
    assert (
        payload["rollups"]["current_blocker_deploy_marker_readback_required_count"]
        == 0
    )
    assert (
        payload["rollups"]["current_blocker_cd_failure_after_registry_ready_count"]
        == 0
    )
    assert payload["rollups"]["runtime_dispatch_performed"] is False

    batches = {batch["target"]: batch for batch in payload["execution_batches"]}
    assert set(batches) == {"km", "rag", "playbook", "mcp", "verifier", "ai_agent"}
    for target, batch in batches.items():
        assert batch["batch_id"] == f"log-feedback-controlled-writeback::{target}"
        assert batch["executor_route"] == "ai_agent_metadata_writeback_executor"
        assert batch["status"] == "ready_for_controlled_executor_dispatch"
        assert batch["apply_mode"] == "controlled_apply"
        assert batch["dispatch_enabled_by_policy"] is True
        assert batch["plan_count"] == expected_runtime_sample_count
        assert len(batch["plan_ids"]) == expected_runtime_sample_count
        assert len(batch["receipt_ids"]) == expected_runtime_sample_count
        assert batch["target_selector_count"] == expected_runtime_sample_count
        assert batch["source_of_truth_diff_count"] == expected_runtime_sample_count
        assert batch["check_mode"]["enabled"] is True
        assert batch["check_mode"]["required"] is True
        assert batch["rollback"]["required"] is True
        assert len(batch["rollback"]["rollback_refs"]) == expected_runtime_sample_count
        assert batch["post_apply_verifier"]["required"] is True
        assert (
            len(batch["post_apply_verifier"]["verifier_refs"])
            == expected_runtime_sample_count
        )
        assert batch["current_blocker_recovery_count"] == 1
        assert batch["current_blocker_recoveries"][0]["blocker_id"] == (
            "controlled_cd_lane_guardrails_blocked"
        )
        assert batch["current_blocker_recoveries"][0]["runner_label"] == (
            "awoooi-non110-host"
        )
        assert batch["runtime_dispatch_performed"] is False

    context = payload["agent_consumption_context"]
    assert context["context_id"] == "ai-agent-log-controlled-writeback-consumption-v1"
    assert "ai_agent_autonomous_runtime_control" in context["consumable_by"]
    assert "km_rag_playbook_learning_loop" in context["consumable_by"]
    assert context["log_source_tagging_contract_count"] == 10
    assert context["log_source_grouping_keys"] == [
        "project_id",
        "product",
        "site_or_route",
        "service",
        "package",
        "tool",
        "source_system",
        "runtime_component",
        "signal_lane",
        "evidence_boundary",
    ]
    assert {
        item["tag_key"] for item in context["log_source_tagging_contract"]
    } == set(context["log_source_grouping_keys"])
    assert len(context["evidence_chain"]) == 4
    assert len(context["next_action_queue"]) == 6
    assert {item["target"] for item in context["next_action_queue"]} == set(batches)
    current_queue = context["current_blocker_execution_queue"]
    assert len(current_queue) == 1
    assert current_queue[0]["queue_item_id"] == (
        "current-p0-blocker::controlled_cd_lane_guardrails_blocked"
    )
    assert current_queue[0]["status"] == (
        "controlled_recovery_packaged_waiting_controlled_cd_lane_guardrails_readback"
    )
    assert current_queue[0]["runner_label"] == "awoooi-non110-host"
    assert current_queue[0]["node_load_classifier"] == "load_not_high"
    assert current_queue[0]["node_load_high"] is False
    assert current_queue[0]["registry_v2_status"] == 401
    assert current_queue[0]["registry_v2_ready"] is True
    assert current_queue[0]["registry_v2_status_classifier"] == (
        "ready_auth_required_http_401"
    )
    assert current_queue[0]["deployment_closure_state"] == (
        "blocked_controlled_cd_lane_guardrails_after_ssh_and_harbor_ready"
    )
    assert current_queue[0]["deploy_marker_readback_required"] is False
    assert current_queue[0]["current_cd_run_id"] == "4293"
    assert current_queue[0]["current_cd_run_status"] == "production_readback_verified"
    assert current_queue[0]["current_cd_commit_sha"] == (
        "87512d32f5a73849b2d8090092677a745c85f9a8"
    )
    assert current_queue[0]["cd_failed_after_registry_ready"] is False
    assert current_queue[0]["harbor_110_repair_run_id"] == "4255"
    assert current_queue[0]["harbor_110_repair_run_status"] == "Failure"
    assert current_queue[0]["harbor_110_repair_failed_after_registry_ready"] is False
    assert current_queue[0]["harbor_110_repair_failure_classifier"] == (
        "controlled_cd_lane_guardrails_blocked_after_ssh_and_harbor_ready"
    )
    assert current_queue[0]["log_source_tag_count"] == 10
    source_tags = {
        item["tag_key"]: item for item in current_queue[0]["log_source_tags"]
    }
    assert source_tags["project_id"]["tag_value"] == "awoooi"
    assert source_tags["product"]["tag_value"] == "awoooi"
    assert source_tags["service"]["tag_value"] == "awoooi-110-control-path"
    assert source_tags["package"]["tag_value"] == "ops/runner"
    assert source_tags["tool"]["tag_value"] == (
        "read_public_gitea_queue_and_remote_control_classifier"
    )
    assert source_tags["source_system"]["tag_value"] == (
        "gitea_queue_and_remote_control_classifier_readback"
    )
    assert source_tags["signal_lane"]["tag_value"] == (
        "controlled_cd_lane_guardrails_blocked"
    )
    assert all(
        item["metadata_only"] is True
        and item["raw_output_allowed"] is False
        and item["secret_value_allowed"] is False
        for item in source_tags.values()
    )
    assert current_queue[0]["controlled_recovery_package"] == (
        "check-awoooi-110-controlled-cd-lane-readiness.sh"
    )
    assert current_queue[0]["post_apply_verifier"] == (
        "harbor-registry-controlled-recovery-receipt validator"
    )
    assert current_queue[0]["harbor_recovery_receipt_endpoint"] == (
        "/api/v1/agents/harbor-registry-controlled-recovery-receipt"
    )
    assert current_queue[0]["harbor_recovery_receipt_input_count"] == 11
    assert [
        item["input_id"]
        for item in current_queue[0]["harbor_recovery_receipt_inputs"]
    ] == [
        "gitea_actions_queue_readback",
        "remote_control_channel_readback",
        "ssh_local_repair_output",
        "local_console_recovery_output",
        "watchdog_check_output",
        "watchdog_repair_output",
        "controlled_cd_lane_readiness_output",
        "non110_runner_readiness_output",
        "public_registry_v2_http_status",
        "internal_registry_v2_http_status",
        "deploy_marker_readback",
    ]
    assert current_queue[0]["harbor_recovery_receipt_inputs"][-1][
        "expected_schema"
    ] == "awoooi_production_deploy_readback_blocker_v1"
    assert current_queue[0]["harbor_recovery_receipt_output_contract_count"] == 8
    assert current_queue[0]["safe_next_action_id"] == (
        "restore_controlled_cd_lane_guardrails_then_rerun_readiness_receipt"
    )
    assert current_queue[0]["safe_next_action_stage"] == (
        "controlled_cd_lane_guardrails_receipt_required"
    )
    assert current_queue[0]["safe_next_action_requires_local_console"] is False
    assert current_queue[0]["safe_next_action_command"] == (
        "check-awoooi-110-controlled-cd-lane-readiness.sh"
    )
    assert [
        item["output_id"]
        for item in current_queue[0]["harbor_recovery_receipt_output_contract"]
    ] == [
        "control_path_readiness",
        "ssh_local_repair",
        "controlled_cd_lane_readiness",
        "non110_runner_readiness",
        "gitea_actions_queue",
        "local_console_phase_readback",
        "post_apply_verifier",
        "deploy_marker",
    ]
    assert all(
        item["metadata_only"] is True
        and item["raw_output_allowed"] is False
        and item["secret_value_allowed"] is False
        and item["writeback_targets"] == [
            "km",
            "rag",
            "playbook",
            "mcp",
            "verifier",
            "ai_agent",
        ]
        for item in current_queue[0]["harbor_recovery_receipt_output_contract"]
    )
    assert current_queue[0]["queue_readback_normalizer_contract_count"] == 15
    assert [
        item["field_id"]
        for item in current_queue[0]["queue_readback_normalizer_contract"]
    ] == [
        "cd_run_jobs_payload_classifier",
        "harbor_110_repair_jobs_payload_classifier",
        "latest_visible_harbor_110_repair_no_matching_runner_label",
        "latest_visible_harbor_110_repair_remote_control_channel_unavailable",
        "latest_visible_harbor_110_repair_remote_ssh_publickey_auth_stalled",
        "latest_visible_harbor_110_repair_remote_ssh_publickey_offer_timeout",
        "latest_visible_harbor_110_repair_remote_ssh_server_accepts_key_then_session_timeout",
        "current_cd_workflow_runner_readiness",
        "current_cd_deploy_marker_closure",
        "registry_v2_ready_state",
        "harbor_110_repair_failure_after_registry_ready",
        "harbor_110_repair_visible_running_jobs_api_stale",
        "current_cd_waiting_behind_harbor_110_repair_running",
        "safe_next_action_id",
        "controlled_profile_no_matching_runner_labels",
    ]
    assert "gitea_queue_cd_jobs_stale_or_mismatched" in current_queue[0][
        "queue_readback_normalizer_contract"
    ][0]["writes_blockers"]
    assert all(
        item["metadata_only"] is True
        and item["raw_output_allowed"] is False
        and item["secret_value_allowed"] is False
        for item in current_queue[0]["harbor_recovery_receipt_inputs"]
    )
    assert [phase["phase_id"] for phase in current_queue[0][
        "controlled_local_console_execution_plan"
    ]] == [
        "verify_ssh_control_path_restored",
        "verify_harbor_v2_ready",
        "verify_controlled_cd_lane_guardrails",
    ]
    assert current_queue[0]["controlled_local_console_execution_plan"][0][
        "mode"
    ] == "read_only"
    assert current_queue[0]["controlled_local_console_execution_plan"][2][
        "command"
    ] == "check-awoooi-110-controlled-cd-lane-readiness.sh"
    assert current_queue[0]["post_recovery_readback_commands"] == [
        "check-awoooi-110-controlled-cd-lane-readiness.sh",
        "curl -k https://registry.wooo.work/v2/",
        _expected_local_registry_readback(public_endpoint=public_endpoint),
    ]
    assert "read_runner_registration_token_or_runner_file" in current_queue[0][
        "forbidden_runtime_actions"
    ]
    assert current_queue[0]["runtime_write_gate"] == (
        "controlled_after_110_local_console_preflight"
    )
    assert current_queue[0]["runtime_apply_required_on_110_local_console"] is False
    assert current_queue[0]["external_control_path_blocker"] == ""
    assert current_queue[0]["control_path_pressure_blocker"] == ""
    assert current_queue[0]["control_channel_readback_required"] is False
    assert set(current_queue[0]["learning_writeback_targets"]) == set(batches)
    assert len(current_queue[0]["target_batches"]) == 6
    assert current_queue[0]["runtime_dispatch_performed"] is False
    assert current_queue[0]["raw_payload_required"] is False
    assert context["learning_feedback_targets"] == [
        "km",
        "rag",
        "playbook",
        "mcp",
        "verifier",
        "ai_agent",
    ]
    assert context["raw_payload_required"] is False

    boundaries = payload["operation_boundaries"]
    assert boundaries["executor_readback_only"] is True
    assert boundaries["controlled_apply_enabled_by_policy"] is True
    assert boundaries["executor_dispatch_performed"] is False
    assert boundaries["km_write_performed"] is False
    assert boundaries["rag_index_write_performed"] is False
    assert boundaries["playbook_trust_write_performed"] is False
    assert boundaries["mcp_tool_call_performed"] is False
    assert boundaries["agent_runtime_action_performed"] is False
    assert boundaries["workflow_trigger_performed"] is False
    assert boundaries["raw_log_payload_persisted"] is False
    assert boundaries["secret_value_collection_allowed"] is False
    assert boundaries["github_api_used"] is False


def _expected_local_registry_readback(*, public_endpoint: bool = False) -> str:
    if public_endpoint:
        return "curl host:public-gateway/registry/v2/"
    return "curl http://192.168.0.110:5000/v2/"
