#!/usr/bin/env python3
"""Build an RSP-Italy stand-alone OE6VAG index and global-search supplement.

The input is a cached inventory of public HTML-directory hyperlinks. This
generator makes NO network requests and downloads NO PDFs. Different source
URLs remain independent records, even if filenames match another collection.
"""

from __future__ import annotations

import argparse
import json
import re
import unicodedata
from collections import Counter
from datetime import date
from html import escape
from pathlib import Path
from urllib.parse import urlparse


SOURCE_URL = "https://www.rsp-italy.it/Electronics/Radio%20Schematics/"
PUBLIC_INDEX = "https://oe6vag.net/downloads/index/rsp_italy_radio_schematics_index.html"
OUTPUT_HTML = "rsp_italy_radio_schematics_index.html"
OUTPUT_JSON = "rsp-italy-search-index.json"


def normalize(text: str) -> str:
    text = unicodedata.normalize("NFD", str(text)).replace("ß", "ss")
    text = re.sub(r"[\u0300-\u036f]", "", text)
    text = re.sub(r"[_.\-/,;:()\[\]+]", " ", text)
    return " ".join(text.lower().split())


def prepare(inventory: dict) -> list[dict]:
    seen = set()
    documents = []
    for r in inventory["records"]:
        url = r["url"]
        parsed = urlparse(url)
        if parsed.scheme != "https" or parsed.hostname != "www.rsp-italy.it" or not parsed.path.lower().endswith(".pdf"):
            raise RuntimeError(f"Unexpected source link: {url!r}")
        if url in seen:
            continue  # Duplicate anchors inside the SAME RSP directory only.
        seen.add(url)
        filename = r["filename"].strip()
        if not filename or "<" in filename or "\n" in filename:
            raise RuntimeError(f"Unusable source filename: {filename!r}")
        documents.append({
            "brand": r["brand"].strip(),
            "filename": filename,
            "url": url,
            "collection": bool(r["collection"]),
        })
    documents.sort(key=lambda r: (r["collection"], r["brand"].casefold(), r["filename"].casefold(), r["url"]))
    if len(documents) < 6000:
        raise RuntimeError(f"Unexpectedly small RSP index ({len(documents)} URLs): refusing to generate")
    if inventory["failed_pages"]:
        raise RuntimeError("Some RSP directory pages could not be scanned; review inventory first")
    return documents


def make_search_json(documents: list[dict]) -> list[dict]:
    result = []
    for d in documents:
        context = "RSP Italy – Beitman / Riders collections" if d["collection"] else "RSP Italy – Radio Schematics"
        result.append({
            "type": "external_pdf",
            "title": d["filename"],
            "url": d["url"],
            "brand": d["brand"],
            "context": context,
            "search_text": normalize(f"{d['brand']} {d['filename']} {context}"),
        })
    return result


def make_page(documents: list[dict], checked: str) -> str:
    by_brand = Counter(d["brand"] for d in documents)
    options = "\n".join(f'<option value="{escape(b, quote=True)}">{escape(b)} ({by_brand[b]:,})</option>' for b in sorted(by_brand, key=str.casefold))
    data = json.dumps(documents, ensure_ascii=False, separators=(",", ":")).replace("<", "\\u003c")
    manufacturer_count = len({d["brand"] for d in documents if not d["collection"]})
    collection_count = sum(d["collection"] for d in documents)

    template = r'''<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>RSP Italy Radio Schematics Index | OE6VAG</title>
<meta name="description" content="Search __COUNT__ public links to historical radio schematics and service documents in RSP Italy's collection, organized by manufacturer and model.">
<link rel="canonical" href="__CANONICAL__">
<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(220px,1fr) minmax(180px,250px) minmax(155px,190px) 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.type { color:var(--muted); font-size:.88rem; }
.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:780px){body{padding:18px 12px}.stats{grid-template-columns:repeat(2,minmax(0,1fr))}.filters{grid-template-columns:1fr}th,td{padding:9px 8px}}
</style>
</head>
<body>
<p class="eyebrow">OE6VAG Radio Document Archive · External collection</p>
<h1>RSP Italy Radio Schematics Index</h1>
<p class="lead">Search historical circuit diagrams and service documents by manufacturer and radio model. Each document links to the publisher's PDF; OE6VAG.net hosts the searchable index only. Multiple sources for the same model remain available in the overall search.</p>
<div class="source"><strong>Original collection:</strong> <a href="__SOURCE__" target="_blank" rel="noopener noreferrer">RSP Italy – Radio Schematics</a><br><small>Public directory links checked on __CHECKED__. Direct PDF availability and content are controlled by the publisher.</small></div>
<div class="stats">
<div class="stat"><strong>__COUNT_FORMATTED__</strong><span>distinct PDF links</span></div>
<div class="stat"><strong>__MANUFACTURERS__</strong><span>manufacturer directories</span></div>
<div class="stat"><strong>__COLLECTIONS__</strong><span>Beitman and Riders volumes</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, Graetz, Nordmende" autocomplete="off"></div>
<div><label for="brand">Manufacturer / collection</label><select id="brand"><option value="">All manufacturers</option>__BRAND_OPTIONS__</select></div>
<div><label for="kind">Document group</label><select id="kind"><option value="">All PDFs</option><option value="maker">Manufacturer schematics</option><option value="collection">Beitman / Riders volumes</option></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>Document group</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 directory for an independent collection. Source documents are not copied or mirrored. <a href="https://oe6vag.net/downloads/search/">Back to overall Radio Document Search</a>.</p>
<script>
const documents = __INLINE_DATA__;
const q = document.getElementById('q');
const brandSelect = document.getElementById('brand');
const kindSelect = document.getElementById('kind');
const resultsBody = document.getElementById('results');
const count = document.getElementById('count');
const more = document.getElementById('more');
const params = new URLSearchParams(window.location.search);
q.value = params.get('q') || '';
if ([...brandSelect.options].some(o => o.value === params.get('brand'))) brandSelect.value = params.get('brand') || '';
if ([...kindSelect.options].some(o => o.value === params.get('kind'))) kindSelect.value = params.get('kind') || '';
let visible = 200;
let matches = [];
function normalize(value) {
  return String(value || '').normalize('NFD').replace(/[\u0300-\u036f]/g, '')
    .replace(/ß/g,'ss').replace(/[_.\-/,;:()[\]+]/g,' ')
    .toLowerCase().replace(/\s+/g,' ').trim();
}
function escapeHtml(value) {
  return String(value ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
}
const indexed = documents.map(d => normalize(d.brand + ' ' + d.filename));
function render(reset = true) {
  if (reset) visible = 200;
  const terms = normalize(q.value).split(' ').filter(Boolean);
  const brand = brandSelect.value;
  const kind = kindSelect.value;
  matches = documents.filter((d, i) => (!brand || d.brand === brand) && (!kind || (kind === 'collection') === d.collection) && terms.every(t => indexed[i].includes(t)));
  const page = matches.slice(0, visible);
  resultsBody.innerHTML = page.length ? page.map(d => `<tr><td><a href="${escapeHtml(d.url)}" target="_blank" rel="noopener noreferrer">${escapeHtml(d.filename)}</a></td><td class="brand">${escapeHtml(d.brand)}</td><td class="type">${d.collection ? 'Reference volume' : 'Manufacturer PDF'}</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 PDFs · ${page.length.toLocaleString('en-US')} displayed`;
  more.hidden = page.length >= matches.length;
}
q.addEventListener('input', () => render());
brandSelect.addEventListener('change', () => render());
kindSelect.addEventListener('change', () => render());
document.getElementById('reset').addEventListener('click', () => { q.value=''; brandSelect.value=''; kindSelect.value=''; render(); q.focus(); });
more.addEventListener('click', () => { visible += 200; render(false); });
render();
</script>
</body>
</html>
'''
    values = {
        "__INLINE_DATA__": data,
        "__BRAND_OPTIONS__": options,
        "__COUNT__": str(len(documents)),
        "__COUNT_FORMATTED__": f"{len(documents):,}",
        "__MANUFACTURERS__": str(manufacturer_count),
        "__COLLECTIONS__": str(collection_count),
        "__CHECKED__": checked,
        "__SOURCE__": SOURCE_URL,
        "__CANONICAL__": PUBLIC_INDEX,
    }
    for token, replacement in values.items():
        template = template.replace(token, replacement)
    if "__INLINE_DATA__" in template or "__COUNT__" in template:
        raise AssertionError("Unsubstituted template variable")
    return template


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--inventory", type=Path, default=Path(__file__).with_name("inventory.json"))
    parser.add_argument("--output-dir", type=Path, default=Path("."))
    parser.add_argument("--checked", default=date.today().isoformat(), help="Date on which public source links were inventoried")
    opts = parser.parse_args()
    inv = json.loads(opts.inventory.read_text(encoding="utf-8"))
    docs = prepare(inv)
    opts.output_dir.mkdir(parents=True, exist_ok=True)
    standalone = opts.output_dir / OUTPUT_HTML
    supplement = opts.output_dir / OUTPUT_JSON
    standalone.write_text(make_page(docs, opts.checked), encoding="utf-8")
    supplement.write_text(json.dumps(make_search_json(docs), ensure_ascii=False, separators=(",", ":")) + "\n", encoding="utf-8")
    print(f"{len(docs):,} unique PDF links: {standalone} and {supplement}")


if __name__ == "__main__":
    main()
