import json
from pathlib import Path

import pytest

from ai_testing_swarm.core.auth_matrix import load_auth_matrix, merge_auth_headers, AuthCase
from ai_testing_swarm.core.risk import compute_test_risk_score
from ai_testing_swarm.reporting.trend import compute_trend


def test_strategy_aware_risk_security_risk_is_100():
    r = {
        "failure_type": "security_risk",
        "status": "FAILED",
        "mutation": {"strategy": "security"},
        "response": {"status_code": 200, "elapsed_ms": 10, "openapi_validation": []},
    }
    assert compute_test_risk_score(r) == 100


def test_strategy_aware_risk_validation_bypass_is_high():
    r = {
        "failure_type": "missing_param_accepted",
        "status": "RISK",
        "mutation": {"strategy": "missing_param"},
        "response": {"status_code": 200, "elapsed_ms": 10, "openapi_validation": []},
    }
    assert compute_test_risk_score(r) >= 80


def test_compute_trend_regressions_detected():
    prev = {
        "meta": {"endpoint_risk_score": 10},
        "results": [
            {"name": "happy_path", "status": "PASSED", "risk_score": 0},
            {"name": "sec_probe", "status": "RISK", "risk_score": 35},
        ],
    }
    cur = {
        "meta": {"endpoint_risk_score": 90},
        "results": [
            {"name": "happy_path", "status": "FAILED", "risk_score": 70},
            {"name": "sec_probe", "status": "RISK", "risk_score": 60},
        ],
    }
    t = compute_trend(cur, prev)
    assert t["has_previous"] is True
    assert t["endpoint_risk_prev"] == 10
    assert t["endpoint_risk_delta"] == 80
    assert t["regression_count"] == 2


def test_auth_matrix_load_and_merge(tmp_path: Path):
    p = tmp_path / "auth.json"
    p.write_text(
        json.dumps(
            {
                "cases": [
                    {"name": "user", "headers": {"Authorization": "Bearer U"}},
                    {"name": "admin", "headers": {"Authorization": "Bearer A"}},
                ]
            }
        ),
        encoding="utf-8",
    )

    cases = load_auth_matrix(p)
    assert [c.name for c in cases] == ["user", "admin"]

    req = {"method": "GET", "url": "https://example.com", "headers": {"X": "1"}}
    req2 = merge_auth_headers(req, cases[0])
    assert req2["headers"]["X"] == "1"
    assert req2["headers"]["Authorization"] == "Bearer U"
