#!/usr/bin/env python3
"""Generate a searchable OE6VAG index from Umberto Alessio's public file list.

This indexes document metadata and hyperlinks only. It never downloads PDFs.
The output is a standalone HTML index and an optional supplement for the
existing Radio Document Search. Python's standard library is sufficient.
"""

from __future__ import annotations

import argparse
import json
import re
import unicodedata
from collections import Counter
from datetime import datetime
from html import escape
from html.parser import HTMLParser
from pathlib import Path
from urllib.parse import unquote, urljoin, urlparse
from urllib.request import Request, urlopen


SOURCE_URL = "https://www.umberto-alessio.it/Radio%20Schematics/"
OUTPUT_HTML = "umberto_radio_schematics_index.html"
OUTPUT_JSON = "umberto-search-index.json"


def collapse_space(value: str) -> str:
    return " ".join(value.split())


class FileListParser(HTMLParser):
    """Read pairs of (linked filename, size) inside the site's file table."""

    def __init__(self) -> None:
        super().__init__(convert_charrefs=True)
        self.table_depth = 0
        self.cells: list[dict] = []
        self.cell: dict | None = None
        self.records: list[dict] = []

    def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
        attrs_by_name = dict(attrs)
        if tag == "table":
            if self.table_depth:
                self.table_depth += 1
            elif attrs_by_name.get("summary") == "file table":
                self.table_depth = 1
            return
        if not self.table_depth:
            return
        if tag == "tr":
            self.cells = []
        elif tag == "td":
            self.cell = {"text": [], "href": None}
        elif tag == "a" and self.cell is not None:
            self.cell["href"] = attrs_by_name.get("href")

    def handle_data(self, data: str) -> None:
        if self.cell is not None:
            self.cell["text"].append(data)

    def handle_endtag(self, tag: str) -> None:
        if not self.table_depth:
            return
        if tag == "td" and self.cell is not None:
            self.cell["text"] = collapse_space("".join(self.cell["text"]))
            self.cells.append(self.cell)
            self.cell = None
        elif tag == "tr":
            for left, right in zip(self.cells[::2], self.cells[1::2]):
                href = left["href"]
                if not href or not href.lower().endswith(".pdf"):
                    continue
                resolved = urljoin(SOURCE_URL, href)
                parsed = urlparse(resolved)
                if parsed.scheme != "https" or parsed.netloc != "www.umberto-alessio.it":
                    raise ValueError(f"Unexpected link destination: {href}")
                path_parts = href.split("/")
                if len(path_parts) != 2:
                    raise ValueError(f"Unexpected archive path: {href}")
                brand = collapse_space(unquote(path_parts[0]))
                self.records.append(
                    {
                        "brand": brand,
                        "filename": left["text"],
                        "size": right["text"],
                        "url": resolved,
                    }
                )
        elif tag == "table":
            self.table_depth -= 1


def normalize(text: str) -> str:
    """Match the normalization used by the global Radio Document Search."""
    text = unicodedata.normalize("NFD", text).replace("ß", "ss")
    text = re.sub(r"[\u0300-\u036f]", "", text)
    text = re.sub(r"[_.\-/,;:()\[\]+]", " ", text)
    return collapse_space(text).lower()


def last_updated(source_html: str) -> str:
    without_tags = re.sub(r"<[^>]+>", " ", source_html)
    match = re.search(r"Last Updated\s+(\w+)\s+(\d+)(?:st|nd|rd|th)?\s+(\d{4})", without_tags)
    if not match:
        return "date not specified"
    try:
        return datetime.strptime(" ".join(match.groups()), "%b %d %Y").strftime("%d %B %Y")
    except ValueError:
        return "date not specified"


def make_page(records: list[dict], source_date: str) -> str:
    safe_inline_data = json.dumps(records, ensure_ascii=False, separators=(",", ":")).replace("<", "\\u003c")
    counts = Counter(r["brand"] for r in records)
    brands = sorted(counts, key=str.casefold)
    options = "\n".join(
        f'<option value="{escape(b, quote=True)}">{escape(b)} ({counts[b]:,})</option>'
        for b in brands
    )
    page = r'''<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Umberto Alessio Radio Schematics Index | OE6VAG</title>
<meta name="description" content="Search __COUNT__ historical radio schematics by manufacturer and model, with direct links to the original PDFs in Umberto Alessio's collection.">
<link rel="canonical" href="https://oe6vag.net/downloads/index/umberto_radio_schematics_index.html">
<style>
:root { color-scheme:light; --ink:#1f2937; --muted:#576474; --line:#d8dee5; --blue:#17548b; --bg:#fbfcfe; --card:#fff; }
* { box-sizing:border-box; }
body { margin:0 auto; max-width:1120px; padding:28px 22px 50px; color:var(--ink); font:15px/1.48 system-ui,-apple-system,"Segoe UI",sans-serif; background:var(--bg); }
h1 { font-size:clamp(1.65rem,3vw,2.2rem); margin:0 0 .4rem; line-height:1.22; }
p { margin:.5rem 0; }
a { color:var(--blue); }
.eyebrow { margin-bottom:.6rem; color:var(--muted); font-size:.86rem; text-transform:uppercase; letter-spacing:.045em; }
.lead { color:var(--muted); max-width:900px; }
.source { background:#f3f0e8; border:1px solid #dfd8c6; border-radius:9px; padding:10px 13px; margin:16px 0; }
.source small { color:#5b5445; }
.stats { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:10px; margin:16px 0; }
.stat { background:var(--card); border:1px solid var(--line); border-radius:9px; padding:12px; }
.stat strong { display:block; font-size:1.35rem; }
.stat span { font-size:.82rem; color:var(--muted); }
.filters { display:grid; grid-template-columns:minmax(240px,1fr) minmax(190px,260px) auto; align-items:end; gap:10px; border:1px solid var(--line); border-radius:9px; background:var(--card); padding:12px; }
label { display:block; font-weight:600; font-size:.82rem; margin-bottom:5px; }
input,select,button { width:100%; font:inherit; border:1px solid #b9c3cf; border-radius:7px; background:white; color:var(--ink); padding:9px 10px; min-height:42px; }
button { cursor:pointer; font-weight:600; white-space:nowrap; }
button:hover { background:#e9f2fa; }
.count { color:var(--muted); margin:13px 0 8px; }
.table-wrap { overflow-x:auto; border:1px solid var(--line); border-radius:9px; background:var(--card); }
table { width:100%; border-collapse:collapse; }
th,td { text-align:left; border-bottom:1px solid #e8edf2; padding:10px 12px; vertical-align:top; }
th { background:#f2f5f8; font-size:.84rem; }
td a { font-weight:600; overflow-wrap:anywhere; text-decoration:none; }
td a:hover { text-decoration:underline; }
td.brand,td.size { color:var(--muted); font-size:.88rem; }
td.size { white-space:nowrap; }
.more { display:block; width:100%; margin-top:10px; background:#f2f7fb; }
.footer { margin-top:22px; color:var(--muted); font-size:.85rem; }
[hidden] { display:none!important; }
@media(max-width:700px){body{padding:18px 12px}.stats{grid-template-columns:repeat(2,minmax(0,1fr))}.filters{grid-template-columns:1fr}.size{display:none}th,td{padding:9px 8px}}
</style>
</head>
<body>
<p class="eyebrow">OE6VAG Radio Document Archive · External collection</p>
<h1>Umberto Alessio Radio Schematics Index</h1>
<p class="lead">Search historic radio circuit diagrams and service documents by manufacturer and model. Each result links directly to its original PDF; no PDFs are hosted on OE6VAG.net.</p>
<div class="source"><strong>Original collection:</strong> <a href="https://www.umberto-alessio.it/Radio%20Schematics/" target="_blank" rel="noopener noreferrer">Radio Schematics by Umberto Alessio</a><br><small>Source list last updated: __UPDATED__ · Document titles and sizes originate from the publisher's directory listing.</small></div>
<div class="stats">
<div class="stat"><strong>__COUNT_FORMATTED__</strong><span>direct PDF links</span></div>
<div class="stat"><strong>__BRANDS__</strong><span>manufacturers</span></div>
<div class="stat"><strong>__YEAR__</strong><span>source's last reported update</span></div>
</div>
<div class="filters" role="search">
<div><label for="q">Search manufacturer, model or filename</label><input id="q" type="search" placeholder="e.g. Geloso G207, Minerva, Telefunken" autocomplete="off"></div>
<div><label for="brand">Manufacturer</label><select id="brand"><option value="">All manufacturers</option>__BRAND_OPTIONS__</select></div>
<div><button id="reset" type="button">Clear filters</button></div>
</div>
<p id="count" class="count" role="status" aria-live="polite"></p>
<div class="table-wrap"><table><thead><tr><th>Document / model</th><th>Manufacturer</th><th class="size">Original size</th></tr></thead><tbody id="results"></tbody></table></div>
<button type="button" id="more" class="more" hidden>Show 200 more results</button>
<p class="footer">This is a searchable metadata index of an independently hosted archive. The publisher retains control over the PDF files and their availability. <a href="https://oe6vag.net/downloads/search/">Back to overall Radio Document Search</a>.</p>
<script>
const documents = __INLINE_DATA__;
const searchInput = document.getElementById('q');
const brandSelect = document.getElementById('brand');
const resultsBody = document.getElementById('results');
const count = document.getElementById('count');
const more = document.getElementById('more');
const params = new URLSearchParams(window.location.search);
searchInput.value = params.get('q') || '';
if ([...brandSelect.options].some(option => option.value === params.get('brand'))) brandSelect.value = params.get('brand') || '';
let visible = 200;
let matches = documents;
function normalize(value) {
  return String(value || '').normalize('NFD').replace(/[\u0300-\u036f]/g, '')
    .replace(/ß/g, 'ss').replace(/[_.\-/,;:()[\]+]/g, ' ')
    .toLowerCase().replace(/\s+/g, ' ').trim();
}
function escapeHtml(text) {
  return String(text ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
}
const indexed = documents.map(doc => normalize(doc.brand + ' ' + doc.filename));
function render(resetPage = true) {
  if (resetPage) visible = 200;
  const terms = normalize(searchInput.value).split(' ').filter(Boolean);
  const brand = brandSelect.value;
  matches = documents.filter((doc, i) => (!brand || doc.brand === brand) && terms.every(term => indexed[i].includes(term)));
  const display = matches.slice(0, visible);
  resultsBody.innerHTML = display.length ? display.map(doc => `<tr><td><a href="${escapeHtml(doc.url)}" target="_blank" rel="noopener noreferrer">${escapeHtml(doc.filename)}</a></td><td class="brand">${escapeHtml(doc.brand)}</td><td class="size">${escapeHtml(doc.size)}</td></tr>`).join('') : '<tr><td colspan="3">No matching documents. Try another model or manufacturer.</td></tr>';
  count.textContent = `${matches.length.toLocaleString('en-US')} matching documents · ${display.length.toLocaleString('en-US')} displayed`;
  more.hidden = display.length >= matches.length;
}
searchInput.addEventListener('input', () => render());
brandSelect.addEventListener('change', () => render());
document.getElementById('reset').addEventListener('click', () => { searchInput.value = ''; brandSelect.value = ''; render(); searchInput.focus(); });
more.addEventListener('click', () => { visible += 200; render(false); });
render();
</script>
</body>
</html>
'''
    for token, value in {
        "__INLINE_DATA__": safe_inline_data,
        "__BRAND_OPTIONS__": options,
        "__COUNT__": str(len(records)),
        "__COUNT_FORMATTED__": f"{len(records):,}",
        "__BRANDS__": str(len(brands)),
        "__UPDATED__": escape(source_date),
        "__YEAR__": source_date.rsplit(" ", 1)[-1] if source_date != "date not specified" else "Unknown",
    }.items():
        page = page.replace(token, value)
    return page


def main() -> None:
    args = argparse.ArgumentParser(description=__doc__)
    args.add_argument("--source-html", type=Path, help="Use a downloaded HTML file instead of fetching the website")
    args.add_argument("--output-dir", type=Path, default=Path("."))
    opts = args.parse_args()
    if opts.source_html:
        source = opts.source_html.read_text(encoding="utf-8")
    else:
        request = Request(SOURCE_URL, headers={"User-Agent": "OE6VAG-Archive-Indexer/1.0 (metadata only)"})
        with urlopen(request, timeout=45) as response:
            source = response.read().decode("utf-8")
    parser = FileListParser()
    parser.feed(source)
    records = sorted(parser.records, key=lambda r: (r["brand"].casefold(), r["filename"].casefold()))
    if len(records) < 100 or len({r["url"] for r in records}) != len(records):
        raise RuntimeError("Source unexpectedly small or contains duplicate PDF URLs; refusing to publish")
    if any(not r["filename"] or not re.fullmatch(r"[\d,]+\s*K", r["size"]) for r in records):
        raise RuntimeError("Unexpected filename or size format; inspect source structure")

    search = [
        {
            "type": "external_pdf",
            "title": rec["filename"],
            "url": rec["url"],
            "brand": rec["brand"],
            "context": "Umberto Alessio – Radio Schematics",
            "search_text": normalize(rec["brand"] + " " + rec["filename"] + " Umberto Alessio Radio Schematics"),
        }
        for rec in records
    ]
    opts.output_dir.mkdir(parents=True, exist_ok=True)
    (opts.output_dir / OUTPUT_HTML).write_text(make_page(records, last_updated(source)), encoding="utf-8")
    (opts.output_dir / OUTPUT_JSON).write_text(json.dumps(search, ensure_ascii=False, separators=(",", ":")) + "\n", encoding="utf-8")
    print(f"Generated {len(records):,} direct PDF entries from {len(set(r['brand'] for r in records))} manufacturers")
    print("Largest manufacturer groups:", ", ".join(f"{brand}: {n}" for brand, n in Counter(r["brand"] for r in records).most_common(6)))
    print("Written:", opts.output_dir / OUTPUT_HTML, "and", opts.output_dir / OUTPUT_JSON)


if __name__ == "__main__":
    main()
