#!/usr/bin/env python3
from pathlib import Path
import json
import re
import html
import unicodedata

BASE_DIR = Path("/mnt/radioarchive/radioarchive")

# URL, unter der BASE_DIR über Caddy erreichbar ist.
# Falls deine Dateien unter https://oe6vag.net/downloads/... liegen:
PUBLIC_PREFIX = "/downloads"

OUTPUT_FILE = BASE_DIR / "search" / "search-index.json"

LOCAL_PDF_ROOTS = [
    BASE_DIR / "schematics",
    BASE_DIR / "books",
    BASE_DIR / "magazines",
]

EXTERNAL_INDEX_ROOTS = [
    BASE_DIR / "index",
]

def normalize_text(text: str) -> str:
    text = text.replace("ß", "ss").replace("ẞ", "SS")
    text = unicodedata.normalize("NFKD", text)
    text = "".join(c for c in text if not unicodedata.combining(c))
    text = text.lower()
    text = re.sub(r"[_\-/.,;:()\[\]+]", " ", text)
    text = re.sub(r"\s+", " ", text)
    return text.strip()

def prettify_filename(path: Path) -> str:
    name = path.stem
    name = name.replace("_", " ")
    name = name.replace("-", " ")
    name = re.sub(r"\s+", " ", name)
    return name.strip()

def make_url(path: Path) -> str:
    rel = path.relative_to(BASE_DIR).as_posix()
    return f"{PUBLIC_PREFIX}/{rel}"

def guess_brand_from_path(path: Path) -> str:
    try:
        parts = path.relative_to(BASE_DIR).parts
    except ValueError:
        return ""

    # Beispiel: schematics/minerva/Minerva_395W.pdf
    if len(parts) >= 3 and parts[0] == "schematics":
        return parts[1].replace("_", " ").replace("-", " ").title()

    return ""

def add_local_pdfs(records):
    for root in LOCAL_PDF_ROOTS:
        if not root.exists():
            continue

        for pdf in sorted(root.rglob("*.pdf")):
            title = prettify_filename(pdf)
            brand = guess_brand_from_path(pdf)
            url = make_url(pdf)

            text = " ".join([
                title,
                brand,
                str(pdf.relative_to(BASE_DIR)),
            ])

            records.append({
                "type": "local_pdf",
                "source": "Local scan",
                "title": title,
                "brand": brand,
                "url": url,
                "text": text,
                "search_text": normalize_text(text),
            })

def strip_tags(s: str) -> str:
    s = re.sub(r"<script.*?</script>", " ", s, flags=re.I | re.S)
    s = re.sub(r"<style.*?</style>", " ", s, flags=re.I | re.S)
    s = re.sub(r"<[^>]+>", " ", s)
    s = html.unescape(s)
    s = re.sub(r"\s+", " ", s)
    return s.strip()

def add_external_html_indices(records):
    link_re = re.compile(
        r'<a\s+[^>]*href=["\']([^"\']+)["\'][^>]*>(.*?)</a>',
        flags=re.I | re.S
    )

    for root in EXTERNAL_INDEX_ROOTS:
        if not root.exists():
            continue

        for page in sorted(root.rglob("*.html")):
            if page.name.lower() == "index.html":
                pass

            content = page.read_text(encoding="utf-8", errors="ignore")
            page_title_match = re.search(r"<title[^>]*>(.*?)</title>", content, flags=re.I | re.S)
            page_title = strip_tags(page_title_match.group(1)) if page_title_match else prettify_filename(page)

            for href, label_html in link_re.findall(content):
                href = html.unescape(href).strip()
                label = strip_tags(label_html)

                if not label:
                    continue

                if href.startswith("#"):
                    continue

                if href.startswith("mailto:"):
                    continue

                # Navigation / uninteressante Links grob ausfiltern
                bad_labels = {"home", "back", "download", "downloads", "top"}
                if label.strip().lower() in bad_labels:
                    continue

                text = " ".join([
                    page_title,
                    label,
                    href,
                ])

                records.append({
                    "type": "external_index",
                    "source": "External index",
                    "title": label,
                    "brand": "",
                    "url": href,
                    "context": page_title,
                    "text": text,
                    "search_text": normalize_text(text),
                })

def main():
    records = []

    add_local_pdfs(records)
    add_external_html_indices(records)

    # Duplikate entfernen
    unique = {}
    for r in records:
        key = (r.get("title", ""), r.get("url", ""))
        unique[key] = r

    records = list(unique.values())
    records.sort(key=lambda r: (r.get("title", "").lower(), r.get("source", "")))

    OUTPUT_FILE.parent.mkdir(parents=True, exist_ok=True)
    OUTPUT_FILE.write_text(
        json.dumps(records, ensure_ascii=False, indent=2),
        encoding="utf-8"
    )

    print(f"Created: {OUTPUT_FILE}")
    print(f"Records: {len(records)}")

if __name__ == "__main__":
    main()
