import json
import re
from pathlib import Path

INPUT_DIR = Path("/home/gdoll/automotive_reports")
OUTPUT_JSON = Path("/home/gdoll/automotive_dashboard/dataset.json")


# ---------------------------------------------------------
# THREAT SCORE EXTRACTION (ROBUST)
# ---------------------------------------------------------

def extract_threat_score(text: str):
    """
    Extract a real threat score from HTML.
    Returns (score, confidence)
    """

    text_lower = text.lower()

    # 1. Explicit "Threat Score: X"
    m = re.search(r"threat\s*score\s*[:\-]\s*(critical|high|medium|low)", text_lower)
    if m:
        return m.group(1).capitalize(), "High"

    # 2. HTML field <div class="threat-score">Critical</div>
    m = re.search(r'class=["\']threat-score["\']\s*>\s*(critical|high|medium|low)', text_lower)
    if m:
        return m.group(1).capitalize(), "High"

    # 3. <span class="score">High</span>
    m = re.search(r'class=["\']score["\']\s*>\s*(critical|high|medium|low)', text_lower)
    if m:
        return m.group(1).capitalize(), "Medium"

    # 4. "Score: High"
    m = re.search(r"score\s*[:\-]\s*(critical|high|medium|low)", text_lower)
    if m:
        return m.group(1).capitalize(), "Medium"

    # 5. No real score found
    return "Unknown", "Low"


# ---------------------------------------------------------
# ATTACK SURFACE DETECTION
# ---------------------------------------------------------

def detect_attack_surfaces(name: str):
    """
    Detect attack surfaces based on repo name heuristics.
    """

    n = name.lower()
    surfaces = []

    if "can" in n:
        surfaces.append("CAN Bus")
    if "uds" in n:
        surfaces.append("UDS Diagnostics")
    if "isotp" in n or "tp" in n:
        surfaces.append("ISO-TP")
    if "someip" in n:
        surfaces.append("SOME/IP")
    if "doip" in n:
        surfaces.append("DOIP")
    if "ecu" in n:
        surfaces.append("ECU Firmware")
    if "fuzz" in n:
        surfaces.append("Fuzzing Engine")
    if "key" in n or "fob" in n:
        surfaces.append("KeyFob / RF")
    if "gateway" in n:
        surfaces.append("Diagnostic Gateway")
    if "blockchain" in n:
        surfaces.append("Automotive Blockchain")
    if "ai" in n or "ml" in n:
        surfaces.append("Automotive AI")
    if "cluster" in n:
        surfaces.append("Dashboard Cluster")
    if "checksum" in n:
        surfaces.append("ECU Checksum Tools")
    if "routing" in n or "racecar" in n:
        surfaces.append("Telematics / Routing")

    if not surfaces:
        surfaces.append("General Automotive Surface")

    return surfaces


# ---------------------------------------------------------
# MAIN PIPELINE
# ---------------------------------------------------------

def main():
    repos = []

    for file in INPUT_DIR.glob("*.html"):
        with open(file, "r", encoding="utf-8") as f:
            doc = f.read()

        repo_name = file.stem

        score, confidence = extract_threat_score(doc)
        surfaces = detect_attack_surfaces(repo_name)

        repos.append({
            "name": repo_name,
            "score": score,
            "confidence": confidence,
            "surfaces": surfaces
        })

    with open(OUTPUT_JSON, "w", encoding="utf-8") as f:
        json.dump(repos, f, indent=4)

    print("dataset.json updated")


if __name__ == "__main__":
    main()
