import os
from pathlib import Path

import pytest

from ai_testing_swarm.core.curl_parser import parse_curl
from ai_testing_swarm.orchestrator import SwarmOrchestrator


pytestmark = pytest.mark.integration

LIVE_TEST_ENABLED = os.getenv("AI_SWARM_RUN_LIVE_TESTS", "0").lower() in {"1", "true", "yes"}


@pytest.mark.skipif(not LIVE_TEST_ENABLED, reason="Live swarm test disabled (set AI_SWARM_RUN_LIVE_TESTS=1)")
def test_public_httpbin_anything_swarm_plain():
    previous_public_only = os.environ.get("AI_SWARM_PUBLIC_ONLY")
    os.environ["AI_SWARM_PUBLIC_ONLY"] = "1"

    try:
        curl = (
            "curl --location 'https://httpbin.org/anything/swarm-check?env=public' "
            "--header 'accept: application/json'"
        )

        request = parse_curl(curl)
        decision, results = SwarmOrchestrator().run(request)

        assert results, "No swarm tests executed"
        happy_path = next((r for r in results if r.get("name") == "happy_path"), None)
        assert happy_path is not None, "Happy path missing"
        assert decision in {"APPROVE_RELEASE", "APPROVE_RELEASE_WITH_RISKS", "REJECT_RELEASE"}

        reports_root = Path(__file__).resolve().parents[1] / "ai_swarm_reports"
        assert (reports_root / "index.html").exists()
        assert (reports_root / "GET_swarm-check" / "latest.html").exists()
        assert (reports_root / "GET_swarm-check" / "history.json").exists()

        status_code = happy_path.get("response", {}).get("status_code")
        if status_code is None:
            err = happy_path.get("response", {}).get("error", "network error")
            pytest.skip(f"Public endpoint unreachable from current network: {err}")
        assert status_code == 200
    finally:
        if previous_public_only is None:
            os.environ.pop("AI_SWARM_PUBLIC_ONLY", None)
        else:
            os.environ["AI_SWARM_PUBLIC_ONLY"] = previous_public_only
