from __future__ import annotations

import json
from pathlib import Path

from fastapi import FastAPI
from fastapi.testclient import TestClient

from src.api.v1.agents import router
from src.services.awoooi_gitea_onboarding_warning_step_dashboard import (
    load_latest_awoooi_gitea_onboarding_warning_step_dashboard,
)
from src.services.awoooi_gitea_onboarding_warning_step_owner_package import (
    load_latest_awoooi_gitea_onboarding_warning_step_owner_package,
)
from src.services.awoooi_gitea_onboarding_warning_step_owner_response_preflight import (
    load_latest_awoooi_gitea_onboarding_warning_step_owner_response_preflight,
)
from src.services.awoooi_gitea_onboarding_warning_step_runtime_enablement_gate import (
    load_latest_awoooi_gitea_onboarding_warning_step_runtime_enablement_gate,
)
from src.services.awoooi_gitea_onboarding_warning_step_template_copy_apply_gate import (
    load_latest_awoooi_gitea_onboarding_warning_step_template_copy_apply_gate,
)
from src.services.awoooi_gitea_onboarding_warning_step_template_copy_execution_plan import (
    load_latest_awoooi_gitea_onboarding_warning_step_template_copy_execution_plan,
)
from src.services.awoooi_gitea_onboarding_warning_step_template_copy_receipt import (
    load_latest_awoooi_gitea_onboarding_warning_step_template_copy_receipt,
)
from src.services.awoooi_new_product_onboarding_page_model import (
    load_latest_awoooi_new_product_onboarding_page_model,
)
from src.services.awoooi_onboarding_reminder_contract import (
    load_latest_awoooi_onboarding_reminder_contract,
)
from src.services.awoooi_product_onboarding_guard import (
    load_latest_awoooi_product_onboarding_guard,
)
from src.services.p0_cicd_baseline_source_readiness import (
    load_latest_p0_cicd_baseline_source_readiness,
)

_REPO_ROOT = Path(__file__).resolve().parents[3]
_SNAPSHOT_PATH = (
    _REPO_ROOT
    / "docs"
    / "operations"
    / "p0-cicd-baseline-source-readiness.snapshot.json"
)
_RECEIPT_SNAPSHOT_PATH = (
    _REPO_ROOT
    / "docs"
    / "operations"
    / "awoooi-gitea-onboarding-warning-step-template-copy-receipt.snapshot.json"
)
_WARNING_STEP_TEMPLATE_PATH = (
    _REPO_ROOT
    / "docs"
    / "operations"
    / "templates"
    / "awoooi-gitea-onboarding-warning-step.workflow.yaml"
)
_WARNING_STEP_WORKFLOW_PATH = (
    _REPO_ROOT
    / ".gitea"
    / "workflows"
    / "awoooi-onboarding-warning-step.yaml"
)


def test_p0_cicd_baseline_source_readiness_loader_reports_ready_sources():
    payload = load_latest_p0_cicd_baseline_source_readiness()

    assert payload["schema_version"] == "p0_cicd_baseline_source_readiness_v1"
    assert payload["status"] == "ready_for_template_copy_apply_gate"
    assert payload["priority"] == "P0-004"
    assert payload["readback"]["workplan_id"] == "P0-004"
    assert payload["readback"]["scorecard_completion_percent"] == 60
    assert payload["rollups"]["required_source_count"] == 11
    assert payload["rollups"]["present_required_source_count"] == 11
    assert payload["rollups"]["missing_required_source_count"] == 0
    assert payload["rollups"]["source_readiness_percent"] == 100
    assert payload["rollups"]["blocked_source_ids"] == []
    assert payload["operation_boundaries"]["read_only_api_allowed"] is True
    assert payload["operation_boundaries"]["workflow_modification_allowed"] is False
    assert payload["operation_boundaries"]["workflow_trigger_allowed"] is False
    assert payload["operation_boundaries"]["github_api_allowed"] is False
    assert payload["operation_boundaries"]["secret_read_allowed"] is False


def test_p0_cicd_baseline_source_readiness_supports_runtime_image_layout(tmp_path):
    operations_dir = tmp_path / "docs" / "operations"
    operations_dir.mkdir(parents=True)
    payload = json.loads(_SNAPSHOT_PATH.read_text(encoding="utf-8"))
    (operations_dir / _SNAPSHOT_PATH.name).write_text(
        json.dumps(payload),
        encoding="utf-8",
    )

    for source in payload["required_sources"]:
        relative_path = source["path"]
        if relative_path.startswith("apps/api/"):
            runtime_path = tmp_path / relative_path.removeprefix("apps/api/")
            runtime_path.parent.mkdir(parents=True, exist_ok=True)
            runtime_path.write_text("# runtime image source\n", encoding="utf-8")
        else:
            repo_path = tmp_path / relative_path
            repo_path.parent.mkdir(parents=True, exist_ok=True)
            repo_path.write_text("{}", encoding="utf-8")

    data = load_latest_p0_cicd_baseline_source_readiness(operations_dir)

    assert data["status"] == "ready_for_template_copy_apply_gate"
    assert data["rollups"]["present_required_source_count"] == 11
    assert data["rollups"]["missing_required_source_count"] == 0
    assert data["rollups"]["blocked_source_ids"] == []


def test_recreated_onboarding_sources_open_only_controlled_template_copy_gate():
    response = {
        "accept_warning_only_scope": True,
        "confirm_no_push_or_pull_request_trigger": True,
        "confirm_no_generic_runner_label": True,
        "confirm_runner_pressure_guard_required": True,
    }
    payloads = [
        load_latest_awoooi_gitea_onboarding_warning_step_owner_package(),
        load_latest_awoooi_gitea_onboarding_warning_step_owner_response_preflight(
            response
        ),
        load_latest_awoooi_gitea_onboarding_warning_step_template_copy_execution_plan(),
        load_latest_awoooi_gitea_onboarding_warning_step_template_copy_apply_gate(),
        load_latest_awoooi_gitea_onboarding_warning_step_dashboard(),
        load_latest_awoooi_product_onboarding_guard(),
        load_latest_awoooi_onboarding_reminder_contract(),
        load_latest_awoooi_new_product_onboarding_page_model(),
    ]

    assert (
        payloads[1]["readback"]["accepted_acknowledgement_count"]
        == payloads[1]["readback"]["required_acknowledgement_count"]
    )
    assert payloads[1]["readback"]["ready_for_template_copy_plan"] is True
    execution_plan = payloads[2]
    assert execution_plan["status"] == "controlled_template_copy_execution_plan_ready"
    assert (
        execution_plan["readback"]["execution_status"]
        == "ready_for_controlled_template_copy"
    )
    assert execution_plan["readback"]["dry_run_only"] is False
    assert (
        execution_plan["readback"]["source_template_path"]
        == "docs/operations/templates/"
        "awoooi-gitea-onboarding-warning-step.workflow.yaml"
    )
    assert (
        execution_plan["readback"]["destination_workflow_path"]
        == ".gitea/workflows/awoooi-onboarding-warning-step.yaml"
    )
    assert execution_plan["readback"]["forbidden_events"] == [
        "push",
        "pull_request",
        "pull_request_target",
    ]
    assert execution_plan["readback"]["allowed_runner_labels"] == [
        "awoooi-non110-host"
    ]
    assert (
        execution_plan["operation_boundaries"]["workflow_modification_allowed"]
        is False
    )
    apply_gate = payloads[3]
    assert apply_gate["status"] == "controlled_template_copy_apply_gate_ready"
    assert apply_gate["readback"]["apply_allowed"] is True
    assert apply_gate["readback"]["workflow_template_copy_authorized"] is True
    assert apply_gate["readback"]["workflow_trigger_authorized"] is False
    assert (
        apply_gate["readback"]["auto_push_or_pull_request_trigger_authorized"]
        is False
    )
    assert apply_gate["readback"]["generic_runner_label_authorized"] is False
    assert apply_gate["readback"]["runner_pressure_guard_required"] is True
    assert apply_gate["operation_boundaries"]["workflow_modification_allowed"] is True
    assert apply_gate["operation_boundaries"]["workflow_trigger_allowed"] is False
    assert (
        apply_gate["operation_boundaries"][
            "auto_push_or_pull_request_trigger_allowed"
        ]
        is False
    )
    assert apply_gate["operation_boundaries"]["generic_runner_label_allowed"] is False

    for payload in payloads[:3] + payloads[4:]:
        boundaries = payload["operation_boundaries"]
        assert boundaries["read_only_api_allowed"] is True
        assert boundaries["workflow_modification_allowed"] is False
        assert boundaries["workflow_trigger_allowed"] is False
        assert boundaries["github_api_allowed"] is False
        assert boundaries["host_or_k8s_write_allowed"] is False
        assert boundaries["secret_read_allowed"] is False


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

    response = client.get("/api/v1/agents/p0-cicd-baseline-source-readiness")

    assert response.status_code == 200
    data = response.json()
    assert data["schema_version"] == "p0_cicd_baseline_source_readiness_v1"
    assert data["status"] == "ready_for_template_copy_apply_gate"
    assert data["rollups"]["missing_required_source_count"] == 0
    assert data["operation_boundaries"]["workflow_modification_allowed"] is False


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

    response = client.get(
        "/api/v1/agents/"
        "awoooi-gitea-onboarding-warning-step-template-copy-execution-plan"
    )

    assert response.status_code == 200
    data = response.json()
    assert (
        data["schema_version"]
        == "awoooi_gitea_onboarding_warning_step_template_copy_execution_plan_v1"
    )
    assert data["status"] == "controlled_template_copy_execution_plan_ready"
    assert (
        data["readback"]["execution_status"]
        == "ready_for_controlled_template_copy"
    )
    assert data["readback"]["dry_run_only"] is False
    assert data["readback"]["template_runtime_default"] == "fail_closed_job_disabled"
    assert data["operation_boundaries"]["workflow_trigger_allowed"] is False


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

    response = client.get(
        "/api/v1/agents/"
        "awoooi-gitea-onboarding-warning-step-template-copy-apply-gate"
    )

    assert response.status_code == 200
    data = response.json()
    assert (
        data["schema_version"]
        == "awoooi_gitea_onboarding_warning_step_template_copy_apply_gate_v1"
    )
    assert data["status"] == "controlled_template_copy_apply_gate_ready"
    assert data["readback"]["apply_allowed"] is True
    assert data["readback"]["workflow_template_copy_authorized"] is True
    assert data["readback"]["workflow_trigger_authorized"] is False
    assert data["operation_boundaries"]["workflow_modification_allowed"] is True
    assert data["operation_boundaries"]["workflow_trigger_allowed"] is False


def test_warning_step_template_copy_is_fail_closed_and_pressure_guarded():
    template = _WARNING_STEP_TEMPLATE_PATH.read_text(encoding="utf-8")
    workflow = _WARNING_STEP_WORKFLOW_PATH.read_text(encoding="utf-8")

    assert workflow == template
    for forbidden in [
        "push:",
        "pull_request:",
        "pull_request_target:",
        "awoooi-host",
        "awoooi-ubuntu",
        "ubuntu-latest",
        "self-hosted",
    ]:
        assert forbidden not in workflow

    assert "workflow_dispatch:" in workflow
    assert "workflow-shape:" in workflow
    assert "Confirm controlled warning-step workflow shape" in workflow
    assert "runs-on: awoooi-non110-host" in workflow
    assert 'AWOOOI_ONBOARDING_WARNING_STEP_EXECUTION_ENABLED: "1"' in workflow
    assert "ops/runner/guard-gitea-runner-pressure.py --root ." in workflow


def test_template_copy_receipt_loader_confirms_template_copy():
    payload = load_latest_awoooi_gitea_onboarding_warning_step_template_copy_receipt()

    _assert_template_copy_receipt(payload)
    assert payload["rollups"]["runtime_image_workflow_file_present"] is True
    assert payload["rollups"]["workflow_file_visible_in_runtime_image"] is True


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

    response = client.get(
        "/api/v1/agents/"
        "awoooi-gitea-onboarding-warning-step-template-copy-receipt"
    )

    assert response.status_code == 200
    _assert_template_copy_receipt(response.json())


def test_template_copy_receipt_supports_runtime_image_layout(tmp_path):
    template_path = (
        tmp_path
        / "docs"
        / "operations"
        / "templates"
        / "awoooi-gitea-onboarding-warning-step.workflow.yaml"
    )
    template_path.parent.mkdir(parents=True)
    template_path.write_text(
        _WARNING_STEP_TEMPLATE_PATH.read_text(encoding="utf-8"),
        encoding="utf-8",
    )
    receipt_path = tmp_path / "docs" / "operations" / _RECEIPT_SNAPSHOT_PATH.name
    receipt_path.write_text(
        _RECEIPT_SNAPSHOT_PATH.read_text(encoding="utf-8"),
        encoding="utf-8",
    )

    payload = load_latest_awoooi_gitea_onboarding_warning_step_template_copy_receipt(
        tmp_path
    )

    _assert_template_copy_receipt(payload)
    assert payload["readback"]["workflow_content_source"] == (
        "packaged_template_digest_fallback"
    )
    assert payload["rollups"]["runtime_image_workflow_file_present"] is False
    assert payload["rollups"]["workflow_file_visible_in_runtime_image"] is False
    assert payload["operation_boundaries"]["runtime_image_workflow_file_present"] is False
    assert (
        payload["operation_boundaries"]["active_workflow_file_visible_in_runtime_image"]
        is False
    )


def test_warning_step_runtime_enablement_gate_loader_returns_controlled_package():
    payload = load_latest_awoooi_gitea_onboarding_warning_step_runtime_enablement_gate()

    _assert_runtime_enablement_gate(payload)


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

    response = client.get(
        "/api/v1/agents/"
        "awoooi-gitea-onboarding-warning-step-runtime-enablement-gate"
    )

    assert response.status_code == 200
    _assert_runtime_enablement_gate(response.json())


def _assert_template_copy_receipt(payload: dict):
    assert (
        payload["schema_version"]
        == "awoooi_gitea_onboarding_warning_step_template_copy_receipt_v1"
    )
    assert payload["priority"] == "P0-004"
    assert payload["status"] == "controlled_template_copy_receipt_ready"
    assert payload["active_blockers"] == []
    assert payload["readback"]["template_copy_performed"] is True
    assert payload["readback"]["workflow_content_sha256_12"] == "980ff5452f59"
    assert payload["target_selector"]["active_workflow_file_created"] is True
    assert payload["rollups"]["template_file_present"] is True
    assert payload["rollups"]["receipt_snapshot_present"] is True
    assert payload["rollups"]["workflow_file_present"] is True
    assert payload["rollups"]["workflow_matches_template"] is True
    assert payload["rollups"]["auto_branch_event_count"] == 0
    assert payload["rollups"]["generic_runner_label_count"] == 0
    assert payload["rollups"]["expected_workflow_sha256_12"] == "980ff5452f59"
    assert payload["rollups"]["fail_closed_execution_switch_present"] is False
    assert payload["rollups"]["runtime_execution_switch_controlled"] is True
    assert payload["rollups"]["runtime_execution_switch_value"] == "1"
    assert payload["rollups"]["runtime_execution_switch_enabled"] is True
    assert payload["rollups"]["runtime_enablement_switch_changed"] is True
    assert payload["rollups"]["runtime_enablement_switch_present"] is True
    assert payload["rollups"]["runtime_execution_enabled"] is True
    assert payload["rollups"]["apply_gate_ready"] is True
    assert payload["rollups"]["workflow_trigger_performed"] is False
    assert payload["operation_boundaries"]["controlled_template_copy_only"] is True
    assert payload["operation_boundaries"]["active_workflow_file_created"] is True
    assert payload["operation_boundaries"]["workflow_trigger_performed"] is False
    assert payload["operation_boundaries"]["github_api_used"] is False
    assert payload["operation_boundaries"]["secret_value_collection_allowed"] is False
    assert payload["operation_boundaries"]["raw_session_or_sqlite_read_allowed"] is False


def _assert_runtime_enablement_gate(payload: dict):
    assert (
        payload["schema_version"]
        == "awoooi_gitea_onboarding_warning_step_runtime_enablement_gate_v1"
    )
    assert payload["priority"] == "P0-004"
    assert payload["scope"] == "gitea_onboarding_warning_step_runtime_enablement"
    assert payload["status"] == "controlled_warning_step_runtime_enabled"
    assert payload["active_blockers"] == []
    assert payload["readback"]["source_receipt_status"] == (
        "controlled_template_copy_receipt_ready"
    )
    assert payload["readback"]["runtime_enablement_switch"] == (
        "AWOOOI_ONBOARDING_WARNING_STEP_EXECUTION_ENABLED"
    )
    assert payload["readback"]["previous_switch_value_before_controlled_apply"] == "0"
    assert payload["readback"]["current_switch_default"] == "1"
    assert payload["readback"]["desired_switch_value_after_controlled_apply"] == "1"
    assert payload["controlled_apply"]["controlled_apply_allowed"] is True
    assert payload["controlled_apply"]["controlled_apply_completed"] is True
    assert payload["controlled_apply"]["workflow_runtime_enablement_authorized"] is True
    assert payload["controlled_apply"]["workflow_dispatch_authorized"] is False
    assert payload["controlled_apply"]["auto_push_or_pull_request_trigger_authorized"] is False
    assert payload["controlled_apply"]["generic_runner_label_authorized"] is False
    assert payload["target_selector"]["env_key"] == (
        "AWOOOI_ONBOARDING_WARNING_STEP_EXECUTION_ENABLED"
    )
    assert payload["target_selector"]["previous_expected_value_before_controlled_apply"] == "0"
    assert payload["target_selector"]["expected_current_value"] == "1"
    assert payload["target_selector"]["desired_value_after_controlled_apply"] == "1"
    assert payload["source_of_truth_diff"]["delta_kind"] == "env_switch_value_change"
    assert payload["check_mode"]["enabled"] is True
    assert payload["rollback"]["required"] is True
    assert payload["post_apply_verifier"]["required"] is True
    assert payload["rollups"]["template_copy_receipt_ready"] is True
    assert payload["rollups"]["controlled_runtime_enablement_ready"] is True
    assert payload["rollups"]["fail_closed_execution_switch_present"] is False
    assert payload["rollups"]["runtime_execution_switch_controlled"] is True
    assert payload["rollups"]["runtime_execution_switch_value"] == "1"
    assert payload["rollups"]["runtime_execution_switch_enabled"] is True
    assert payload["rollups"]["runtime_enablement_switch_present"] is True
    assert payload["rollups"]["runtime_execution_enabled"] is True
    assert payload["rollups"]["active_blocker_count"] == 0
    assert payload["rollups"]["workflow_trigger_performed"] is False
    assert payload["rollups"]["runtime_switch_changed"] is True
    assert payload["operation_boundaries"]["readback_only"] is True
    assert payload["operation_boundaries"]["controlled_runtime_enablement_gate_open"] is True
    assert payload["operation_boundaries"]["workflow_file_modified_by_this_endpoint"] is False
    assert payload["operation_boundaries"]["workflow_trigger_performed"] is False
    assert payload["operation_boundaries"]["github_api_used"] is False
    assert payload["operation_boundaries"]["secret_value_collection_allowed"] is False
