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_plan_readback import (
    load_latest_ai_agent_log_controlled_writeback_plan_readback,
)


def test_log_controlled_writeback_plan_loader_builds_apply_plan():
    payload = load_latest_ai_agent_log_controlled_writeback_plan_readback()

    _assert_controlled_writeback_plan(payload)


def test_log_controlled_writeback_plan_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-plan-readback")

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


def _assert_controlled_writeback_plan(payload: dict, *, public_endpoint: bool = False):
    assert payload["schema_version"] == "ai_agent_log_controlled_writeback_plan_readback_v1"
    assert payload["priority"] == "P1-LOG-KM-RAG-MCP-PLAYBOOK"
    assert payload["status"] == "controlled_writeback_plan_ready"
    assert payload["active_blockers"] == []
    assert payload["readback"]["feedback_status"] == "trusted_feedback_receipt_dry_run_ready"
    assert payload["readback"]["verifier_status"] == "post_write_verifier_dry_run_ready"
    assert payload["readback"]["safe_next_step"] == (
        "execute_controlled_writeback_apply_with_post_apply_verifier"
    )

    controlled_apply = payload["controlled_apply"]
    assert controlled_apply["mode"] == "controlled_apply_prepared"
    assert controlled_apply["target_selector_required"] is True
    assert controlled_apply["source_of_truth_diff_required"] is True
    assert controlled_apply["check_mode_required"] is True
    assert controlled_apply["rollback_required"] is True
    assert controlled_apply["post_apply_verifier_required"] is True
    assert controlled_apply["owner_review_required_for_low_medium_high"] is False
    assert controlled_apply["critical_break_glass_required"] is True

    assert payload["rollups"]["target_count"] == 6
    assert payload["rollups"]["candidate_receipt_count"] == 18
    assert payload["rollups"]["writeback_plan_count"] == 18
    assert payload["rollups"]["ready_writeback_plan_count"] == 18
    assert payload["rollups"]["current_blocker_recovery_plan_count"] == 6
    assert payload["rollups"]["current_blocker_recovery_unique_count"] == 1
    assert payload["rollups"]["check_mode_plan_count"] == 18
    assert payload["rollups"]["rollback_plan_count"] == 18
    assert payload["rollups"]["post_apply_verifier_plan_count"] == 18
    assert payload["rollups"]["controlled_writeback_plan_ready"] is True
    assert payload["rollups"]["runtime_write_performed"] is False

    target_rollups = {item["target"]: item for item in payload["target_rollups"]}
    assert set(target_rollups) == {"km", "rag", "playbook", "mcp", "verifier", "ai_agent"}
    for rollup in target_rollups.values():
        assert rollup["plan_count"] == 3
        assert rollup["ready_plan_count"] == 3
        assert rollup["check_mode_ready"] is True
        assert rollup["rollback_ready"] is True
        assert rollup["post_apply_verifier_ready"] is True

    plans = payload["writeback_plans"]
    assert {plan["target"] for plan in plans} == set(target_rollups)
    assert all(plan["status"] == "controlled_apply_ready" for plan in plans)
    assert all(plan["write_enabled_by_plan"] is False for plan in plans)
    for plan in plans:
        selector = plan["target_selector"]
        assert selector["project_id"] == "awoooi"
        assert selector["product"] == "awoooi"
        assert selector["service"] in {
            "awoooi-api",
            "awoooi-worker",
            "awoooi-110-control-path",
        }
        assert selector["package"] in {"apps/api", "ops/runner"}
        assert selector["tool"] in {
            "kubectl_logs_readback",
            "read_public_gitea_queue_and_remote_control_classifier",
        }
        assert selector["source_system"] in {
            "k8s_logs",
            "gitea_queue_and_remote_control_classifier_readback",
        }
        assert selector["target_surface"]
        assert plan["source_of_truth_diff"]["current_state"] == (
            "metadata_only_feedback_not_written"
        )
        assert plan["source_of_truth_diff"]["desired_state"] == (
            "metadata_only_feedback_receipt_bound_to_target"
        )
        assert plan["source_of_truth_diff"]["raw_payload_included"] is False
        assert plan["source_of_truth_diff"]["redaction_state"] in {
            "metadata_only_no_raw_payload",
            "metadata_only_no_redacted_payload",
        }
        assert plan["check_mode"]["enabled"] is True
        assert "target_selector_resolves_single_surface" in plan["check_mode"]["checks"]
        assert plan["rollback"]["required"] is True
        assert plan["rollback"]["rollback_ref"].startswith(
            "rollback://ai-agent-log-feedback/"
        )
        assert plan["post_apply_verifier"]["required"] is True
        assert plan["post_apply_verifier"]["verifier_ref"].startswith(
            "post-write-verifier://ai-agent-log-feedback/"
        )

    p0_plans = [
        plan
        for plan in plans
        if plan["target_selector"]["source_sample_id"]
        == "p0_110_harbor_runner_control_path_sample"
    ]
    assert len(p0_plans) == 6
    assert {plan["target"] for plan in p0_plans} == set(target_rollups)
    assert {
        plan["current_blocker_recovery"]["blocker_id"] for plan in p0_plans
    } == {"controlled_cd_lane_guardrails_blocked"}
    assert {
        plan["current_blocker_recovery"]["project_id"] for plan in p0_plans
    } == {"awoooi"}
    assert {
        plan["current_blocker_recovery"]["service"] for plan in p0_plans
    } == {"awoooi-110-control-path"}
    assert {
        plan["current_blocker_recovery"]["package"] for plan in p0_plans
    } == {"ops/runner"}
    assert {
        plan["current_blocker_recovery"]["tool"] for plan in p0_plans
    } == {"read_public_gitea_queue_and_remote_control_classifier"}
    assert {
        plan["current_blocker_recovery"]["controlled_recovery_package"]
        for plan in p0_plans
    } == {"check-awoooi-110-controlled-cd-lane-readiness.sh"}
    assert {
        plan["current_blocker_recovery"]["post_apply_verifier"]
        for plan in p0_plans
    } == {"harbor-registry-controlled-recovery-receipt validator"}
    assert all(
        [
            phase["phase_id"]
            for phase in plan["current_blocker_recovery"][
                "controlled_local_console_execution_plan"
            ]
        ]
        == [
            "verify_ssh_control_path_restored",
            "verify_harbor_v2_ready",
            "verify_controlled_cd_lane_guardrails",
        ]
        for plan in p0_plans
    )
    assert all(
        plan["current_blocker_recovery"]["post_recovery_readback_commands"]
        == _expected_post_recovery_readback_commands(public_endpoint=public_endpoint)
        for plan in p0_plans
    )
    assert all(
        "read_or_print_authorized_keys"
        in plan["current_blocker_recovery"]["forbidden_runtime_actions"]
        for plan in p0_plans
    )
    assert all(
        plan["current_blocker_recovery"]["runtime_apply_required_on_110_local_console"]
        is False
        for plan in p0_plans
    )
    assert {
        plan["current_blocker_recovery"]["external_control_path_blocker"]
        for plan in p0_plans
    } == {""}

    boundaries = payload["operation_boundaries"]
    assert boundaries["plan_readback_only"] is True
    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_post_recovery_readback_commands(
    *, public_endpoint: bool = False
) -> list[str]:
    local_registry_readback = (
        "curl host:public-gateway/registry/v2/"
        if public_endpoint
        else "curl http://192.168.0.110:5000/v2/"
    )
    return [
        "check-awoooi-110-controlled-cd-lane-readiness.sh",
        "curl -k https://registry.wooo.work/v2/",
        local_registry_readback,
    ]
