#!/usr/bin/env python3
"""ALPHA: ATO page generator.

Reads one JSON file per ATO (or --master docs/ato-master/ato-master-10nov.json via the converter) and writes the approved
2-column guest page body only:
    out/<school-slug>/index.html
The top bar and logo come from /ato/_shared/topbar.js (ATO-20), never copied into the page.
Everything that depends on who is looking (all reviews, the review form, votes, reply boxes) is NOT in the static
page. The page fetches it after load from GET /api/ato/<slug>/view (the server checks the session and the rules).

The rating card is NOT worked out here. Each school file carries the server's rating summary (see rating.py), so the
big number, the bars and the four counts always come from the same set of reviews (CORE-01).

Run:  python3 generator.py            (all ATOs in data/ato, writes out/)
      python3 generator.py --master ../docs/ato-master/ato-master-10nov.json --out build
Nothing here deploys anything. Pages stay "noindex" unless --index is given.
"""
import argparse, json, shutil, hashlib, datetime as dt, re
from pathlib import Path
from urllib.parse import quote
from jinja2 import Environment, FileSystemLoader, select_autoescape, StrictUndefined
from markupsafe import Markup
import svg
import rating as rating_rules

HERE = Path(__file__).resolve().parent
MIN_REVIEWS = rating_rules.MIN_RATINGS   # rating shows from 3 reviews (REV-011) from 3 aged reviewers (REV-039)
GUEST_TOP = 3            # guests see the top 3 reviews by counted aged upvotes, ties newest (REV-029 / REV-039)
SAST = dt.timezone(dt.timedelta(hours=2))
SLUG_RE = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")          # REV-023
RESERVED_SLUGS = {"static", "fonts", "index", "manifest"}    # folders and files that live beside the school folders
SIGNIN_HREF = "/signin/?return={path}"                       # UR-55: come back to the same school after sign-in
# 7 rating categories, fixed order and names (A-30). The third item is the hint shown on the write form.
CATEGORIES = [
    ("org", "Organisation", "Bookings, paperwork and how well they communicate."),
    ("flt", "Fleet", "Aircraft condition: clean, safe, faults fixed fast."),
    ("gnd", "Ground school", "Theory lessons, notes and exam preparation."),
    ("ins", "Instructors", "Teaching, patience and professionalism."),
    ("saf", "Safety culture", "How seriously safety is taken: briefings, reporting."),
    ("val", "Value", "What you get for the money: fair prices, no hidden fees."),
    ("avl", "Availability", "How easy it is to book aircraft and instructors."),
]
THEMES = {"midnight": ("night", "black"), "amethyst": ("night", "purple"),
          "pearl": ("day", "white"), "champagne": ("day", "beige")}
MONTHS = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split()

# Only these fields may appear in a school file. Anything else stops the build, so a private field added upstream
# by mistake cannot reach a public page (an allow-list, not a list of known bad names).
ATO_KEYS = {"id", "slug", "name", "handle", "kind", "status", "bases", "about", "contact", "courses", "rating",
            "top_reviews", "visible_reviews", "legacy_slug_targets", "_warnings", "_school_id", "_merged_from", "_note"}
BASE_KEYS = {"ident", "name", "town", "href", "anchor", "certificate"}
CERT_KEYS = {"number", "valid_until", "updated", "current", "date"}
REVIEW_KEYS = {"id", "author", "stars", "title", "text", "status", "published_at", "edited", "edited_at", "text_added_at",
               "up", "upvotes", "vote_records", "voteRecords", "official_replies", "cost", "when", "licence"}
AUTHOR_KEYS = {"name", "anonymous", "badges", "licences", "handle"}
PRIVATE_KEYS = {"email_private", "private_author_id", "account_id", "author_id", "seat_no", "voter_id", "google_sub", "ip_hash"}

PHONE_RE = re.compile(r"^[0-9+ ()-]{7,20}$")
EMAIL_RE = re.compile(r"^[^\s@<>\"']+@[^\s@<>\"']+\.[^\s@<>\"']{2,}$")
WEB_RE = re.compile(r"^[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+(/[A-Za-z0-9._~%/-]*)?$")     # host and path only; no scheme, no query


def today_sast():
    """Today's date in South Africa. Current / Expired depends on it, so there is no fixed default date."""
    return dt.datetime.now(SAST).date()


def nice_date(iso):
    d = dt.date.fromisoformat(iso)
    return f"{d.day} {MONTHS[d.month - 1]} {d.year}"


def nice_month(iso):
    """Anonymous posts show the month only (REV-038), never a made-up day."""
    d = dt.date.fromisoformat(str(iso)[:7] + "-01")
    return f"{MONTHS[d.month - 1]} {d.year}"


def counts_toward_rating(rv):
    """Published and author-deleted ratings count (CORE-01 / REV-055)."""
    st = str((rv or {}).get("status") or "published").lower()
    return st in ("published", "deleted")


def guest_visible_reviews(reviews):
    """Written, published cards only. Deleted and stars-only do not take a guest slot."""
    out = []
    for rv in reviews or []:
        st = str(rv.get("status") or "published").lower()
        if st != "published":
            continue
        if not str(rv.get("text") or "").strip():
            continue
        out.append(rv)
    return out


VOTE_MIN_ACCOUNT_AGE_MS = 7 * 24 * 3600 * 1000


def counted_upvotes(review, now_ms=None):
    """The number of upvotes that count for this review.

    The server sends it as `up`: it has already applied the 7-day account rule AND the 20-a-day cap (REV-039), which
    needs to know who voted and cannot be done here. When `up` is present it is used as is.
    Example data without `up` falls back to vote_records and the 7-day rule only. `now_ms` must then be given by the
    caller (the build passes the build date), so two builds of the same data always agree."""
    review = review or {}
    up = review.get("up")
    if isinstance(up, int) and not isinstance(up, bool) and up >= 0:
        return up
    records = review.get("vote_records") or review.get("voteRecords") or []
    if not records:
        return 0
    if now_ms is None:
        raise ValueError("counted_upvotes needs the build date (now_ms) when a review has no server count")
    n = 0
    for v in records:
        if not isinstance(v, dict):
            continue
        if v.get("value") != 1:
            continue
        created = v.get("accountCreated", v.get("account_created"))
        try:
            created = int(created)
        except (TypeError, ValueError):
            continue
        if now_ms - created >= VOTE_MIN_ACCOUNT_AGE_MS:
            n += 1
    return n


def day_ms(day):
    """Midnight SAST at the start of `day`, in milliseconds. The fixed clock for one build."""
    return int(dt.datetime(day.year, day.month, day.day, tzinfo=SAST).timestamp() * 1000)


def guest_top_reviews(reviews, n=GUEST_TOP, now_ms=None):
    """Most counted aged upvotes first; a tie goes to the newest published_at (REV-029)."""
    return sorted(
        guest_visible_reviews(reviews),
        key=lambda x: (counted_upvotes(x, now_ms), str(x.get("published_at") or "")),
        reverse=True,
    )[:n]


def star_bars(summary):
    """The 5-to-1 bars, straight from the rating summary. Never from the reviews printed on the page."""
    count = summary["count"]
    if not summary["shown"]:
        return [{"k": k, "c": 0, "frac": 0} for k in (5, 4, 3, 2, 1)]
    return [{"k": b["stars"], "c": b["count"], "frac": (b["count"] / count) if count else 0} for b in summary["bars"]]


def _only(obj, allowed, what, who):
    extra = set(obj) - allowed
    if extra:
        raise ValueError(f"{who}: field not allowed in {what}: {', '.join(sorted(extra))}")


def clean_contact(contact, who, warnings):
    """Phone, email and website go into links, so each must be a plain value. A bad one is left out and flagged."""
    out = {"phone": None, "email": None, "web": None}
    c = contact or {}
    phone, email, web = c.get("phone"), c.get("email"), c.get("web")
    if phone:
        if PHONE_RE.match(str(phone)):
            out["phone"] = str(phone)
        else:
            warnings.append(f"{who}: phone left out (not a plain number)")
    if email:
        if EMAIL_RE.match(str(email)):
            out["email"] = str(email)
        else:
            warnings.append(f"{who}: email left out (not a plain address)")
    if web:
        web = re.sub(r"^https?://", "", str(web), flags=re.I).rstrip("/")
        if WEB_RE.match(web):
            out["web"] = web
        else:
            warnings.append(f"{who}: website left out (not a plain web address)")
    return out


def check(ato):
    """Stop on bad data: required fields, allowed public fields only, a safe slug, a rating summary that adds up.
    Reviews and a paid/verified status are optional (REV-022: do not invent them).
    A known aerodrome code must link to /ad/{CODE}. A missing code is flagged."""
    who = ato.get("id", "?")
    for k in ("id", "slug", "name", "bases"):
        if k not in ato:
            raise ValueError(f"{who}: missing {k}")
    slug = ato["slug"]
    if not isinstance(slug, str) or not SLUG_RE.match(slug) or len(slug) > 80:
        raise ValueError(f"{who}: slug {slug!r} is not allowed (REV-023: lower-case letters and digits, single hyphens)")
    if slug in RESERVED_SLUGS:
        raise ValueError(f"{who}: slug {slug!r} is reserved")
    status = ato.get("status")
    if status is not None and status not in ("paid", "verified", "unclaimed", "gifted"):
        raise ValueError(f"{who}: bad status {status}")

    def keys(o):
        if isinstance(o, dict):
            for k, v in o.items():
                yield k
                yield from keys(v)
        elif isinstance(o, list):
            for v in o:
                yield from keys(v)
    if PRIVATE_KEYS & set(keys(ato)):
        raise ValueError(f"{who}: private field in data")
    _only(ato, ATO_KEYS, "a school file", who)

    warnings = list(ato.get("_warnings") or [])
    anchors = set()
    for i, b in enumerate(ato.get("bases") or []):
        _only(b, BASE_KEYS, "a base", who)
        if b.get("certificate"):
            _only(b["certificate"], CERT_KEYS, "a certificate", who)
            for f in ("valid_until", "updated"):
                v = b["certificate"].get(f)
                if v:
                    try:
                        dt.date.fromisoformat(v)
                    except ValueError:
                        raise ValueError(f"{who}: certificate {f} {v!r} is not a date (YYYY-MM-DD)") from None
        ident = b.get("ident")
        href = b.get("href")
        if ident:
            if not re.match(r"^[A-Z0-9-]{3,8}$", str(ident)):
                raise ValueError(f"{who}: aerodrome code {ident!r} is not valid")
            expected = f"/ad/{ident}"
            if href != expected:
                raise ValueError(f"{who}: base {ident} must link to {expected}")
        else:
            if href:
                raise ValueError(f"{who}: href without an aerodrome code")
            label = b.get("name") or b.get("town") or f"base {i}"
            warnings.append(f"{who}: missing aerodrome code for {label}")
        anchor = b.get("anchor")
        if anchor:
            if not SLUG_RE.match(str(anchor)):
                raise ValueError(f"{who}: base anchor {anchor!r} is not allowed")
            if anchor in anchors:
                raise ValueError(f"{who}: base anchor {anchor!r} is used twice")
            anchors.add(anchor)
    for rv in ato.get("top_reviews") or []:
        _only(rv, REVIEW_KEYS, "a review", who)
        _only(rv.get("author") or {}, AUTHOR_KEYS, "a review author", who)
        if str(rv.get("id", "")).startswith("ex") and not str(who).startswith("EXAMPLE"):
            raise ValueError(f"{who}: sample review {rv.get('id')} in real data (REV-022)")
    ato["contact"] = clean_contact(ato.get("contact"), who, warnings)
    n_certs = sum(1 for b in ato.get("bases") or [] if b.get("certificate"))
    ato["rating"] = rating_rules.normalise(ato.get("rating"), n_certs, who)
    ato["_warnings"] = warnings
    return warnings


def scrub_pilot(text):
    """Standing rule: the word 'pilot' is not shown on the page (nav tab excepted)."""
    if text is None:
        return text
    out = re.sub(r"\bpilot\b", "", str(text), flags=re.I)
    out = re.sub(r"\s+", " ", out)
    out = re.sub(r"\(\s*\)", "", out)
    return out.strip(" -")


def course_groups(ato, scrub_courses=False):
    """Licences / Ratings / Other, matching the approved page. First 3 show; the rest sit behind More.
    scrub_courses: decision D4, DECIDED by MT 11 Nov (NEW-08): False (the default) keeps the licence's real name,
    "Private Pilot Licence". True removes "pilot" from course names and About, the old behaviour."""
    fix = scrub_pilot if scrub_courses else (lambda t: re.sub(r"\s+", " ", str(t)).strip() if t is not None else t)
    raw = []
    for g in ato.get("courses") or []:
        if isinstance(g, str):
            raw.append(g)
        elif isinstance(g, dict):
            if g.get("items"):
                raw.extend(g["items"])
            elif g.get("name") and g.get("name") not in ("Licences", "Ratings", "Other"):
                raw.append(g["name"])
    seen, names = set(), []
    for n in raw:
        t = fix(n)
        k = (t or "").lower()
        if not t or k in seen:
            continue
        seen.add(k)
        names.append(t)
    lic_exact = {
        "spl", "ppl", "cpl", "atpl", "night", "night rating",
        "instrument rating", "ir", "instructor", "instructor rating",
        "multi-engine", "me",
    }
    lic, rat, oth = [], [], []
    for n in names:
        low = n.lower()
        if low in lic_exact or re.search(r"\b(spl|ppl|cpl|atpl)\b", low) or re.search(
            r"night|instrument|\bir\b|instructor|multi.?engine", low
        ):
            lic.append(n)
        elif re.search(r"aerotow|tug|heli|turbine|jet|type rating|seaplane|aerobat|upset|uprt", low):
            rat.append(n)
        else:
            oth.append(n)
    about = ato.get("about")
    if isinstance(about, str):
        ato["about"] = fix(about)
    return [g for g in (
        {"name": "Licences", "items": lic},
        {"name": "Ratings", "items": rat},
        {"name": "Other", "items": oth},
    ) if g["items"]]


def redirect_lines(master=None, extra_aliases=None):
    """Cloudflare _redirects lines: approval slugs to /ato/{slug}#{base}, plus the names of merged schools.
    Never redirect a school's own /ato/{slug} onto a hashed copy of itself."""
    from master_convert import MERGES
    lines = []
    seen = set()

    def add(src, dest, code=301):
        src = src.rstrip("/") or src
        if not src.startswith("/"):
            src = "/ato/" + src.lstrip("/")
        if src in seen or src == dest.split("#", 1)[0]:
            return
        seen.add(src)
        lines.append(f"{src} {dest} {code}")

    if isinstance(master, (str, Path)):
        master = json.loads(Path(master).read_text())
    if isinstance(master, dict):
        for red in master.get("redirect_map") or []:
            dest = red.get("to_path") or ""
            own = red.get("to_school_id") or ""
            slugs = []
            if red.get("from_slug"):
                slugs.append(red["from_slug"])
            for v in red.get("from_variants") or []:
                slugs.append(v)
            for slug in slugs:
                if not slug:
                    continue
                if slug == own or slug.replace("_", "-").lower() == own:
                    continue
                # Paths like SACAA/1637/ATO become /ato/SACAA/1637/ATO
                add(slug if slug.startswith("/") else f"/ato/{slug}", dest)
        for target, members in MERGES.items():
            for m in members:
                add(f"/ato/{m}", f"/ato/{target}")
    for src, dest in extra_aliases or ():
        add(src, dest)
    return lines


def json_ld(ato, summary, site):
    """Rating markup for search engines: only when the rating is shown, with the same number and count as the card."""
    if not summary["shown"]:
        return None
    obj = {"@context": "https://schema.org", "@type": "EducationalOrganization", "name": ato["name"],
           "aggregateRating": {"@type": "AggregateRating", "ratingValue": summary["score"], "bestRating": "5",
                               "worstRating": "1", "ratingCount": summary["count"]}}
    if site:
        obj["url"] = f"{site}/ato/{ato['slug']}"
    return Markup(json.dumps(obj, ensure_ascii=False).replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026"))


def page_model(ato, today, site=None, index=False, scrub_courses=False, show_categories=False):
    """Everything the template needs, decided here (rules in one place, not in the template).
    check(ato) must have run first: it validates the data and normalises the rating summary."""
    if "shown" not in (ato.get("rating") or {}):
        check(ato)
    reviews = list(ato.get("top_reviews") or [])
    r = ato["rating"]
    shown = r["shown"]                         # the server decided: 3 ratings from 3 aged reviewers (REV-011, REV-039)
    avg = float(r["score"]) if shown else 0.0  # for drawing the stars; gold is NOT decided from this rounded value
    kind = "empty" if not shown else ("glass" if r["gold"] else "flat")     # NEW-01: gold from the raw average
    for rv in reviews:                       # fill optional fields so the template stays strict
        a = rv.setdefault("author", {})
        a.setdefault("anonymous", False); a.setdefault("badges", []); a.setdefault("licences", [])
        if a["anonymous"]:                               # anonymous: no name, badges, licences or identifying extras
            a.update(name="", badges=[], licences=[])
            a.pop("handle", None)
            for k in ("cost", "when", "licence", "authorName", "displayName"):
                rv.pop(k, None)
            pub = str(rv.get("published_at") or "")
            if len(pub) >= 7:
                rv["published_at"] = pub[:7] + "-01"
            for k in ("edited_at", "text_added_at"):
                if rv.get(k):
                    rv[k] = str(rv[k])[:7] + "-01"
        rv["when_label"] = (nice_month if a["anonymous"] else nice_date)(rv["published_at"]) if rv.get("published_at") else ""
        rv.setdefault("official_replies", []); rv.setdefault("title", ""); rv.setdefault("text", ""); rv.setdefault("edited", False)
    for b in ato["bases"]:
        ident = b.get("ident")
        if ident:
            b["href"] = f"/ad/{ident}"
        else:
            b["href"] = None
        b.setdefault("certificate", None)
        b.setdefault("anchor", None)
        b.setdefault("ident", None)
        b.setdefault("name", None)
        b.setdefault("town", None)
        if b["certificate"]:
            b["certificate"].setdefault("updated", None)
            b["certificate"].setdefault("date", None)
            b["certificate"].setdefault("number", None)
            b["certificate"].setdefault("valid_until", None)
    top = guest_top_reviews(reviews, now_ms=day_ms(today))
    for b in ato["bases"]:
        c = b.get("certificate")
        if c and c.get("valid_until"):
            # Current / Expired from the expiry date, never the ATP current flag (DEC-011).
            c["current"] = dt.date.fromisoformat(c["valid_until"]) >= today
            c["date"] = nice_date(c["valid_until"])
    status = ato.get("status")
    paid = status in ("paid", "gifted")
    verified = status in ("paid", "verified", "gifted")
    ato.setdefault("about", None)
    ato.setdefault("handle", None)
    # "N more reviews" behind the sign-in gate: cards a member can really open. Stars-only and deleted reviews are
    # in the count but have no card, so the gate must not promise them.
    visible = ato.get("visible_reviews")
    if not isinstance(visible, int) or isinstance(visible, bool):
        visible = r["written"]                  # written, published reviews = the cards that exist
    cats = []
    if show_categories:
        by_key = {c["key"]: c for c in (r["categories"] or [])}
        for key, label, _hint in CATEGORIES:
            c = by_key.get(key) or {}
            score = c.get("score") if shown else None            # a dash until the category has 3 ratings (REV-011)
            cats.append({"key": key, "label": label, "score": score, "avg": float(score) if score else 0.0,
                         "kind": "empty" if not score else ("glass" if c.get("gold") else "flat")})
    bases_txt = ", ".join(dict.fromkeys(str(b.get("ident") or b.get("town") or b.get("name")) for b in ato["bases"]
                                         if b.get("ident") or b.get("town") or b.get("name")))
    path = f"/ato/{ato['slug']}"
    return {
        "ato": ato, "paid": paid, "verified": verified,
        "rating_shown": shown, "rating_kind": kind, "score": r["score"] if shown else "", "rating_avg": avg,
        "top": top, "more": max(0, visible - len(top)), "categories": CATEGORIES,
        "api": f"/api/ato/{ato['slug']}/view", "min_reviews": MIN_REVIEWS,     # by SCHOOL, never by certificate (REV-003)
        "star_bars": star_bars(r),
        "course_groups": course_groups(ato, scrub_courses),
        "written_count": r["written"], "rated_hi": r["rated_hi"] if shown else None,
        "cat_rows": cats,
        "signin_href": SIGNIN_HREF.format(path=quote(path, safe="")),
        "robots": "index,follow" if index else "noindex,nofollow",
        "canonical": f"{site}{path}" if site else None,
        "description": f"{ato['name']}: flight training{' at ' + bases_txt if bases_txt else ''}. "
                       "Certificates, courses, contact details and reviews on Go Around.",
        "json_ld": json_ld(ato, r, site),
    }


def copy_fonts(out_dir):
    """Local preview only: copy the site's font CSS + the font files it uses into out/fonts (on the real site /fonts exists)."""
    src = HERE.parent / "site" / "fonts"
    if not src.exists():
        return
    dst = out_dir / "fonts"
    dst.mkdir(exist_ok=True)
    css = (src / "wm-fonts.css").read_text()
    shutil.copy(src / "wm-fonts.css", dst)
    for name in set(re.findall(r"url\('([^']+)'\)", css)) | {"sora-400.woff2", "sora-600.woff2"}:
        if (src / name).exists():
            shutil.copy(src / name, dst / name)


def build(data_dir, out_dir, theme, today, site=None, index=False, scrub_courses=False, show_categories=False, prune=False):
    env = Environment(loader=FileSystemLoader(HERE / "template"), autoescape=select_autoescape(["html", "j2"]),
                      undefined=StrictUndefined, trim_blocks=True, lstrip_blocks=True)
    env.globals.update(svg=svg, nice_date=nice_date, nice_month=nice_month)
    tpl = env.get_template("ato.html.j2")
    t, pal = THEMES[theme]
    tokens = (HERE / "themes" / f"{theme}.css").read_text()
    out_dir = Path(out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)
    out_root = out_dir.resolve()
    shutil.copytree(HERE / "static", out_dir / "static", dirs_exist_ok=True)
    copy_fonts(out_dir)
    manifest, warnings, seen = [], [], {}
    for f in sorted(Path(data_dir).glob("*.json")):
        if f.name.startswith("_"):
            continue
        ato = json.loads(f.read_text())
        warnings.extend(check(ato))
        slug = ato["slug"]
        if slug in seen:                                # REV-023: never let one school overwrite another
            raise ValueError(f"slug {slug!r} is used by both {seen[slug]} and {f.name}. Fix the data or the merge list.")
        seen[slug] = f.name
        dest = (out_dir / slug / "index.html").resolve()
        if out_root not in dest.parents:                # belt and braces: the page must land inside the output folder
            raise ValueError(f"{ato['id']}: page path leaves the output folder")
        svg.IDS.n = 0                                   # stable SVG ids per page
        html = tpl.render(**page_model(ato, today, site=site, index=index, scrub_courses=scrub_courses,
                                       show_categories=show_categories),
                          theme=theme, data_theme=t, data_pal=pal, tokens=tokens)
        dest.parent.mkdir(parents=True, exist_ok=True)
        dest.write_text(html)
        manifest.append({"id": ato["id"], "slug": slug, "page": str(dest.relative_to(out_root)),
                         "data_sha1": hashlib.sha1(f.read_bytes()).hexdigest()[:12],
                         "page_sha1": hashlib.sha1(html.encode()).hexdigest()[:12]})
        print("wrote", dest.relative_to(HERE) if dest.is_relative_to(HERE) else dest)
    # Pages left over from an earlier build whose school is no longer in the data (renamed, merged or removed).
    stale = sorted(d.name for d in out_dir.iterdir()
                   if d.is_dir() and d.name not in seen and SLUG_RE.match(d.name) and d.name not in RESERVED_SLUGS
                   and (d / "index.html").exists())
    for name in stale:
        if prune:
            shutil.rmtree(out_dir / name)
        else:
            print(f"WARNING: stale page {name}/ is not in this build (use --prune to remove it)")
    (out_dir / "manifest.json").write_text(json.dumps(
        {"theme": theme, "today": str(today), "pages": manifest, "warnings": warnings,
         "stale_pages": [] if prune else stale}, indent=1))
    return manifest


def main(argv=None):
    a = argparse.ArgumentParser(description="Generate static guest ATO pages. Nothing is deployed.")
    a.add_argument("--data", default=HERE / "data" / "ato")
    a.add_argument("--master", default=None, help="path to ato-master-10nov.json (converted, no invented reviews)")
    a.add_argument("--out", default=HERE / "out")
    a.add_argument("--theme", default="amethyst", choices=THEMES)
    a.add_argument("--today", default=None, help="date used for Current / Expired, YYYY-MM-DD. Default: today in South Africa. "
                                                 "Give a fixed date only to reproduce an old build.")
    a.add_argument("--site", default=None, help="site address, e.g. https://example.co.za, for canonical links. Default: none")
    a.add_argument("--index", action="store_true", help="let search engines index the pages. Default: noindex (preview)")
    a.add_argument("--keep-pilot-in-courses", action="store_true",
                   help='kept for old scripts: "pilot" now stays in course names by default (NEW-08)')
    a.add_argument("--strip-pilot-in-courses", action="store_true",
                   help='the old behaviour: remove "pilot" from course names and About')
    a.add_argument("--show-categories", action="store_true",
                   help="draw the seven category averages under the rating card (NEW-03). See README before using")
    a.add_argument("--prune", action="store_true", help="delete pages in the output folder whose school is no longer in the data")
    o = a.parse_args(argv)
    today = dt.date.fromisoformat(o.today) if o.today else today_sast()
    site = o.site.rstrip("/") if o.site else None
    if site and not re.match(r"^https://[A-Za-z0-9.-]+$", site):
        a.error("--site must look like https://example.co.za")
    data_dir = Path(o.data)
    out = Path(o.out)
    if o.master:
        from master_convert import convert_master_to_dir
        data_dir = convert_master_to_dir(o.master, out / "_from_master", today)
    build(data_dir, out, o.theme, today, site=site, index=o.index, scrub_courses=o.strip_pilot_in_courses and not o.keep_pilot_in_courses,
          show_categories=o.show_categories, prune=o.prune)
    if o.master:
        extra = Path(HERE.parent / "site" / "_redirects").read_text() if (HERE.parent / "site" / "_redirects").exists() else ""
        # Keep existing file lines (including /ad/FACT) and append generated ATO redirects.
        generated = redirect_lines(o.master)
        existing = {ln.split()[0] for ln in extra.splitlines() if ln.strip() and not ln.strip().startswith("#") and ln.split()}
        addon = [ln for ln in generated if ln.split()[0] not in existing]
        block = extra.rstrip() + "\n\n# Generated ATO school redirects (ATO-19).\n" + "\n".join(addon) + "\n"
        (out / "_redirects").write_text(block)
        print("wrote", len(addon), "ATO redirects")


if __name__ == "__main__":
    main()
