#!/usr/bin/env python3
"""Generate OE6VAG indexes for HRCS / Radiojournal's public PDF link lists.

Fetches only six HTML directory pages, never the PDFs. Multiple model names
pointing to one PDF URL are retained as searchable aliases. Same-named PDFs on
other publisher sites are deliberately not de-duplicated.
"""

from __future__ import annotations

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

from lxml import html


COLLECTION = "https://www.radiojournal.cz/schemata.htm"
CANONICAL = "https://oe6vag.net/downloads/index/radiojournal_schematics_index.html"
SOURCES = OrderedDict([
    ("Radios", "https://www.radiojournal.cz/schemata.htm"),
    ("Televisions", "https://www.radiojournal.cz/schemata2.htm"),
    ("Record players", "https://www.radiojournal.cz/schemata3.htm"),
    ("Tape recorders", "https://www.radiojournal.cz/schemata4.htm"),
    ("Amplifiers", "https://www.radiojournal.cz/schemata5.htm"),
    ("Other equipment", "https://www.radiojournal.cz/schemata6.htm"),
])


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


def collapse(text: str) -> str:
    return " ".join(text.split())


def get_sources(source_dir: Path, fetch: bool) -> dict[str, bytes]:
    result: dict[str, bytes] = {}
    for category, url in SOURCES.items():
        filename = Path(urlparse(url).path).name
        saved = source_dir / filename
        if fetch or not saved.is_file():
            req = Request(url, headers={"User-Agent": "OE6VAG-Radiojournal-Indexer/1.0 (HTML metadata only)"})
            with urlopen(req, timeout=30) as response:
                raw = response.read()
                if response.status != 200 or len(raw) < 1000:
                    raise RuntimeError(f"Bad response for {url}: status {response.status}, length {len(raw)}")
        else:
            raw = saved.read_bytes()
        result[category] = raw
    return result


def extract_documents(sources: dict[str, bytes]) -> tuple[list[dict], dict]:
    by_url: OrderedDict[str, dict] = OrderedDict()
    info = {}
    for category, source_url in SOURCES.items():
        root = html.fromstring(sources[category], base_url=source_url)
        count = 0
        for anchor in root.xpath('//a[@href]'):
            href = anchor.get("href", "").strip()
            resolved = urljoin(source_url, href)
            parsed = urlparse(resolved)
            if parsed.scheme not in {"https", "http"} or not parsed.path.casefold().endswith(".pdf"):
                continue
            count += 1
            title = collapse(anchor.text_content()) or parsed.path.rsplit("/", 1)[-1]
            if not title:
                continue
            if resolved not in by_url:
                by_url[resolved] = {
                    "url": resolved,
                    "filename": parsed.path.rsplit("/", 1)[-1],
                    "titles": [],
                    "categories": [],
                }
            doc = by_url[resolved]
            if title not in doc["titles"]:
                doc["titles"].append(title)
            if category not in doc["categories"]:
                doc["categories"].append(category)
        info[category] = {"anchors": count, "page": source_url}
    docs = sorted(by_url.values(), key=lambda d: (d["categories"][0], d["titles"][0].casefold(), d["url"]))
    if len(docs) < 450:
        raise RuntimeError(f"Only {len(docs)} PDFs found; source pages or their structure may have changed")
    return docs, info


def search_records(documents: list[dict]) -> list[dict]:
    records = []
    for d in documents:
        label = " / ".join(d["titles"])
        categories = ", ".join(d["categories"])
        records.append({
            "type": "external_pdf",
            "title": label,
            "url": d["url"],
            "context": f"Radiojournal.cz – {categories} (Historický radioklub československý)",
            "search_text": norm(f"{label} {d['filename']} {categories} Radiojournal.cz HRCS Historický radioklub československý"),
        })
    return records


def stand_alone(documents: list[dict], inspected: str) -> str:
    compact = json.dumps(documents, ensure_ascii=False, separators=(",", ":")).replace("<", "\\u003c")
    counts = Counter(d["categories"][0] for d in documents)
    options = "".join(f'<option value="{escape(cat, quote=True)}">{escape(cat)} ({counts[cat]})</option>' for cat in SOURCES)
    html_page = r'''<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Radiojournal.cz Historical Schematics Index | OE6VAG</title>
<meta name="description" content="Search __COUNT__ historical Czechoslovak radio, TV, audio and electronic equipment schematics with direct links to original Radiojournal PDFs.">
<link rel="canonical" href="__CANONICAL__">
<style>
:root{--ink:#202b36;--muted:#586576;--line:#d8e1ea;--blue:#14558c;--bg:#fbfcfe}
*{box-sizing:border-box}body{max-width:1100px;margin:0 auto;padding:28px 22px 48px;background:var(--bg);color:var(--ink);font:15px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif}
h1{font-size:clamp(1.65rem,3vw,2.15rem);margin:0 0 .5rem}a{color:var(--blue)}p{margin:.55rem 0}
.eyebrow{font-size:.85rem;text-transform:uppercase;letter-spacing:.06em;color:var(--muted)}.lead{color:var(--muted)}
.source{padding:12px 14px;margin:18px 0;border:1px solid #dfd8c6;border-radius:8px;background:#f3f0e8}
.stats{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px;margin:18px 0}.stat{background:white;border:1px solid var(--line);border-radius:9px;padding:12px}.stat strong{display:block;font-size:1.32rem}.stat span{font-size:.82rem;color:var(--muted)}
.filters{display:grid;grid-template-columns:minmax(230px,1fr) minmax(200px,260px) auto;gap:10px;align-items:end;padding:12px;background:white;border:1px solid var(--line);border-radius:9px}
label{display:block;font-size:.82rem;font-weight:700;margin-bottom:5px}input,select,button{width:100%;min-height:42px;padding:9px 11px;font:inherit;border:1px solid #bbc8d5;border-radius:7px;background:white;color:var(--ink)}button{cursor:pointer;font-weight:650}button:hover{background:#eef6fc}
.count{margin:13px 0 8px;color:var(--muted)}.table-wrap{overflow-x:auto;background:white;border:1px solid var(--line);border-radius:9px}table{width:100%;border-collapse:collapse}th,td{padding:10px 12px;border-bottom:1px solid #e8edf2;text-align:left;vertical-align:top}th{background:#f2f5f8;font-size:.85rem}td a{font-weight:650;text-decoration:none;overflow-wrap:anywhere}td a:hover{text-decoration:underline}.sub{font-size:.83rem;color:var(--muted)}.more{margin-top:10px;background:#f0f6fb}.footer{margin-top:22px;font-size:.87rem;color:var(--muted)}[hidden]{display:none!important}
@media(max-width:720px){body{padding:18px 12px}.stats{grid-template-columns:1fr 1fr}.filters{grid-template-columns:1fr}th,td{padding:9px}}
</style>
</head>
<body>
<p class="eyebrow">OE6VAG Radio Document Archive · External collection</p>
<h1>Radiojournal.cz Historical Schematics Index</h1>
<p class="lead">Search historical radio, television and electronic equipment by model. Model aliases sharing one PDF are all searchable. Documents remain hosted by the Czechoslovak Historic Radio Club; this is a metadata index only.</p>
<div class="source"><strong>Original PDF collection:</strong> <a href="__SOURCE__" target="_blank" rel="noopener noreferrer">Historický radioklub československý – Radiojournal.cz</a><p class="sub">Public HTML listings checked __CHECKED__. Original owners control document availability.</p></div>
<div class="stats"><div class="stat"><strong>__COUNT__</strong><span>distinct PDF URLs</span></div><div class="stat"><strong>6</strong><span>document categories</span></div><div class="stat"><strong>__ALIASES__</strong><span>model and document labels</span></div></div>
<div class="filters" role="search"><div><label for="q">Search manufacturer, model or document</label><input id="q" type="search" placeholder="e.g. Talisman 305U, AZK450, Sonet Duo" autocomplete="off"></div><div><label for="category">Category</label><select id="category"><option value="">All categories</option>__OPTIONS__</select></div><div><button type="button" id="clear">Clear filters</button></div></div>
<p id="count" class="count" role="status" aria-live="polite"></p>
<div class="table-wrap"><table><thead><tr><th>Model / document</th><th>Category</th><th>File</th></tr></thead><tbody id="results"></tbody></table></div>
<button type="button" id="more" class="more" hidden>Show 100 more results</button>
<p class="footer">Each result links to an externally hosted PDF. Repeated model names across different independent archives remain separate sources in the <a href="https://oe6vag.net/downloads/search/">overall Radio Document Search</a>.</p>
<script>
const documents=__DATA__;
const q=document.getElementById('q'), category=document.getElementById('category'), results=document.getElementById('results'), counter=document.getElementById('count'), more=document.getElementById('more');
const params=new URLSearchParams(window.location.search);q.value=params.get('q')||'';
if([...category.options].some(o=>o.value===params.get('category')))category.value=params.get('category')||'';
function normalize(x){return String(x||'').normalize('NFD').replace(/[\u0300-\u036f]/g,'').replace(/ß/g,'ss').replace(/[_.\-/,;:()[\]+]/g,' ').toLowerCase().replace(/\s+/g,' ').trim()}
function esc(x){return String(x??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]))}
const indexed=documents.map(d=>normalize(d.titles.join(' ')+' '+d.filename+' '+d.categories.join(' ')));
let visible=100;function render(reset=true){if(reset)visible=100;const terms=normalize(q.value).split(' ').filter(Boolean),cat=category.value;
const found=documents.filter((d,i)=>(!cat||d.categories.includes(cat))&&terms.every(t=>indexed[i].includes(t)));
const page=found.slice(0,visible);results.innerHTML=page.length?page.map(d=>`<tr><td><a href="${esc(d.url)}" target="_blank" rel="noopener noreferrer">${esc(d.titles.join(' / '))}</a></td><td class="sub">${esc(d.categories.join(', '))}</td><td class="sub">${esc(d.filename)}</td></tr>`).join(''):'<tr><td colspan="3">No matching documents.</td></tr>';
counter.textContent=`${found.length.toLocaleString('en-US')} matching documents · ${page.length.toLocaleString('en-US')} displayed`;more.hidden=page.length>=found.length;}
q.addEventListener('input',()=>render());category.addEventListener('change',()=>render());document.getElementById('clear').addEventListener('click',()=>{q.value='';category.value='';render();q.focus()});more.addEventListener('click',()=>{visible+=100;render(false)});render();
</script>
</body>
</html>
'''
    tokens = {
        "__DATA__": compact,
        "__CANONICAL__": CANONICAL,
        "__SOURCE__": COLLECTION,
        "__CHECKED__": inspected,
        "__COUNT__": str(len(documents)),
        "__ALIASES__": str(sum(len(d["titles"]) for d in documents)),
        "__OPTIONS__": options,
    }
    for token, replacement in tokens.items():
        html_page = html_page.replace(token, replacement)
    if "__DATA__" in html_page:
        raise AssertionError("Missing inline data in HTML")
    return html_page


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--source-dir", type=Path, default=Path(__file__).with_name("source"))
    parser.add_argument("--fetch", action="store_true", help="Refresh all six HTML directory pages")
    parser.add_argument("--output-dir", type=Path, default=Path("."))
    parser.add_argument("--checked", default=date.today().isoformat())
    opts = parser.parse_args()
    sources = get_sources(opts.source_dir, opts.fetch)
    docs, info = extract_documents(sources)
    opts.output_dir.mkdir(parents=True, exist_ok=True)
    (opts.output_dir / "radiojournal_schematics_index.html").write_text(stand_alone(docs, opts.checked), encoding="utf-8")
    (opts.output_dir / "radiojournal-search-index.json").write_text(json.dumps(search_records(docs), ensure_ascii=False, separators=(",", ":")) + "\n", encoding="utf-8")
    (opts.output_dir / "radiojournal_inventory.json").write_text(json.dumps({"source_pages":info,"documents":docs}, ensure_ascii=False, indent=1)+"\n", encoding="utf-8")
    print(f"{len(docs)} distinct PDF URLs; {sum(x['anchors'] for x in info.values())} linked anchors; {sum(len(d['titles']) for d in docs)} model labels")
    for category, stats in info.items():
        print(f"{category}: {stats['anchors']} PDF anchors")


if __name__ == "__main__":
    main()
