import logging
import os

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"}
PRIVATE_TEST_ENABLED = os.getenv("AI_SWARM_RUN_PRIVATE_TESTS", "0").lower() in {"1", "true", "yes"}


logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)


OFFERS_LIST_CURL = (
    "curl --location "
    "'https://api.wakefit.co/api/offers/WOMFM72366/list' "
    "--header 'authority: api.wakefit.co' "
    "--header 'accept: application/json, text/plain, */*' "
    "--header 'accept-language: en-GB,en-US;q=0.9,en;q=0.8' "
    "--header 'api-secret-key: ycq55IbIjkLb' "
    "--header 'api-token: c84d563b77441d784dce71323f69eb42' "
    "--header 'content-type: application/json' "
    "--header 'my-cookie: undefined' "
    "--header 'origin: https://www.wakefit.co' "
    "--header 'referer: https://www.wakefit.co/' "
    "--header 'sec-ch-ua: \"Chromium\";v=\"110\", \"Not A(Brand\";v=\"24\", \"Google Chrome\";v=\"110\"' "
    "--header 'sec-ch-ua-mobile: ?0' "
    "--header 'sec-ch-ua-platform: \"macOS\"' "
    "--header 'sec-fetch-dest: empty' "
    "--header 'sec-fetch-mode: cors' "
    "--header 'sec-fetch-site: same-site' "
    "--header 'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
    "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36'"
)


@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


@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 offers test disabled (set AI_SWARM_RUN_PRIVATE_TESTS=1)")
def test_offers_list_api_swarm_plain(private_target_mode):
    """Plain pytest version of offers-list swarm test (no Allure dependency)."""
    request = parse_curl(OFFERS_LIST_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 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"Expected happy path HTTP 200, got {status_code}"
    assert decision in {"APPROVE_RELEASE", "APPROVE_RELEASE_WITH_RISKS", "REJECT_RELEASE"}

    summary_lines = [
        f"{r.get('name'):35} | HTTP={r.get('response', {}).get('status_code')} | type={r.get('failure_type')}"
        for r in results
    ]
    logger.info("Offers List swarm summary:\n%s", "\n".join(summary_lines))
