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
# ============================================================
def write_report(request: dict, results: list) -> 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"

    report = {
        "endpoint": f"{method} {url}",
        "run_time": timestamp,
        "total_tests": len(results),
        "results": 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)
