#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Build site/incidents.html from incidents/incidents.json.

Threat mappings come from evidence/threat_correlations.json. The page presents
concrete incidents separately from assessments, observations and exploitation
activity while preserving the shared site header.
"""
from __future__ import annotations

import argparse
import html
import json
import re
import sys
from collections import Counter, defaultdict
from pathlib import Path
from typing import Any
from site_navigation import navigation as site_navigation

DEFAULT_INCIDENTS = Path("incidents/incidents.json")
DEFAULT_CORRELATIONS = Path("evidence/threat_correlations.json")
DEFAULT_OUTPUT = Path("site/incidents.html")


RECORD_LABELS = {
    "incident": "Incident",
    "strategic_assessment": "Strategic assessment",
    "threat_observation": "Threat observation",
    "exploitation_activity": "Exploitation activity",
    "organizational": "Organizational publication",
    "unknown": "Unclassified record",
}


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Build the incidents overview page.")
    parser.add_argument("--incidents", type=Path, default=DEFAULT_INCIDENTS)
    parser.add_argument("--correlations", type=Path, default=DEFAULT_CORRELATIONS)
    parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
    parser.add_argument("--summary-limit", type=int, default=520)
    args = parser.parse_args()
    if args.summary_limit < 80:
        parser.error("--summary-limit must be at least 80")
    return args


def e(value: Any) -> str:
    return html.escape(str(value if value is not None else ""), quote=True)


def clean(value: Any) -> str:
    return re.sub(r"\s+", " ", str(value or "")).strip()


def truncate_text(value: Any, limit: int = 520) -> str:
    value = clean(value)
    if limit <= 0:
        return ""
    if len(value) <= limit:
        return value
    if limit <= 3:
        return value[:limit]
    clipped = value[: limit - 3].rsplit(" ", 1)[0].rstrip(" ,;:")
    return (clipped or value[: limit - 3]).rstrip() + "..."


def safe_float(value: Any) -> float:
    try:
        return float(value)
    except (TypeError, ValueError):
        return 0.0


def load_json(path: Path) -> dict[str, Any]:
    if not path.exists():
        raise FileNotFoundError(f"Input file not found: {path}")
    with path.open("r", encoding="utf-8") as handle:
        try:
            data = json.load(handle)
        except json.JSONDecodeError as exc:
            raise ValueError(
                f"Invalid JSON in {path}: line {exc.lineno}, column {exc.colno}: {exc.msg}"
            ) from exc
    if not isinstance(data, dict):
        raise ValueError(f"Expected a JSON object in {path}")
    return data


def list_values(value: Any) -> list[str]:
    if not isinstance(value, list):
        return []
    return [clean(item) for item in value if clean(item)]


def first_source(record: dict[str, Any]) -> dict[str, Any]:
    sources = record.get("sources", [])
    if not isinstance(sources, list):
        return {}
    return next((item for item in sources if isinstance(item, dict)), {})


def record_id(record: dict[str, Any]) -> str:
    return clean(record.get("incident_id") or record.get("id"))


def build_correlation_index(correlations: dict[str, Any]) -> dict[str, list[dict[str, Any]]]:
    index: dict[str, list[dict[str, Any]]] = defaultdict(list)
    threats = correlations.get("threats", {})
    if not isinstance(threats, dict):
        return index
    for threat_id, threat in threats.items():
        if not isinstance(threat, dict):
            continue
        threat_title = clean(threat.get("title"))
        evidence = threat.get("evidence", [])
        if not isinstance(evidence, list):
            continue
        for item in evidence:
            if not isinstance(item, dict):
                continue
            evidence_type = clean(item.get("evidence_type")).lower()
            if evidence_type not in {"incident", "assessment", "threat observation", "narrative"}:
                continue
            evidence_id = clean(item.get("evidence_id")).casefold()
            if not evidence_id:
                continue
            index[evidence_id].append({
                "threat_id": clean(threat_id),
                "threat_title": threat_title,
                "status": clean(item.get("status")).lower() or "review",
                "score": safe_float(item.get("relevance_score")),
            })
    for matches in index.values():
        matches.sort(key=lambda item: item["score"], reverse=True)
    return index


def correlations_for(
    record: dict[str, Any],
    index: dict[str, list[dict[str, Any]]],
) -> list[dict[str, Any]]:
    candidates = {
        record_id(record).casefold(),
        clean(record.get("title")).casefold(),
    }
    matches: list[dict[str, Any]] = []
    seen: set[tuple[str, str]] = set()
    for candidate in candidates:
        if not candidate:
            continue
        for match in index.get(candidate, []):
            key = (match["threat_id"], match["status"])
            if key not in seen:
                matches.append(match)
                seen.add(key)
    return sorted(matches, key=lambda item: item["score"], reverse=True)


def navigation() -> str:
    return site_navigation("Incidents")

CSS = r"""
:root{--bg:#eef1f5;--surface:#fff;--surface-alt:#f7f9fb;--surface-hover:#f1f5f8;--ink:#1b2430;--muted:#5d6b7c;--line:#d5dce5;--accent:#1f4e79;--accepted:#2f7d59;--review:#b37a20;--incident:#b55832;--assessment:#3d7b72;--high:#b3261e;--medium:#d9692a;--low:#5b8c85;--unknown:#7a8696}
@media(prefers-color-scheme:dark){:root{--bg:#12171e;--surface:#1a212b;--surface-alt:#151c25;--surface-hover:#202a36;--ink:#e6ebf1;--muted:#93a1b3;--line:#2c3644;--accent:#7db4e6;--accepted:#58c493;--review:#e0a74d;--incident:#e98c68;--assessment:#73c1b3;--high:#ef6a60;--medium:#f0924f;--low:#7fb3aa;--unknown:#93a1b3}}
*{box-sizing:border-box}body{margin:0;padding:0;background:var(--bg);color:var(--ink);font:16px/1.5 "Segoe UI",system-ui,sans-serif}a{color:var(--accent);text-decoration:none}a:hover{text-decoration:underline}h1,h2,h3{margin-top:0}.site-header{display:flex;align-items:center;justify-content:space-between;gap:24px;min-height:68px;padding:12px 28px;background:var(--surface);border-bottom:1px solid var(--line)}.site-nav{display:flex;flex-wrap:wrap;justify-content:flex-start;gap:4px}.site-nav-link{color:var(--muted);padding:7px 10px;border-radius:5px;font-size:.84rem;font-weight:600}.site-nav-link:hover{color:var(--ink);background:var(--surface-alt);text-decoration:none}.site-nav-link.active{color:var(--accent);background:color-mix(in srgb,var(--accent) 12%,transparent)}.site-brand{margin-left:auto;color:var(--ink);font-weight:700;white-space:nowrap}.site-brand:hover{text-decoration:none}main{max-width:1240px;margin:auto;padding:26px 24px 44px}.hero,.card{background:var(--surface);border:1px solid var(--line);border-radius:7px;padding:22px;margin-bottom:20px}.hero h1{margin-bottom:6px}.sub,.muted{color:var(--muted)}.small{font-size:.82rem}.metric-row{display:flex;flex-wrap:wrap;gap:8px;margin-bottom:20px}.metric{display:flex;align-items:baseline;gap:7px;padding:9px 12px;background:var(--surface);border:1px solid var(--line);border-radius:6px}.metric strong{font-size:1.15rem}.metric span{color:var(--muted);font-size:.78rem}.toolbar{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:14px}.toolbar h2{margin:0}.count{color:var(--muted);font-size:.8rem}.filters{display:grid;grid-template-columns:minmax(280px,1fr) repeat(4,minmax(145px,auto));gap:10px;margin-bottom:16px}.filters input,.filters select{width:100%;background:var(--bg);color:var(--ink);border:1px solid var(--line);border-radius:5px;padding:8px 10px;font:inherit}.incident-list{display:flex;flex-direction:column;gap:12px}.incident-card{background:var(--surface-alt);border:1px solid var(--line);border-left:3px solid var(--incident);border-radius:6px;padding:16px}.incident-card.assessment{border-left-color:var(--assessment)}.incident-card:hover{background:var(--surface-hover)}.incident-head{display:flex;justify-content:space-between;align-items:flex-start;gap:16px}.incident-head h3{margin:0 0 5px;font-size:1.02rem}.badges,.tags,.matches,.meta{display:flex;flex-wrap:wrap;gap:5px}.badge,.tag,.match{display:inline-flex;align-items:center;padding:3px 7px;border:1px solid var(--line);border-radius:10px;font-size:.68rem}.badge{font-weight:700;text-transform:uppercase}.severity-high{color:var(--high)}.severity-medium{color:var(--medium)}.severity-low{color:var(--low)}.severity-unknown{color:var(--unknown)}.summary{margin:10px 0}.meta{color:var(--muted);font-size:.74rem}.tags{margin-top:9px}.tag{background:var(--bg);color:var(--muted)}.matches{margin-top:12px;padding-top:10px;border-top:1px solid var(--line)}.match.accepted{color:var(--accepted)}.match.review{color:var(--review)}.source-link{font-size:.78rem;font-weight:600}.footer{margin-top:28px;color:var(--muted);font-size:.82rem}
@media(max-width:1000px){.filters{grid-template-columns:1fr 1fr}}@media(max-width:900px){.site-header{align-items:flex-start;flex-direction:column-reverse}.site-brand{margin-left:0}}@media(max-width:650px){.site-header{padding:12px 16px}main{padding:18px 12px 34px}.filters{grid-template-columns:1fr}.incident-head,.toolbar{flex-direction:column}}
"""


def build_page(
    incidents_data: dict[str, Any],
    correlations: dict[str, Any],
    summary_limit: int,
) -> str:
    raw_records = incidents_data.get("incidents", [])
    if not isinstance(raw_records, list):
        raise ValueError("Incidents input must contain an incidents list")
    records = [record for record in raw_records if isinstance(record, dict)]
    records.sort(
        key=lambda record: (
            clean((record.get("dates") or {}).get("published") if isinstance(record.get("dates"), dict) else ""),
            clean(record.get("title")),
        ),
        reverse=True,
    )

    correlation_index = build_correlation_index(correlations)
    record_types = Counter(clean(record.get("record_type")).lower() or "unknown" for record in records)
    statuses = sorted({clean(record.get("status")).lower() or "unknown" for record in records})
    sectors = sorted({sector for record in records for sector in list_values(record.get("sectors"))}, key=str.casefold)
    event_types = sorted({clean(record.get("event_type")).lower() for record in records if clean(record.get("event_type"))})

    enriched = []
    mapped = 0
    accepted_mapped = 0
    for record in records:
        matches = correlations_for(record, correlation_index)
        if matches:
            mapped += 1
        if any(match["status"] == "accepted" for match in matches):
            accepted_mapped += 1
        enriched.append((record, matches))

    output = [
        '<!DOCTYPE html><html lang="en"><head><meta charset="utf-8">',
        '<meta name="viewport" content="width=device-width,initial-scale=1">',
        '<title>Incidents</title><style>', CSS, '</style></head><body>',
        navigation(), '<main>',
        '<section class="hero"><h1>Incidents</h1>',
        '<p class="sub">Observed cybersecurity incidents, exploitation activity, threat observations and authoritative assessments used as evidence for the Automotive Cybersecurity Threat Register.</p></section>',
        '<section class="metric-row">',
    ]
    metrics = [
        (len(records), "Records"),
        (record_types.get("incident", 0), "Concrete incidents"),
        (record_types.get("strategic_assessment", 0), "Assessments"),
        (record_types.get("threat_observation", 0), "Threat observations"),
        (mapped, "With threat mapping"),
        (accepted_mapped, "With accepted mapping"),
    ]
    for value, label in metrics:
        output.append(f'<div class="metric"><strong>{value}</strong><span>{e(label)}</span></div>')

    output.extend([
        '</section><section class="card">',
        '<div class="toolbar"><h2>Incident intelligence</h2><span class="count" id="count"></span></div>',
        '<div class="filters">',
        '<input type="search" id="q" placeholder="Search title, summary, sector, theme ...">',
        '<select id="recordType"><option value="">All record types</option>',
        ''.join(f'<option value="{e(value)}">{e(RECORD_LABELS.get(value, value.replace("_", " ").title()))}</option>' for value in sorted(record_types)),
        '</select><select id="status"><option value="">All statuses</option>',
        ''.join(f'<option value="{e(value)}">{e(value.title())}</option>' for value in statuses),
        '</select><select id="sector"><option value="">All sectors</option>',
        ''.join(f'<option value="{e(value)}">{e(value)}</option>' for value in sectors),
        '</select><select id="mapping"><option value="">All mappings</option><option value="accepted">Accepted</option><option value="review">Review</option><option value="unmatched">Unmatched</option></select>',
        '</div><div class="incident-list">',
    ])

    for record, matches in enriched:
        rid = record_id(record)
        title = clean(record.get("title")) or rid or "Untitled incident record"
        summary = truncate_text(record.get("summary"), summary_limit)
        record_type = clean(record.get("record_type")).lower() or "unknown"
        status = clean(record.get("status")).lower() or "unknown"
        event_type = clean(record.get("event_type")).lower()
        dates = record.get("dates") if isinstance(record.get("dates"), dict) else {}
        published = clean(dates.get("published"))
        sectors_value = list_values(record.get("sectors"))
        themes = list_values(record.get("themes"))
        tags = list_values(record.get("tags"))
        geography = record.get("geography") if isinstance(record.get("geography"), dict) else {}
        countries = list_values(geography.get("countries"))
        impact = record.get("impact") if isinstance(record.get("impact"), dict) else {}
        severity = clean(impact.get("severity")).lower() or "unknown"
        source = first_source(record)
        source_url = clean(source.get("url"))
        publisher = clean(source.get("publisher"))
        confidence = safe_float((record.get("evidence") or {}).get("confidence_score") if isinstance(record.get("evidence"), dict) else 0)
        mapping = "accepted" if any(item["status"] == "accepted" for item in matches) else ("review" if matches else "unmatched")
        haystack = " ".join([title, summary, record_type, status, event_type, " ".join(sectors_value), " ".join(themes), " ".join(tags), " ".join(countries), publisher]).lower()
        card_class = "incident-card" if record_type == "incident" else "incident-card assessment"
        labels = []
        for value in (sectors_value + themes + tags):
            if value and value.casefold() not in {item.casefold() for item in labels}:
                labels.append(value)
        tag_html = ''.join(f'<span class="tag">{e(value.replace("_", " "))}</span>' for value in labels[:12])
        match_html = []
        for match in matches[:8]:
            href = f'threats/{match["threat_id"]}.html#evidence'
            match_html.append(
                f'<a class="match {e(match["status"])}" href="{e(href)}" title="{e(match["threat_title"])}">'
                f'{e(match["threat_id"])} · {match["score"]:.2f}</a>'
            )
        if not match_html:
            match_html.append('<span class="muted small">No threat mapping above the review threshold</span>')
        external_link = (
            f'<a class="source-link" href="{e(source_url)}" target="_blank" rel="noopener noreferrer">View source →</a>'
            if source_url else ""
        )
        output.append(
            f'<article class="{card_class}" data-hay="{e(haystack)}" data-record-type="{e(record_type)}" '
            f'data-status="{e(status)}" data-sectors="{e("|".join(sectors_value))}" data-mapping="{e(mapping)}">'
            '<div class="incident-head"><div>'
            f'<h3>{e(title)}</h3><div class="badges">'
            f'<span class="badge">{e(RECORD_LABELS.get(record_type, record_type.replace("_", " ").title()))}</span>'
            f'<span class="badge">{e(status)}</span>'
            f'<span class="badge severity-{e(severity)}">{e(severity)} impact</span>'
            '</div></div>'
            f'{external_link}</div>'
            f'<p class="summary">{e(summary or "No summary available.")}</p>'
            '<div class="meta">'
            f'<span>{e(rid)}</span>'
            + (f'<span>{e(published)}</span>' if published else '')
            + (f'<span>{e(publisher)}</span>' if publisher else '')
            + (f'<span>{e(event_type.replace("_", " "))}</span>' if event_type else '')
            + (f'<span>{e(", ".join(countries))}</span>' if countries else '')
            + f'<span>confidence {confidence:.2f}</span>'
            + '</div>'
            f'<div class="tags">{tag_html}</div>'
            f'<div class="matches">{"".join(match_html)}</div>'
            '</article>'
        )

    metadata = incidents_data.get("metadata", {}) if isinstance(incidents_data.get("metadata"), dict) else {}
    generated = clean(metadata.get("generated_at"))[:16].replace("T", " ")
    output.extend([
        '</div></section>',
        f'<footer class="footer">Incident intelligence generated {e(generated)} · source: incidents/incidents.json</footer>',
        r'''<script>
const cards=[...document.querySelectorAll(".incident-card")];
const controls={q:document.getElementById("q"),recordType:document.getElementById("recordType"),status:document.getElementById("status"),sector:document.getElementById("sector"),mapping:document.getElementById("mapping")};
function apply(){const terms=controls.q.value.trim().toLowerCase().split(/\s+/).filter(Boolean);let visible=0;cards.forEach(card=>{const sectorMatch=!controls.sector.value||card.dataset.sectors.split("|").includes(controls.sector.value);const show=terms.every(term=>card.dataset.hay.includes(term))&&(!controls.recordType.value||card.dataset.recordType===controls.recordType.value)&&(!controls.status.value||card.dataset.status===controls.status.value)&&sectorMatch&&(!controls.mapping.value||card.dataset.mapping===controls.mapping.value);card.style.display=show?"":"none";if(show)visible++;});document.getElementById("count").textContent="Showing "+visible+" of "+cards.length+" records";}
Object.values(controls).forEach(control=>control.addEventListener("input",apply));apply();
</script>''',
        '</main></body></html>',
    ])
    return ''.join(output)


def main() -> int:
    args = parse_args()
    try:
        incidents_data = load_json(args.incidents)
        correlations = load_json(args.correlations)
        page = build_page(incidents_data, correlations, args.summary_limit)
        args.output.parent.mkdir(parents=True, exist_ok=True)
        args.output.write_text(page, encoding="utf-8")
        records = incidents_data.get("incidents", [])
        count = len(records) if isinstance(records, list) else 0
        print(f"Wrote {args.output} with {count} records")
        return 0
    except (FileNotFoundError, ValueError, OSError) as exc:
        print(f"ERROR: {exc}", file=sys.stderr)
        return 2


if __name__ == "__main__":
    sys.exit(main())
