import json
import logging
import os

import pytest

allure = pytest.importorskip("allure")

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


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


# ------------------------------------------------------------------------------
# Logger setup
# ------------------------------------------------------------------------------
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)


@pytest.fixture
def private_target_mode():
    previous_public_only = os.environ.get("AI_SWARM_PUBLIC_ONLY")
    os.environ["AI_SWARM_PUBLIC_ONLY"] = "0"
    try:
        yield
    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


@allure.feature("Cart APIs")
@allure.story("Cart Quickview – Item SKU")
@allure.severity(allure.severity_level.CRITICAL)
@pytest.mark.integration
@pytest.mark.skipif(not LIVE_TEST_ENABLED, reason="Live swarm test disabled (set AI_SWARM_RUN_LIVE_TESTS=1)")
@pytest.mark.skipif(not PRIVATE_TEST_ENABLED, reason="Private cart test disabled (set AI_SWARM_RUN_PRIVATE_TESTS=1)")
def test_cart_quickview_api_swarm(private_target_mode):
    """
    AI-powered swarm test for:
    GET /api/v1/users/carts/quickview

    PURPOSE:
    - Validate API robustness & security behavior
    - Validate swarm intelligence
    - NOT a deployment gate
    """

    # --------------------------------------------------------------------------
    # STEP 1: Prepare CURL
    # --------------------------------------------------------------------------
    with allure.step("Prepare input CURL"):
        curl = (
            "curl --location "
            "'https://api.wakefit.co/api/v1/users/carts/quickview"
            "?item_sku=WOMFM72305' "
            "--header 'Api-Token: c84d563b77441d784dce71323f69eb42' "
            "--header 'Api-Secret-Key: ycq55IbIjkLb' "
            "--header 'Content-Type: application/json' "
            "--header 'Guest-User-Id: fea09c9f-a7a2-48b1-a8bb-7f579e2e46'"
        )

        logger.info("📌 Input CURL prepared")
        allure.attach(curl, "Input CURL", allure.attachment_type.TEXT)

    # --------------------------------------------------------------------------
    # STEP 2: Parse CURL
    # --------------------------------------------------------------------------
    with allure.step("Parse CURL into structured request"):
        request = parse_curl(curl)

        logger.info("🔍 Parsed request")
        allure.attach(
            json.dumps(request, indent=2),
            "Parsed Request",
            allure.attachment_type.JSON,
        )

    # --------------------------------------------------------------------------
    # STEP 3: Run AI Testing Swarm
    # --------------------------------------------------------------------------
    with allure.step("Execute AI Testing Swarm"):
        logger.info("🤖 Running AI Swarm for Cart Quickview API")
        decision, results = SwarmOrchestrator().run(request)

        logger.info("🚦 Release Decision = %s", decision)
        allure.attach(decision, "Release Decision", allure.attachment_type.TEXT)

    # --------------------------------------------------------------------------
    # STEP 4: Attach raw swarm results
    # --------------------------------------------------------------------------
    with allure.step("Attach AI Swarm detailed results"):
        allure.attach(
            json.dumps(results, indent=2),
            "AI Swarm Results",
            allure.attachment_type.JSON,
        )

    # --------------------------------------------------------------------------
    # STEP 5: Human-readable summary
    # --------------------------------------------------------------------------
    with allure.step("Attach human-readable test summary"):
        summary = []
        for r in results:
            summary.append(
                f"{r['name']:30} | "
                f"HTTP={r['response']['status_code']} | "
                f"type={r['failure_type']}"
            )

        summary_text = "\n".join(summary)
        logger.info("🧪 Swarm Summary:\n%s", summary_text)

        allure.attach(
            summary_text,
            "AI Swarm Summary",
            allure.attachment_type.TEXT,
        )

    # --------------------------------------------------------------------------
    # STEP 6: 🧠 VALIDATE SWARM INTELLIGENCE (NOT DEPLOYMENT)
    # --------------------------------------------------------------------------
    with allure.step("Validate swarm reasoning and decisions"):

        # ------------------------------------------------------
        # 1️⃣ Happy path MUST exist and succeed
        # ------------------------------------------------------
        happy_path = next(
            (r for r in results if r.get("name") == "happy_path"),
            None,
        )

        assert happy_path is not None, "❌ Happy path test was not executed"

        status_code = happy_path.get("response", {}).get("status_code")
        if status_code is None:
            error = happy_path.get("response", {}).get("error", "Unknown network error")
            pytest.skip(f"Private endpoint unreachable from current network: {error}")

        assert status_code == 200, f"❌ Happy path failed with {status_code}"

        # ------------------------------------------------------
        # 2️⃣ Detect blocking failures (DO NOT FAIL TEST)
        # ------------------------------------------------------
        blocking_failures = [
            r for r in results
            if r["failure_type"] in {"security_risk", "infra", "auth_issue"}
        ]

        if blocking_failures:
            allure.dynamic.severity(allure.severity_level.NORMAL)

            allure.attach(
                json.dumps(blocking_failures, indent=2),
                "🚨 Blocking Failures Detected",
                allure.attachment_type.JSON,
            )

            for r in blocking_failures:
                allure.attach(
                    (
                        f"Test Name: {r['name']}\n"
                        f"Failure Type: {r['failure_type']}\n"
                        f"HTTP Status: {r['response']['status_code']}"
                    ),
                    f"🚨 {r['failure_type'].upper()} → {r['name']}",
                    allure.attachment_type.TEXT,
                )

            logger.warning(
                "🚨 Blocking failures detected (release correctly rejected): %s",
                [f"{r['name']}:{r['failure_type']}" for r in blocking_failures],
            )
        else:
            allure.dynamic.severity(allure.severity_level.CRITICAL)

        # ------------------------------------------------------
        # 3️⃣ Sanity check
        # ------------------------------------------------------
        assert results, "❌ No swarm tests executed"

        logger.info("✅ Swarm intelligence validated successfully")
