import json
import re
from pathlib import Path

from ai_testing_swarm.reporting import report_writer


def test_report_writer_redacts_nested_sensitive_data(tmp_path, monkeypatch):
    monkeypatch.setattr(report_writer, "REPORTS_DIR", tmp_path)
    monkeypatch.setenv("AI_SWARM_REDACT_ENABLED", "1")
    monkeypatch.setenv("AI_SWARM_REDACT_KEYS", "customerEmail")

    request = {"method": "POST", "url": "https://example.com/login"}
    results = [
        {
            "name": "happy_path",
            "failure_type": "success",
            "request": {
                "headers": {"Authorization": "Bearer abc"},
                "params": {"token": "abc123"},
                "body": {"profile": {"customerEmail": "a@b.com", "password": "secret"}},
            },
            "response": {
                "status_code": 200,
                "elapsed_ms": 50,
                "body_snippet": {"access_token": "tok", "data": {"ok": True}},
            },
            "status": "PASSED",
        }
    ]

    report_path = Path(report_writer.write_report(request, results, meta={"decision": "APPROVE_RELEASE"}))
    report_data = json.loads(report_path.read_text(encoding="utf-8"))

    redacted = report_data["results"][0]
    assert redacted["request"]["headers"]["Authorization"] == "***REDACTED***"
    assert redacted["request"]["params"]["token"] == "***REDACTED***"
    assert redacted["request"]["body"]["profile"]["customerEmail"] == "***REDACTED***"
    assert redacted["request"]["body"]["profile"]["password"] == "***REDACTED***"
    assert redacted["response"]["body_snippet"]["access_token"] == "***REDACTED***"

    artifacts = report_data["meta"]["artifacts"]
    assert Path(artifacts["json_report"]).exists()
    assert Path(artifacts["html_report"]).exists()
    assert Path(artifacts["latest_html_report"]).exists()
    assert Path(artifacts["dashboard_html"]).exists()
    assert Path(artifacts["history_file"]).exists()
    assert "risk_score" in report_data["summary"]

    endpoint_html = Path(artifacts["html_report"]).read_text(encoding="utf-8")
    assert "AI Testing Swarm Report" in endpoint_html
    assert "Mutation Scenario" in endpoint_html
    assert "Final cURL" in endpoint_html
    assert "Copy cURL" in endpoint_html


def test_report_writer_redaction_is_off_by_default(tmp_path, monkeypatch):
    monkeypatch.setattr(report_writer, "REPORTS_DIR", tmp_path)
    monkeypatch.delenv("AI_SWARM_REDACT_ENABLED", raising=False)
    monkeypatch.delenv("AI_SWARM_ENABLE_REDACTION", raising=False)

    request = {"method": "POST", "url": "https://example.com/login"}
    results = [
        {
            "name": "happy_path",
            "failure_type": "success",
            "request": {
                "headers": {"Authorization": "Bearer abc"},
                "params": {"token": "abc123"},
                "body": {"profile": {"customerEmail": "a@b.com", "password": "secret"}},
            },
            "response": {
                "status_code": 200,
                "elapsed_ms": 50,
                "body_snippet": {"access_token": "tok", "data": {"ok": True}},
            },
            "status": "PASSED",
        }
    ]

    report_path = Path(report_writer.write_report(request, results, meta={"decision": "APPROVE_RELEASE"}))
    report_data = json.loads(report_path.read_text(encoding="utf-8"))
    payload = report_data["results"][0]

    assert payload["request"]["headers"]["Authorization"] == "Bearer abc"
    assert payload["request"]["params"]["token"] == "abc123"
    assert payload["request"]["body"]["profile"]["password"] == "secret"
    assert payload["response"]["body_snippet"]["access_token"] == "tok"

    pii = report_data["summary"]["pii_audit"]
    assert pii["compliance_status"] == "DISABLED"
    assert pii["redaction_hits"] == 0


def test_report_writer_keeps_history_and_delta(tmp_path, monkeypatch):
    monkeypatch.setattr(report_writer, "REPORTS_DIR", tmp_path)
    monkeypatch.setenv("AI_SWARM_REPORT_HISTORY_LIMIT", "10")

    request = {"method": "GET", "url": "https://example.com/orders"}

    healthy_results = [
        {
            "name": "happy_path",
            "failure_type": "success",
            "status": "PASSED",
            "response": {"status_code": 200, "elapsed_ms": 30},
            "request": {"headers": {}, "params": {}, "body": None},
        }
    ]
    risky_results = [
        {
            "name": "happy_path",
            "failure_type": "unknown",
            "status": "FAILED",
            "response": {"status_code": None, "elapsed_ms": 40, "error": "DNS failure"},
            "request": {"headers": {}, "params": {}, "body": None},
        }
    ]

    first_report = Path(
        report_writer.write_report(request, healthy_results, meta={"decision": "APPROVE_RELEASE"})
    )
    second_report = Path(
        report_writer.write_report(request, risky_results, meta={"decision": "APPROVE_RELEASE_WITH_RISKS"})
    )

    history = json.loads((tmp_path / "GET_orders" / "history.json").read_text(encoding="utf-8"))
    assert len(history) == 2
    assert history[-1]["unknown_count"] >= history[0]["unknown_count"]

    second_data = json.loads(second_report.read_text(encoding="utf-8"))
    assert "delta_vs_previous" in second_data["summary"]
    assert second_data["summary"]["counts_by_failure_type"]["unknown"] == 1

    dashboard_html = (tmp_path / "index.html").read_text(encoding="utf-8")
    assert "GET_orders" in dashboard_html
    assert first_report.exists()


def test_report_writer_renders_mutation_details_and_final_curl(tmp_path, monkeypatch):
    monkeypatch.setattr(report_writer, "REPORTS_DIR", tmp_path)

    request = {"method": "POST", "url": "https://example.com/orders"}
    results = [
        {
            "name": "security_query_sku_1",
            "failure_type": "validation",
            "status": "FAILED",
            "mutation": {
                "strategy": "security",
                "target": "query",
                "operation": "REPLACE",
                "path": ["sku"],
                "original_value": "SKU123",
                "new_value": "' OR 1=1 --",
            },
            "request": {
                "method": "POST",
                "url": "https://example.com/orders",
                "headers": {"content-type": "application/json"},
                "params": {"sku": "' OR 1=1 --"},
                "body": {"hello": "world"},
            },
            "response": {"status_code": 400, "elapsed_ms": 22, "attempt": 1},
        },
        {
            "name": "remove_optional_field",
            "failure_type": "unknown",
            "status": "FAILED",
            "mutation": {
                "strategy": "schema",
                "target": "body",
                "operation": "REMOVE",
                "path": ["email"],
                "original_value": "qa@example.com",
            },
            "request": {
                "method": "POST",
                "url": "https://example.com/orders",
                "headers": {"content-type": "application/json"},
                "params": {},
                "body": {"name": "qa"},
            },
            "response": {"status_code": 422, "elapsed_ms": 30, "attempt": 1},
        },
        {
            "name": "add_debug_flag",
            "failure_type": "security",
            "status": "FAILED",
            "mutation": {
                "strategy": "auth",
                "target": "headers",
                "operation": "ADD",
                "path": ["x-debug"],
                "new_value": "1",
            },
            "request": {
                "method": "POST",
                "url": "https://example.com/orders",
                "headers": {"content-type": "application/json", "x-debug": "1"},
                "params": {},
                "body": {"name": "qa"},
            },
            "response": {"status_code": 403, "elapsed_ms": 18, "attempt": 1},
        },
    ]

    report_path = Path(report_writer.write_report(request, results, meta={"decision": "REJECT_RELEASE"}))
    report_data = json.loads(report_path.read_text(encoding="utf-8"))
    endpoint_html = Path(report_data["meta"]["artifacts"]["html_report"]).read_text(encoding="utf-8")

    assert "Replaced `sku` in `query`." in endpoint_html
    assert "Removed `email` from `body`." in endpoint_html
    assert "Added `x-debug` in `headers`." in endpoint_html
    assert "Copy cURL" in endpoint_html
    assert "--request POST" in endpoint_html
    assert "content-type: application/json" in endpoint_html
    assert "--data-raw" in endpoint_html
    assert "hello" in endpoint_html
    assert "world" in endpoint_html
    assert "payload-view-btn" in endpoint_html
    assert "id=\"payloadModal\"" in endpoint_html
    assert "Payload Viewer" in endpoint_html
    assert "metric-card metric-critical" in endpoint_html
    assert "metric-card metric-info" in endpoint_html
    assert "metric-card metric-success" in endpoint_html


def test_dashboard_sorts_endpoints_by_latest_run_desc(tmp_path, monkeypatch):
    monkeypatch.setattr(report_writer, "REPORTS_DIR", tmp_path)

    older_endpoint = tmp_path / "GET_older"
    newer_endpoint = tmp_path / "GET_newer"
    older_endpoint.mkdir(parents=True, exist_ok=True)
    newer_endpoint.mkdir(parents=True, exist_ok=True)

    (older_endpoint / "history.json").write_text(
        json.dumps(
            [
                {
                    "run_time": "20260221_101010",
                    "decision": "APPROVE_RELEASE",
                    "risk_score": 10,
                    "risk_grade": "LOW",
                    "unknown_count": 0,
                    "blocking_count": 0,
                },
                {
                    "run_time": "20260221_111010",
                    "decision": "APPROVE_RELEASE",
                    "risk_score": 20,
                    "risk_grade": "LOW",
                    "unknown_count": 0,
                    "blocking_count": 0,
                },
            ],
            indent=2,
        ),
        encoding="utf-8",
    )

    (newer_endpoint / "history.json").write_text(
        json.dumps(
            [
                {
                    "run_time": "20260221_131010",
                    "decision": "REJECT_RELEASE",
                    "risk_score": 88,
                    "risk_grade": "CRITICAL",
                    "unknown_count": 2,
                    "blocking_count": 1,
                },
                {
                    "run_time": "20260221_141010",
                    "decision": "APPROVE_RELEASE_WITH_RISKS",
                    "risk_score": 65,
                    "risk_grade": "HIGH",
                    "unknown_count": 1,
                    "blocking_count": 0,
                },
                {
                    "run_time": "20260221_151010",
                    "decision": "REJECT_RELEASE",
                    "risk_score": 90,
                    "risk_grade": "CRITICAL",
                    "unknown_count": 3,
                    "blocking_count": 2,
                },
            ],
            indent=2,
        ),
        encoding="utf-8",
    )

    dashboard_path = Path(report_writer._update_project_dashboard())
    dashboard_html = dashboard_path.read_text(encoding="utf-8")

    assert dashboard_html.index("GET_newer") < dashboard_html.index("GET_older")
    assert "<strong>History Runs:</strong> 3" in dashboard_html
    assert "<strong>History Runs:</strong> 2" in dashboard_html


def test_dashboard_uses_effective_decision_fallback_for_legacy_history(tmp_path, monkeypatch):
    monkeypatch.setattr(report_writer, "REPORTS_DIR", tmp_path)

    endpoint = tmp_path / "GET_legacy"
    endpoint.mkdir(parents=True, exist_ok=True)
    (endpoint / "history.json").write_text(
        json.dumps(
            [
                {
                    "run_time": "20260221_161929",
                    "decision": "REJECT_RELEASE",
                    "risk_score": 100,
                    "risk_grade": "CRITICAL",
                    "total_tests": 26,
                    "pass_count": 15,
                    "manual_pass_count": 11,
                    "fail_count": 0,
                    "unknown_count": 0,
                    "blocking_count": 6,
                }
            ],
            indent=2,
        ),
        encoding="utf-8",
    )

    dashboard_html = Path(report_writer._update_project_dashboard()).read_text(encoding="utf-8")
    assert "GET_legacy" in dashboard_html
    assert "APPROVE_RELEASE" in dashboard_html
    assert "(orig: REJECT_RELEASE)" in dashboard_html
    assert "<strong>Risk:</strong> 0 (LOW)" in dashboard_html


def test_report_writer_renders_enterprise_features(tmp_path, monkeypatch):
    monkeypatch.setattr(report_writer, "REPORTS_DIR", tmp_path)
    monkeypatch.setenv("AI_SWARM_POLICY_PROFILE", "prod")
    monkeypatch.setenv("AI_SWARM_OWNER_MAP", "POST_orders=platform-api")
    monkeypatch.setenv(
        "AI_SWARM_JIRA_URL_TEMPLATE",
        "https://jira.example.local/create?summary={summary}&description={description}",
    )
    monkeypatch.setenv(
        "AI_SWARM_SLACK_URL_TEMPLATE",
        "https://slack.example.local/alert?text={summary}",
    )

    request = {"method": "POST", "url": "https://example.com/orders"}
    run1_results = [
        {
            "name": "happy_path",
            "failure_type": "success",
            "status": "PASSED",
            "mutation": None,
            "request": {
                "method": "POST",
                "url": "https://example.com/orders",
                "headers": {"Authorization": "Bearer run1-token", "content-type": "application/json"},
                "params": {},
                "body": {"email": "qa1@example.com", "qty": 1},
            },
            "response": {"status_code": 200, "elapsed_ms": 40, "attempt": 1},
        },
        {
            "name": "sku_guard",
            "failure_type": "unknown",
            "status": "FAILED",
            "mutation": {
                "strategy": "security",
                "target": "query",
                "operation": "REPLACE",
                "path": ["sku"],
                "original_value": "SKU1",
                "new_value": "' OR 1=1 --",
            },
            "request": {
                "method": "POST",
                "url": "https://example.com/orders",
                "headers": {"content-type": "application/json"},
                "params": {"sku": "' OR 1=1 --"},
                "body": {"email": "qa1@example.com"},
            },
            "response": {"status_code": 500, "elapsed_ms": 120, "error": "Internal error", "attempt": 1},
        },
    ]
    run2_results = [
        {
            "name": "happy_path",
            "failure_type": "unknown",
            "status": "FAILED",
            "mutation": None,
            "request": {
                "method": "POST",
                "url": "https://example.com/orders",
                "headers": {"Authorization": "Bearer run2-token", "content-type": "application/json"},
                "params": {},
                "body": {"email": "qa2@example.com", "qty": 2},
            },
            "response": {"status_code": 503, "elapsed_ms": 220, "error": "Service unavailable", "attempt": 1},
        },
        {
            "name": "sku_guard",
            "failure_type": "success",
            "status": "PASSED",
            "mutation": {
                "strategy": "security",
                "target": "query",
                "operation": "REPLACE",
                "path": ["sku"],
                "original_value": "SKU1",
                "new_value": "' OR 1=1 --",
            },
            "request": {
                "method": "POST",
                "url": "https://example.com/orders",
                "headers": {"content-type": "application/json"},
                "params": {"sku": "' OR 1=1 --"},
                "body": {"email": "qa2@example.com"},
            },
            "response": {"status_code": 200, "elapsed_ms": 90, "attempt": 1},
        },
        {
            "name": "remove_optional_field",
            "failure_type": "unknown",
            "status": "FAILED",
            "mutation": {
                "strategy": "schema",
                "target": "body",
                "operation": "REMOVE",
                "path": ["email"],
                "original_value": "qa2@example.com",
            },
            "request": {
                "method": "POST",
                "url": "https://example.com/orders",
                "headers": {"content-type": "application/json"},
                "params": {},
                "body": {"qty": 2},
            },
            "response": {"status_code": 422, "elapsed_ms": 110, "error": "email required", "attempt": 1},
        },
    ]

    report_writer.write_report(request, run1_results, meta={"decision": "APPROVE_RELEASE_WITH_RISKS"})
    second_json = Path(report_writer.write_report(request, run2_results, meta={"decision": "REJECT_RELEASE"}))
    report_data = json.loads(second_json.read_text(encoding="utf-8"))
    endpoint_html = Path(report_data["meta"]["artifacts"]["html_report"]).read_text(encoding="utf-8")
    dashboard_html = Path(report_data["meta"]["artifacts"]["dashboard_html"]).read_text(encoding="utf-8")

    assert "Run Compare Mode" in endpoint_html
    assert "compareLeft" in endpoint_html
    assert "compareRight" in endpoint_html
    assert "compareRunsData" in endpoint_html
    assert "Flaky & Regression Signals" in endpoint_html
    assert "Root Cause Clusters" in endpoint_html
    assert "Download Repro" in endpoint_html
    assert "Policy Profile" in endpoint_html
    assert "Owner & Escalation" in endpoint_html
    assert "Create Jira" in endpoint_html
    assert "Send Slack Alert" in endpoint_html
    assert "PII Audit" in endpoint_html
    assert "Save View" in endpoint_html
    assert "Copy View URL" in endpoint_html
    assert "Export Selected to Postman" in endpoint_html
    assert "Download Effective JSON" in endpoint_html
    assert "postman-select" in endpoint_html
    assert "MANUALLY_PASSED" in endpoint_html
    assert "manual-pass-btn" in endpoint_html
    assert "projectManualPassMap" in endpoint_html
    assert "data-manual-key" in endpoint_html
    assert "Manually Passed" in endpoint_html
    assert "data-metric='manually_passed'" in endpoint_html
    assert "refreshLiveSummaryMetrics" in endpoint_html
    assert "computeEffectiveRiskScore" in endpoint_html
    assert "computeEffectiveDecision" in endpoint_html
    assert "buildEffectiveJsonReport" in endpoint_html
    assert "applyManualOverridesToRun" in endpoint_html
    assert "id=\"runDecisionBadge\"" in endpoint_html
    assert "id=\"riskMeterFill\"" in endpoint_html

    assert "Trend (Last" in dashboard_html
    assert "sparkline" in dashboard_html
    assert "<strong>Flaky:</strong>" in dashboard_html
    assert "<strong>Manually Passed:</strong>" in dashboard_html
    assert "data-failure-signatures" in dashboard_html
    assert "computeDashboardDecision" in dashboard_html
    assert "data-project-manual-overrides" in dashboard_html
    assert "decisionChips" in dashboard_html

    compare_match = re.search(
        r"<script id='compareRunsData' type='application/json'>(.*?)</script>",
        endpoint_html,
        flags=re.DOTALL,
    )
    assert compare_match is not None
    compare_payload = json.loads(compare_match.group(1))
    assert isinstance(compare_payload, list)
    assert len(compare_payload) >= 2
    assert "manual_pass_count" in compare_payload[-1]
    assert "effective_pass_count" in compare_payload[-1]


def test_owner_panel_disables_jira_action_from_env(tmp_path, monkeypatch):
    monkeypatch.setattr(report_writer, "REPORTS_DIR", tmp_path)
    monkeypatch.setenv("AI_SWARM_ENABLE_JIRA_ACTION", "0")
    monkeypatch.setenv("AI_SWARM_JIRA_URL_TEMPLATE", "https://jira.example.local/create?summary={summary}")

    request = {"method": "GET", "url": "https://example.com/jira-disable"}
    results = [
        {
            "name": "happy_path",
            "failure_type": "success",
            "status": "PASSED",
            "request": {"method": "GET", "url": "https://example.com/jira-disable", "headers": {}, "params": {}, "body": None},
            "response": {"status_code": 200, "elapsed_ms": 21, "attempt": 1},
        }
    ]

    report_path = Path(report_writer.write_report(request, results, meta={"decision": "APPROVE_RELEASE"}))
    report_data = json.loads(report_path.read_text(encoding="utf-8"))
    endpoint_html = Path(report_data["meta"]["artifacts"]["html_report"]).read_text(encoding="utf-8")

    assert "<span class='action-link disabled'>Create Jira</span>" in endpoint_html
    assert "Jira action disabled via AI_SWARM_ENABLE_JIRA_ACTION=0." in endpoint_html


def test_summary_counts_manually_passed_as_pass(tmp_path, monkeypatch):
    monkeypatch.setattr(report_writer, "REPORTS_DIR", tmp_path)

    request = {"method": "POST", "url": "https://example.com/manual-pass"}
    results = [
        {
            "name": "case_manual",
            "failure_type": "unknown",
            "status": "MANUALLY_PASSED",
            "request": {"method": "POST", "url": "https://example.com/manual-pass", "headers": {}, "params": {}, "body": {}},
            "response": {"status_code": 422, "elapsed_ms": 40, "attempt": 1},
        },
        {
            "name": "case_failed",
            "failure_type": "unknown",
            "status": "FAILED",
            "request": {"method": "POST", "url": "https://example.com/manual-pass", "headers": {}, "params": {}, "body": {}},
            "response": {"status_code": 422, "elapsed_ms": 40, "attempt": 1},
        },
    ]

    report_path = Path(report_writer.write_report(request, results, meta={"decision": "APPROVE_RELEASE_WITH_RISKS"}))
    report_data = json.loads(report_path.read_text(encoding="utf-8"))
    summary = report_data["summary"]

    assert summary["pass_count"] == 0
    assert summary["manual_pass_count"] == 1
    assert summary["effective_pass_count"] == 1
    assert summary["unknown_status_count"] == 0
    assert summary["unknown_count"] == 1
    assert summary["fail_count"] == 1

    endpoint_name = report_data["endpoint_name"]
    history = json.loads((tmp_path / endpoint_name / "history.json").read_text(encoding="utf-8"))
    latest = history[-1]
    assert latest["effective_pass_count"] == 1
    assert latest["pass_rate"] == 50
    assert all("case_manual|" not in signature for signature in latest.get("failure_signatures", []))

    dashboard_html = (tmp_path / "index.html").read_text(encoding="utf-8")
    assert "<strong>Passed:</strong> 0 | <strong>Failed:</strong> 1 | <strong>Manually Passed:</strong> 1" in dashboard_html


def test_project_level_manual_pass_overrides_apply_across_reports(tmp_path, monkeypatch):
    monkeypatch.setattr(report_writer, "REPORTS_DIR", tmp_path)

    overrides = {
        "GET_project-manual": {
            "needs_override|REPLACE|query|id": {
                "source": "project",
                "updated_at_utc": "2026-01-01T00:00:00Z",
            }
        }
    }
    (tmp_path / "manual_pass_overrides.json").write_text(json.dumps(overrides, indent=2), encoding="utf-8")

    request = {"method": "GET", "url": "https://example.com/project-manual"}
    results = [
        {
            "name": "needs_override",
            "failure_type": "unknown",
            "status": "FAILED",
            "mutation": {"target": "query", "operation": "REPLACE", "path": ["id"]},
            "request": {"method": "GET", "url": "https://example.com/project-manual", "headers": {}, "params": {"id": "x"}, "body": None},
            "response": {"status_code": 422, "elapsed_ms": 33, "attempt": 1},
        }
    ]

    report_path = Path(report_writer.write_report(request, results, meta={"decision": "APPROVE_RELEASE_WITH_RISKS"}))
    report_data = json.loads(report_path.read_text(encoding="utf-8"))

    assert report_data["results"][0]["status"] == "MANUALLY_PASSED"
    assert report_data["summary"]["manual_pass_count"] == 1
    assert report_data["summary"]["fail_count"] == 0
    assert report_data["project_manual_pass"]["endpoint_overrides"]["needs_override|REPLACE|query|id"]["source"] in {
        "project",
        "report",
    }

    dashboard_html = (tmp_path / "index.html").read_text(encoding="utf-8")
    assert "data-project-manual-overrides=" in dashboard_html


def test_manual_pass_overrides_file_created_in_reports_root(tmp_path, monkeypatch):
    monkeypatch.setattr(report_writer, "REPORTS_DIR", tmp_path)
    request = {"method": "GET", "url": "https://example.com/file-create"}
    results = [
        {
            "name": "happy_path",
            "failure_type": "success",
            "status": "PASSED",
            "request": {"method": "GET", "url": "https://example.com/file-create", "headers": {}, "params": {}, "body": None},
            "response": {"status_code": 200, "elapsed_ms": 10, "attempt": 1},
        }
    ]

    report_writer.write_report(request, results, meta={"decision": "APPROVE_RELEASE"})
    overrides_path = tmp_path / "manual_pass_overrides.json"
    assert overrides_path.exists()
    assert json.loads(overrides_path.read_text(encoding="utf-8")) == {}


def test_manual_pass_button_hidden_for_passed_rows(tmp_path, monkeypatch):
    monkeypatch.setattr(report_writer, "REPORTS_DIR", tmp_path)

    request = {"method": "POST", "url": "https://example.com/manual-btn"}
    results = [
        {
            "name": "already_passed",
            "failure_type": "success",
            "status": "PASSED",
            "request": {"method": "POST", "url": "https://example.com/manual-btn", "headers": {}, "params": {}, "body": {}},
            "response": {"status_code": 200, "elapsed_ms": 30, "attempt": 1},
        },
        {
            "name": "needs_override",
            "failure_type": "unknown",
            "status": "FAILED",
            "request": {"method": "POST", "url": "https://example.com/manual-btn", "headers": {}, "params": {}, "body": {}},
            "response": {"status_code": 422, "elapsed_ms": 40, "attempt": 1},
        },
    ]

    report_path = Path(report_writer.write_report(request, results, meta={"decision": "APPROVE_RELEASE_WITH_RISKS"}))
    report_data = json.loads(report_path.read_text(encoding="utf-8"))
    endpoint_html = Path(report_data["meta"]["artifacts"]["html_report"]).read_text(encoding="utf-8")

    passed_row = re.search(
        r"<tr class='result-row[^']*'[^>]*data-name='already_passed'[^>]*>.*?</tr>",
        endpoint_html,
        flags=re.DOTALL,
    )
    failed_row = re.search(
        r"<tr class='result-row[^']*'[^>]*data-name='needs_override'[^>]*>.*?</tr>",
        endpoint_html,
        flags=re.DOTALL,
    )
    assert passed_row is not None
    assert failed_row is not None
    assert "Already Passed" in passed_row.group(0)
    assert "manual-pass-btn" not in passed_row.group(0)
    assert "manual-pass-btn" in failed_row.group(0)


def test_report_writer_auto_opens_dashboard_and_latest_when_enabled(tmp_path, monkeypatch):
    monkeypatch.setattr(report_writer, "REPORTS_DIR", tmp_path)
    monkeypatch.setenv("AI_SWARM_OPEN_REPORT", "both")
    monkeypatch.setenv("CI", "0")

    opened: list[str] = []

    def fake_open(url: str, new: int = 0):
        opened.append(url)
        return True

    monkeypatch.setattr(report_writer.webbrowser, "open", fake_open)

    request = {"method": "GET", "url": "https://example.com/open-check"}
    results = [
        {
            "name": "happy_path",
            "failure_type": "success",
            "status": "PASSED",
            "request": {"method": "GET", "url": "https://example.com/open-check", "headers": {}, "params": {}, "body": None},
            "response": {"status_code": 200, "elapsed_ms": 20, "attempt": 1},
        }
    ]

    report_writer.write_report(request, results, meta={"decision": "APPROVE_RELEASE"})

    assert any(url.endswith("/index.html") for url in opened)
    assert any(url.endswith("/GET_open-check/latest.html") for url in opened)
