import json
import os
import re
from datetime import datetime
from pathlib import Path
from urllib.parse import urlparse


# ============================================================
# 🔍 FIND CALLER PROJECT ROOT (NOT PACKAGE ROOT)
# ============================================================
def find_execution_root() -> Path:
    """
    Resolve project root based on WHERE tests are executed from,
    not where this package lives.
    """
    current = Path.cwd().resolve()

    while current != current.parent:
        if any(
            (current / marker).exists()
            for marker in (
                "pyproject.toml",
                "setup.py",
                "requirements.txt",
                ".git",
            )
        ):
            return current
        current = current.parent

    # Fallback: use cwd directly
    return Path.cwd().resolve()


PROJECT_ROOT = find_execution_root()
REPORTS_DIR = PROJECT_ROOT / "ai_swarm_reports"


# ============================================================
# 🧹 UTILS
# ============================================================
def extract_endpoint_name(method: str, url: str) -> str:
    """
    POST https://preprod-api.getepichome.in/api/validate-gst/
    -> POST_validate-gst
    """
    parsed = urlparse(url)
    parts = [p for p in parsed.path.split("/") if p]

    endpoint = parts[-1] if parts else "root"
    endpoint = re.sub(r"[^a-zA-Z0-9_-]", "-", endpoint)

    return f"{method}_{endpoint}"


# ============================================================
# 📝 REPORT WRITER
# ============================================================
from ai_testing_swarm.core.config import AI_SWARM_SLA_MS

SENSITIVE_HEADER_KEYS = {
    "authorization",
    "cookie",
    "set-cookie",
    "api-token",
    "api-secret-key",
    "x-api-key",
}


def _redact_headers(headers: dict) -> dict:
    if not isinstance(headers, dict):
        return headers
    out = {}
    for k, v in headers.items():
        if str(k).lower() in SENSITIVE_HEADER_KEYS and v is not None:
            out[k] = "***REDACTED***"
        else:
            out[k] = v
    return out


def _redact_results(results: list) -> list:
    redacted = []
    for r in results:
        r = dict(r)
        req = dict(r.get("request") or {})
        req["headers"] = _redact_headers(req.get("headers") or {})
        r["request"] = req
        redacted.append(r)
    return redacted


def write_report(request: dict, results: list, *, meta: dict | None = None) -> str:
    REPORTS_DIR.mkdir(exist_ok=True)

    method = request.get("method", "UNKNOWN")
    url = request.get("url", "")

    endpoint_name = extract_endpoint_name(method, url)
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")

    # report_path = REPORTS_DIR / f"{timestamp}_{endpoint_name}.json"
    # 🔥 PER-ENDPOINT FOLDER
    endpoint_dir = REPORTS_DIR / endpoint_name
    endpoint_dir.mkdir(parents=True, exist_ok=True)

    # 🔥 FILE NAME FORMAT
    report_path = endpoint_dir / f"{endpoint_name}_{timestamp}.json"

    safe_results = _redact_results(results)

    # Summary (counts + performance)
    summary = {
        "counts_by_failure_type": {},
        "counts_by_status_code": {},
        "slow_tests": [],
    }

    for r in safe_results:
        ft = r.get("failure_type") or "unknown"
        summary["counts_by_failure_type"][ft] = summary["counts_by_failure_type"].get(ft, 0) + 1

        sc = (r.get("response") or {}).get("status_code")
        sc_key = str(sc)
        summary["counts_by_status_code"][sc_key] = summary["counts_by_status_code"].get(sc_key, 0) + 1

        elapsed = (r.get("response") or {}).get("elapsed_ms")
        if isinstance(elapsed, int) and elapsed > AI_SWARM_SLA_MS:
            summary["slow_tests"].append({"name": r.get("name"), "elapsed_ms": elapsed})

    report = {
        "endpoint": f"{method} {url}",
        "run_time": timestamp,
        "total_tests": len(safe_results),
        "summary": summary,
        "meta": meta or {},
        "results": safe_results,
    }

    with open(report_path, "w") as f:
        json.dump(report, f, indent=2)

    print(f"📄 Swarm JSON report written to: {report_path}")

    return str(report_path)
