import re
from pathlib import Path
from urllib.parse import urlparse
from typing import Optional

ROOT = Path(__file__).resolve().parents[1]
HEADER = ROOT / "header.php"

HREF_RE = re.compile(r'href\s*=\s*"([^"]+)"', re.IGNORECASE)


def is_external(href: str) -> bool:
    if href.startswith(("mailto:", "tel:", "javascript:", "#", "data:")):
        return True
    u = urlparse(href)
    return u.scheme in {"http", "https"} or href.startswith("//")


def normalize(href: str) -> str:
    href = href.split("#", 1)[0].split("?", 1)[0]
    return href


def map_to_path(href: str) -> Optional[Path]:
    href = normalize(href)
    if not href:
        return None
    if href.startswith("/aaa/"):
        return ROOT / href.removeprefix("/aaa/")
    if href.startswith("/"):
        return ROOT / href.lstrip("/")
    return ROOT / href


def main():
    data = HEADER.read_text(encoding="utf-8", errors="ignore")
    hrefs = []
    for m in HREF_RE.finditer(data):
        href = m.group(1).strip()
        if not href or is_external(href):
            continue
        if href.endswith("/") or href.endswith(".php"):
            hrefs.append(href)

    missing = []
    for href in sorted(set(hrefs)):
        p = map_to_path(href)
        if p is None:
            continue
        if href.endswith("/") and (p.exists() and p.is_dir()):
            continue
        if not p.exists():
            missing.append(href)

    out = ROOT / "tools" / "menu_missing_targets.txt"
    out.write_text("\n".join(missing) + ("\n" if missing else ""), encoding="utf-8")
    print(f"Menu links checked: {len(set(hrefs))}")
    print(f"Missing targets: {len(missing)}")
    print(f"Wrote: {out}")


if __name__ == "__main__":
    main()

