#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Update the generated Version & contact section in about.html.

Inputs:
  data/version.json
  release_notes.md

The script replaces only the content between:
  <!-- VERSION-INFO:START -->
  <!-- VERSION-INFO:END -->

It also updates the version number in the existing footer. Everything else in
about.html, including the runtime update_status.json JavaScript, is preserved.
"""

from __future__ import annotations

import argparse
import html
import json
import os
import re
import tempfile
from datetime import date, datetime
from pathlib import Path
from typing import Any
from site_navigation import navigation as site_navigation

DEFAULT_ABOUT = Path("site/about.html")
DEFAULT_VERSION = Path("data/version.json")
DEFAULT_RELEASE_NOTES = Path("site/release_notes.md")

START_MARKER = "<!-- VERSION-INFO:START -->"
END_MARKER = "<!-- VERSION-INFO:END -->"

VERSION_BLOCK_RX = re.compile(
    rf"{re.escape(START_MARKER)}.*?{re.escape(END_MARKER)}",
    re.DOTALL,
)
FOOTER_RX = re.compile(
    r'(<div class="footer">Automotive Cybersecurity Dashboard · )(?:Version [^·<]+ · )?'
    r'(Evidence-based threat analysis research prototype</div>)'
)


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Update version, release notes and contact information in about.html."
    )
    parser.add_argument("--about", type=Path, default=DEFAULT_ABOUT)
    parser.add_argument("--version", type=Path, default=DEFAULT_VERSION)
    parser.add_argument("--release-notes", type=Path, default=DEFAULT_RELEASE_NOTES)
    parser.add_argument(
        "--check",
        action="store_true",
        help="Validate inputs and show what would change without writing about.html.",
    )
    return parser.parse_args()


def load_json(path: Path) -> dict[str, Any]:
    if not path.is_file():
        raise FileNotFoundError(f"Version metadata not found: {path}")
    with path.open("r", encoding="utf-8") as handle:
        data = json.load(handle)
    if not isinstance(data, dict):
        raise ValueError(f"Expected a JSON object in {path}")
    return data


def required_text(data: dict[str, Any], key: str) -> str:
    value = str(data.get(key, "")).strip()
    if not value:
        raise ValueError(f"Missing required field {key!r} in version metadata")
    return value


def validate_email(value: str) -> str:
    value = value.strip()
    if not re.fullmatch(r"[^\s@]+@[^\s@]+\.[^\s@]+", value):
        raise ValueError(f"Invalid contact_email: {value!r}")
    return value


def display_date(value: str) -> str:
    """Convert ISO YYYY-MM-DD to a stable English display date."""
    try:
        parsed = date.fromisoformat(value)
    except ValueError:
        return value
    return f"{parsed.day} {parsed.strftime('%B')} {parsed.year}"


def inline_markdown(text: str) -> str:
    """Render a deliberately small, safe subset of Markdown inline syntax."""
    rendered = html.escape(text, quote=True)
    rendered = re.sub(r"`([^`]+)`", r"<code>\1</code>", rendered)
    rendered = re.sub(r"\*\*([^*]+)\*\*", r"<strong>\1</strong>", rendered)
    return rendered


def release_notes_to_html(markdown: str) -> str:
    """Render headings, bullets and paragraphs used by release_notes.md."""
    output: list[str] = []
    in_list = False

    def close_list() -> None:
        nonlocal in_list
        if in_list:
            output.append("        </ul>")
            in_list = False

    for raw_line in markdown.splitlines():
        line = raw_line.strip()

        if not line:
            close_list()
            continue

        if line.startswith("# "):
            # Document title is redundant inside the already labelled details block.
            continue

        if line.startswith("## "):
            close_list()
            output.append(f"        <h3>{inline_markdown(line[3:].strip())}</h3>")
            continue

        if line.startswith("### "):
            close_list()
            output.append(f"        <h4>{inline_markdown(line[4:].strip())}</h4>")
            continue

        if line.startswith(("- ", "* ")):
            if not in_list:
                output.append("        <ul>")
                in_list = True
            output.append(f"          <li>{inline_markdown(line[2:].strip())}</li>")
            continue

        close_list()
        output.append(f"        <p>{inline_markdown(line)}</p>")

    close_list()

    if not output:
        output.append('        <p class="small muted">No release notes available.</p>')

    return "\n".join(output)


def build_version_block(
    version: str,
    release_date: str,
    contact_email: str,
    contact_label: str,
    release_notes_html: str,
) -> str:
    version_e = html.escape(version, quote=True)
    released_e = html.escape(display_date(release_date), quote=True)
    email_e = html.escape(contact_email, quote=True)
    contact_label_e = html.escape(contact_label, quote=True)

    return f'''{START_MARKER}
  <section class="card" id="version-info">
    <h2>Version &amp; contact</h2>
    <p>Release information and contact details for the Automotive Cybersecurity Dashboard research prototype.</p>

    <div class="version-grid">
      <div class="version-item">
        <span class="version-label">Version</span>
        <span class="version-value">{version_e}</span>
      </div>

      <div class="version-item">
        <span class="version-label">Released</span>
        <span class="version-value">{released_e}</span>
      </div>

      <div class="version-item">
        <span class="version-label">Contact</span>
        <span class="version-value"><a href="mailto:{email_e}">{contact_label_e}</a></span>
      </div>
    </div>
    <p class="small muted">Any questions or suggestions? Feel free to reach out.</p>
    <details class="release-notes">
      <summary>Release notes</summary>
      <div class="release-notes-content">
{release_notes_html}
      </div>
    </details>
  </section>
  {END_MARKER}'''



def update_threat_register_section(about: str) -> str:
    start = '  <section class="card">\n    <h2>The Threat Register at the centre</h2>'
    end = '  <section class="card">\n    <h2>Evidence sources</h2>'
    start_pos = about.find(start)
    end_pos = about.find(end, start_pos + 1)
    if start_pos < 0 or end_pos < 0:
        raise ValueError("Could not locate The Threat Register at the centre section")
    section = '  <section class="card">\n    <h2>The Threat Register at the centre</h2>\n    <p>Different evidence sources describe different parts of the cybersecurity landscape. The Threat Register brings those sources together around the risk question. In addition to observable external evidence, threats can now be related to applicable regulatory requirements and analytical regulatory mappings. This keeps evidence, risk analysis and regulatory traceability connected without treating correlation or regulatory relevance as proof of compliance.</p>\n    <div class="model" aria-label="Conceptual threat, evidence and regulatory model">\n      <div class="model-register">Threat Register</div>\n      <div class="model-line"></div>\n      <div class="model-sources">\n        <span class="model-source">CVEs</span>\n        <span class="model-source">Papers</span>\n        <span class="model-source">Repositories</span>\n        <span class="model-source">Signals</span>\n        <span class="model-source">Incidents</span>\n        <span class="model-source">Assessments</span>\n        <span class="model-source">Narratives</span>\n      </div>\n      <div class="model-line"></div>\n      <div class="model-sources">\n        <span class="model-source">UN R155 requirements</span>\n        <span class="model-source">Annex 5 analytical candidates</span>\n        <span class="model-source">Regulatory Hub</span>\n      </div>\n      <div class="model-line"></div>\n      <div class="model-sources">\n        <span class="model-source">Accepted evidence</span>\n        <span class="model-source">Review candidates</span>\n        <span class="model-source">Evidence gaps</span>\n        <span class="model-source">Expert review</span>\n      </div>\n    </div>\n    <p class="small muted" style="margin-top:14px;">The Regulatory Hub complements this threat-level traceability by explaining the wider regulatory frameworks, official sources, expert views and unresolved regulatory questions.</p>\n  </section>\n'
    return about[:start_pos] + section + about[end_pos:]

def update_navigation(about: str) -> str:
    pattern = re.compile(r'<header class="site-header">.*?</header>', re.DOTALL)
    updated, count = pattern.subn(lambda _: site_navigation("About"), about, count=1)
    if count != 1:
        raise ValueError(f"Expected exactly one site header; found {count}")
    return updated

def atomic_write(path: Path, text: str) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    fd, temp_name = tempfile.mkstemp(prefix=path.name + ".", suffix=".tmp", dir=path.parent)
    temp_path = Path(temp_name)
    try:
        with os.fdopen(fd, "w", encoding="utf-8", newline="") as handle:
            handle.write(text)
            handle.flush()
            os.fsync(handle.fileno())
        os.replace(temp_path, path)
    finally:
        if temp_path.exists():
            temp_path.unlink()


def main() -> int:
    args = parse_args()

    if not args.about.is_file():
        raise FileNotFoundError(f"About page not found: {args.about}")
    if not args.release_notes.is_file():
        raise FileNotFoundError(f"Release notes not found: {args.release_notes}")

    metadata = load_json(args.version)
    version = required_text(metadata, "version")
    release_date = required_text(metadata, "release_date")
    contact_email = validate_email(required_text(metadata, "contact_email"))
    contact_label = str(metadata.get("contact_label", contact_email)).strip() or contact_email

    release_notes = args.release_notes.read_text(encoding="utf-8")
    about = args.about.read_text(encoding="utf-8")

    matches = VERSION_BLOCK_RX.findall(about)
    if len(matches) != 1:
        raise ValueError(
            f"Expected exactly one VERSION-INFO block in {args.about}; found {len(matches)}"
        )

    block = build_version_block(
        version=version,
        release_date=release_date,
        contact_email=contact_email,
        contact_label=contact_label,
        release_notes_html=release_notes_to_html(release_notes),
    )
    updated = VERSION_BLOCK_RX.sub(lambda _: block, about, count=1)
    updated = update_threat_register_section(updated)
    updated = update_navigation(updated)

    footer_replacement = rf"\g<1>Version {html.escape(version)} · \g<2>"
    updated, footer_count = FOOTER_RX.subn(footer_replacement, updated, count=1)
    if footer_count != 1:
        raise ValueError("Could not locate the expected dashboard footer")

    changed = updated != about

    if args.check:
        print(f"[ABOUT] Version: {version}")
        print(f"[ABOUT] Release date: {release_date}")
        print(f"[ABOUT] Contact: {contact_email}")
        print(f"[ABOUT] Would change: {'yes' if changed else 'no'}")
        return 0

    if not changed:
        print(f"[ABOUT] {args.about} already up to date (version {version})")
        return 0

    atomic_write(args.about, updated)
    print(f"[ABOUT] Updated {args.about}")
    print(f"[ABOUT] Version {version} · {display_date(release_date)} · {contact_email}")
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except (FileNotFoundError, ValueError, OSError, json.JSONDecodeError) as exc:
        print(f"ERROR: {exc}", file=__import__("sys").stderr)
        raise SystemExit(2)
