#!/usr/bin/env python3
"""
Generates the HTML report per repo, the report index and dataset.json.

The score shown everywhere is the FINAL score:
  - the second model's verdict when it gives one,
  - otherwise the first model's score (no verdict = the second model agrees).

Needs enrich_dataset.py in the same folder (it holds the parser and the surface rules).
This replaces threat_summary.py: dataset.json is built straight from the raw JSON files,
not from the generated HTML.

Usage:
  python3 generate_reports.py
"""
import argparse
import json
from pathlib import Path
from datetime import datetime

from collections import Counter

from enrich_dataset import parse_repo, detect_surfaces, GENERIC_SURFACE

INPUT_DIR = Path("/mnt/bigstor/www/usecases/parallel_output")
OUTPUT_DIR = Path("/mnt/bigstor/www/usecases/reports")
DATASET_OUT = Path("/mnt/bigstor/usecases/dataset.json")

# ------------------------------------------------------------
# HTML TEMPLATE
# ------------------------------------------------------------

HTML_HEADER = """
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{title}</title>
<style>
body {{
    font-family: Arial, sans-serif;
    margin: 40px;
    background: #f5f5f5;
}}
h1 {{ color: #222; }}
h2 {{ color: #333; margin-top: 30px; }}
pre {{
    background: #eee;
    padding: 15px;
    border-radius: 8px;
    white-space: pre-wrap;
    font-size: 0.95em;
}}
.container {{
    background: white;
    padding: 30px;
    border-radius: 12px;
    box-shadow: 0 0 12px #bbb;
}}
.score {{
    font-size: 1.4em;
    font-weight: bold;
}}
.low {{ color: green; }}
.medium {{ color: orange; }}
.high {{ color: red; }}
.critical {{ color: darkred; }}
.unknown {{ color: #555; }}
.footer {{
    margin-top: 40px;
    font-size: 0.8em;
    color: #666;
}}
.collapsible {{
    background-color: #444;
    color: white;
    cursor: pointer;
    padding: 12px;
    width: 100%;
    border: none;
    text-align: left;
    font-size: 1.1em;
    border-radius: 6px;
    margin-top: 20px;
}}
.active, .collapsible:hover {{
    background-color: #666;
}}
.content {{
    padding: 0 15px;
    display: none;
    overflow: hidden;
}}
</style>
</head>
<body>
<div class="container">
"""

HTML_FOOTER = """
<div class="footer">
Generated on {timestamp}
</div>
</div>
<script>
document.querySelectorAll(".collapsible").forEach(btn => {{
  btn.addEventListener("click", function() {{
    this.classList.toggle("active");
    let content = this.nextElementSibling;
    content.style.display = content.style.display === "block" ? "none" : "block";
  }});
}});
</script>
</body>
</html>
"""

# ------------------------------------------------------------
# UTILITIES
# ------------------------------------------------------------

def score_class(score: str) -> str:
    return score.lower()


def safe_html(text: str) -> str:
    return (
        (text or "").replace("&", "&amp;")
            .replace("<", "&lt;")
            .replace(">", "&gt;")
    )


def provenance(rich: dict) -> str:
    """One line that says where the final score comes from."""
    i, v, f = rich.get("score_initial"), rich.get("score_verdict"), rich.get("score_final")
    if not f:
        return "No score could be read from the analysis."
    if v and i and v != i:
        verb = "raised" if rich.get("escalated") else "lowered"
        return f"The second model {verb} the rating from {i} to {v}."
    if v:
        return f"Both models rate this {f}."
    return f"The second model gave no verdict, so the first model's rating ({f}) stands."


# ------------------------------------------------------------
# REPORT GENERATION
# ------------------------------------------------------------

def generate_html_report(repo_name: str, doc: str, summary: str, intel: str, rich: dict) -> str:
    score = rich.get("score_final") or "Unknown"

    doc_html = safe_html(doc)
    summary_html = safe_html(summary)
    intel_html = safe_html(intel)

    html = HTML_HEADER.format(title=safe_html(repo_name))

    html += f"<h1>Repository Report: {safe_html(repo_name)}</h1>"
    html += f"<p class='score {score_class(score)}'>Threat Score: {score}</p>"
    html += f"<p>{safe_html(provenance(rich))}</p>"

    html += """
<button class="collapsible">Document Pipeline</button>
<div class="content"><pre>{}</pre></div>
""".format(doc_html)

    html += """
<button class="collapsible">Summary for DeepSeek</button>
<div class="content"><pre>{}</pre></div>
""".format(summary_html)

    html += """
<button class="collapsible">Intelligence Pipeline</button>
<div class="content"><pre>{}</pre></div>
""".format(intel_html)

    html += HTML_FOOTER.format(timestamp=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    return html


# ------------------------------------------------------------
# MAIN
# ------------------------------------------------------------

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--input", type=Path, default=INPUT_DIR)
    ap.add_argument("--output", type=Path, default=OUTPUT_DIR)
    ap.add_argument("--dataset-out", type=Path, default=DATASET_OUT,
                    help="where to write dataset.json")
    a = ap.parse_args()

    a.output.mkdir(parents=True, exist_ok=True)
    dataset_out = a.dataset_out
    dataset_out.parent.mkdir(parents=True, exist_ok=True)

    records, failed = [], []

    print(f"Scanning {a.input}...")

    for file in sorted(a.input.glob("*.json")):
        try:
            with open(file, "r", encoding="utf-8") as f:
                data = json.load(f)
        except Exception as e:
            print(f"! skipped {file.name}: {e}")
            failed.append(file.name)
            continue

        repo_name = file.stem
        doc = data.get("document_pipeline", "")
        summary = data.get("document_summary_for_deepseek", "")
        intel = data.get("intelligence_pipeline", "")

        rich = parse_repo(doc, intel)

        html_page = generate_html_report(repo_name, doc, summary, intel, rich)
        with open(a.output / f"{repo_name}.html", "w", encoding="utf-8") as f:
            f.write(html_page)

        rec = {
            "name": repo_name,
            "owner": repo_name.split("__")[0],
            "score": rich["score_final"] or "Unknown",
            "surfaces": detect_surfaces(repo_name, rich),
            **rich,
        }
        records.append(rec)

        print(f"✔ Generated {repo_name}.html")

    # ------------------------------------------------------------
    # dataset.json
    # ------------------------------------------------------------

    dataset_out.write_text(json.dumps(records, indent=2, ensure_ascii=False), encoding="utf-8")

    # ------------------------------------------------------------
    # INDEX PAGE
    # ------------------------------------------------------------

    index_entries = [(r["name"], r["score"]) for r in records]

    index_html = HTML_HEADER.format(title="Automotive Cybersecurity Reports")
    index_html += "<h1>Automotive Cybersecurity Report Index</h1>"

    index_html += """
<input type="text" id="searchBox" placeholder="Zoek repository, threat score..." 
       style="width:100%; padding:10px; font-size:1.1em; margin-top:10px;">

<select id="threatFilter" style="margin-top:10px; padding:10px;">
  <option value="">Alle threat scores</option>
  <option value="low">Low</option>
  <option value="medium">Medium</option>
  <option value="high">High</option>
  <option value="critical">Critical</option>
  <option value="unknown">Unknown</option>
</select>

<ul id="repoList">
"""

    for repo, score in index_entries:
        index_html += (
            f"<li data-score='{score_class(score)}'>"
            f"<a href='{repo}.html'>{repo}</a> — "
            f"<span class='{score_class(score)}'>{score}</span></li>"
        )

    index_html += "</ul>"

    index_html += """
<script>
const searchBox = document.getElementById("searchBox");
const threatFilter = document.getElementById("threatFilter");
const repoList = document.getElementById("repoList");

function applyFilters() {
  const text = searchBox.value.toLowerCase();
  const threat = threatFilter.value.toLowerCase();

  document.querySelectorAll("#repoList li").forEach(li => {
    const score = li.dataset.score.toLowerCase();
    const visibleText = li.textContent.toLowerCase();

    const matchesText = visibleText.includes(text);
    const matchesThreat = threat === "" || score === threat;

    li.style.display = matchesText && matchesThreat ? "" : "none";
  });
}

searchBox.addEventListener("input", applyFilters);
threatFilter.addEventListener("change", applyFilters);
</script>
"""

    index_html += HTML_FOOTER.format(timestamp=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

    with open(a.output / "index.html", "w", encoding="utf-8") as f:
        f.write(index_html)

    gave = sum(1 for r in records if r.get("score_verdict"))
    print(f"\n✔ {len(records)} reports in {a.output}")
    print(f"✔ dataset written to {dataset_out}")
    print(f"  second model gave a verdict for {gave}, agreed silently for {len(records) - gave}")
    surf = Counter(x for r in records for x in r["surfaces"])
    general = surf.get(GENERIC_SURFACE, 0)
    print(f"  surfaces: {len(surf)} different, {general} repos only matched '{GENERIC_SURFACE}'")
    unmapped = Counter(r["primary_focus"] for r in records
                       if r["surfaces"] == [GENERIC_SURFACE] and r.get("primary_focus"))
    if unmapped:
        print("  most common focus terms without a surface (add rules in SURFACE_RULES):")
        for term, n in unmapped.most_common(10):
            print(f"    {n:3}  {term}")
    unk = [r["name"] for r in records if r["score"] == "Unknown"]
    if unk:
        print(f"  ! no score found for {len(unk)} repos, e.g. {unk[:3]}")
    if failed:
        print(f"  ! {len(failed)} unreadable files skipped: {failed[:3]}")


if __name__ == "__main__":
    main()
