#!/usr/bin/env python3
"""Crawl RSP Italy's public HTML directory pages (not the PDF documents).

Each file is requested once and cached. A modest global launch interval and
limited workers reduce load on the source website. Existing cached pages are
reused on subsequent runs.
"""

import concurrent.futures
import hashlib
import json
import re
import threading
import time
from collections import Counter
from pathlib import Path
from urllib.parse import quote, unquote, urljoin, urlparse
from urllib.request import Request, urlopen

from lxml import html


ROOT = "https://www.rsp-italy.it/Electronics/Radio%20Schematics/"
HERE = Path(__file__).resolve().parent
CACHE = HERE / "pages"
CACHE.mkdir(exist_ok=True)
LOCK = threading.Lock()
NEXT_REQUEST = 0.0
GAP_SECONDS = 0.75


def normalize_href(href):
    return quote(href, safe="/%:@?&=+#")


def fetch(task):
    global NEXT_REQUEST
    name, href = task
    key = hashlib.sha256(href.encode("utf-8")).hexdigest()[:20]
    path = CACHE / f"{key}.html"
    url = urljoin(ROOT, normalize_href(href))
    if path.exists() and path.stat().st_size > 100:
        return name, href, path, None

    last_error = None
    for attempt in range(2):
        with LOCK:
            now = time.monotonic()
            wait = max(0, NEXT_REQUEST - now)
            NEXT_REQUEST = max(now, NEXT_REQUEST) + GAP_SECONDS
        if wait:
            time.sleep(wait)
        try:
            req = Request(url, headers={"User-Agent": "OE6VAG-Archive-Research/1.0 (HTML index only; no PDF downloads)"})
            with urlopen(req, timeout=28) as response:
                content = response.read()
                if response.status != 200 or len(content) < 100:
                    raise RuntimeError(f"HTTP {response.status}, {len(content)} bytes")
            path.write_bytes(content)
            return name, href, path, None
        except Exception as exc:
            last_error = f"{type(exc).__name__}: {exc}"
            if "HTTP Error 403" in last_error or "HTTP Error 429" in last_error:
                break
            if attempt == 0:
                time.sleep(3)
    return name, href, None, last_error


def main():
    root = html.parse(str(HERE / "source.html"))
    tasks = {}
    for a in root.xpath('//a[@href]'):
        href = a.get("href")
        if not href.lower().endswith("/index.htm") or href.startswith(".."):
            continue
        if href not in tasks:
            tasks[href] = (" ".join(a.itertext()).strip(), href)

    print(f"Directory pages: {len(tasks)} (including Beitman and Riders)", flush=True)
    collected = []
    start = time.monotonic()
    with concurrent.futures.ThreadPoolExecutor(max_workers=6) as executor:
        results = executor.map(fetch, tasks.values())
        for i, result in enumerate(results, 1):
            collected.append(result)
            if i % 25 == 0 or i == len(tasks):
                errors = sum(x[3] is not None for x in collected)
                print(f"Progress {i}/{len(tasks)} | errors={errors} | {time.monotonic()-start:.0f}s", flush=True)

    records = []
    failed = []
    for name, href, path, error in collected:
        if error:
            failed.append({"brand": name, "index_url": urljoin(ROOT, normalize_href(href)), "error": error})
            continue
        try:
            root_page = html.fromstring(path.read_bytes())
        except Exception as exc:
            failed.append({"brand": name, "index_url": urljoin(ROOT, normalize_href(href)), "error": str(exc)})
            continue
        is_collection = href.startswith("Collections/")
        for a in root_page.xpath('//a[@href]'):
            file_href = a.get("href")
            resolved = urljoin(urljoin(ROOT, normalize_href(href)), normalize_href(file_href))
            parsed = urlparse(resolved)
            if parsed.scheme != "https" or parsed.netloc != "www.rsp-italy.it":
                continue
            if not parsed.path.lower().endswith(".pdf"):
                continue
            filename = unquote(parsed.path.rsplit("/", 1)[-1]).strip()
            label = re.sub(r"\s+", " ", a.text_content()).strip()
            records.append({
                "brand": name,
                "collection": is_collection,
                "filename": filename,
                "link_label": label,
                "url": resolved,
                "directory_url": urljoin(ROOT, normalize_href(href)),
            })

    payload = {
        "root_url": ROOT,
        "pages_listed": len(tasks),
        "pages_successful": len(tasks) - len(failed),
        "failed_pages": failed,
        "records": records,
    }
    (HERE / "inventory.json").write_text(json.dumps(payload, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
    print("PDF links:", len(records), "unique URLs:", len(set(r["url"] for r in records)), flush=True)
    print("By group:", Counter("collection" if r["collection"] else "manufacturer" for r in records), flush=True)
    if failed:
        print("Failures:", failed[:20], flush=True)


if __name__ == "__main__":
    main()
