#!/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, unicodedata
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", "certificates"}
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



AERODROMES_PATH = HERE / "data" / "aerodromes.json"
_AERODROMES = None
# Official names often end with these words. "Port Alfred" must match "Port Alfred Airport"
# and must not also match another field that merely shares the town (ZA-0303 Fort D'Acre).
_NAME_SUFFIX = re.compile(
    r"\b(international\s+airport|national\s+airport|airport|airfield|aerodrome|airstrip)\s*$",
    re.I,
)


def norm_ident(value):
    s = str(value or "").strip().upper()
    return s or None


def norm_text(value):
    s = unicodedata.normalize("NFKD", str(value or ""))
    s = "".join(ch for ch in s if not unicodedata.combining(ch)).lower()
    s = s.replace("&", " and ")
    s = re.sub(r"[^a-z0-9]+", " ", s)
    return " ".join(s.split())


def core_name(value):
    return " ".join(_NAME_SUFFIX.sub("", norm_text(value)).split())


def load_aerodromes(path=None):
    """The app's aerodrome list (ident, name, town). Cached. Tests may pass a small list or path."""
    global _AERODROMES
    if path is None and _AERODROMES is not None:
        return _AERODROMES
    src = Path(path) if path else AERODROMES_PATH
    if not src.exists():
        ads = []
    else:
        data = json.loads(src.read_text())
        ads = data.get("aerodromes") if isinstance(data, dict) else data
        ads = list(ads or [])
    if path is None:
        _AERODROMES = ads
    return ads


def match_aerodrome(ident=None, name=None, town=None, catalog=None):
    """ICAO/ident first, then a unique name, then a unique town. None if it would be ambiguous.

    Name matching uses the official name with or without a trailing Airport / Airfield word, so
    "Port Alfred" links to FAPA (Port Alfred Airport) and not to ZA-0303 (Fort D'Acre, same town).
    """
    catalog = list(catalog if catalog is not None else load_aerodromes())
    ident = norm_ident(ident)
    if ident:
        hits = [ad for ad in catalog if norm_ident(ad.get("ident")) == ident]
        if len(hits) == 1:
            return hits[0]
        if len(hits) > 1:
            return None
        # Unknown code: fall through to name/town so a typo can still be rescued by the name.
    name_n, name_c = norm_text(name), core_name(name)
    town_n = norm_text(town)

    def unique(cands):
        return cands[0] if len(cands) == 1 else None

    if name_n:
        hit = unique([ad for ad in catalog if norm_text(ad.get("name")) == name_n])
        if hit:
            return hit
    if name_c:
        hit = unique([ad for ad in catalog if core_name(ad.get("name")) == name_c])
        if hit:
            return hit
    # Town only when exactly one aerodrome sits there. If several share the town, prefer the
    # one whose core official name is the base name or the town (Port Alfred -> FAPA).
    if town_n:
        in_town = [ad for ad in catalog if norm_text(ad.get("town")) == town_n]
        hit = unique(in_town)
        if hit:
            return hit
        keys = {k for k in (name_c, town_n) if k}
        if keys:
            hit = unique([ad for ad in in_town if core_name(ad.get("name")) in keys])
            if hit:
                return hit
    return None


def certs_of(base):
    """Unique certificates on one base, first seen first. Accepts certificate and/or certificates."""
    out, seen = [], set()
    items = list(base.get("certificates") or [])
    if base.get("certificate"):
        items = items + [base["certificate"]]
    for c in items:
        if not isinstance(c, dict):
            continue
        k = c.get("number")
        key = ("n", k) if k else ("o", id(c))
        if key in seen:
            continue
        seen.add(key)
        out.append(c)
    return out


def count_certificates(bases):
    return sum(len(certs_of(b)) for b in bases or [])


def _base_dedupe_key(base):
    ident = norm_ident(base.get("ident"))
    if ident:
        return ("id", ident)
    label = norm_text(base.get("name") or "") or norm_text(base.get("town") or "")
    return ("name", label)


def resolve_and_dedupe_bases(bases, catalog=None, who="?"):
    """Link each base to an aerodrome in the app list, then keep each base once.

    Several certificates at the same field stay listed on that one base. Does not invent a code
    when nothing in the list matches. Idempotent.
    """
    catalog = list(catalog if catalog is not None else load_aerodromes())
    resolved = []
    for b in bases or []:
        row = dict(b)
        ad = match_aerodrome(row.get("ident"), row.get("name"), row.get("town"), catalog)
        if ad:
            ident = norm_ident(ad.get("ident"))
            row["ident"] = ident
            row["href"] = f"/ad/{ident}"
            official = ad.get("name")
            # Fill a missing name, or replace a short town-as-name with the official aerodrome name.
            if official and (not row.get("name") or core_name(row.get("name")) == core_name(official)
                             or norm_text(row.get("name")) == norm_text(row.get("town"))):
                row["name"] = official
            if ad.get("town") and not row.get("town"):
                row["town"] = ad.get("town")
        else:
            ident = norm_ident(row.get("ident"))
            row["ident"] = ident
            # Only a known list entry may link. An unknown or missing code stays plain text.
            row["href"] = None
        row["certificates"] = certs_of(row)
        row["certificate"] = row["certificates"][0] if row["certificates"] else None
        resolved.append(row)

    merged = []
    index = {}
    for row in resolved:
        key = _base_dedupe_key(row)
        if key in index and key[1]:
            keep = merged[index[key]]
            have = {c.get("number") for c in keep["certificates"] if c.get("number")}
            for c in row["certificates"]:
                if not c.get("number") or c.get("number") not in have:
                    keep["certificates"].append(c)
                    if c.get("number"):
                        have.add(c.get("number"))
            keep["certificate"] = keep["certificates"][0] if keep["certificates"] else None
            if not keep.get("name") and row.get("name"):
                keep["name"] = row["name"]
            if not keep.get("town") and row.get("town"):
                keep["town"] = row["town"]
            continue
        index[key] = len(merged)
        merged.append(row)
    return merged


def prepare_bases(ato, catalog=None):
    """Resolve links and drop duplicate bases on a school record. Called from check()."""
    who = ato.get("id") or ato.get("slug") or "?"
    ato["bases"] = resolve_and_dedupe_bases(ato.get("bases") or [], catalog=catalog, who=who)
    return ato["bases"]


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", "lapsed"):
        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 [])
    prepare_bases(ato)
    # A resolved match is no longer "missing a code". Drop only that warning; leave others.
    warnings = [w for w in warnings if "missing aerodrome code" not in w]
    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 and not re.match(r"^[A-Z0-9-]{3,8}$", str(ident)):
            raise ValueError(f"{who}: aerodrome code {ident!r} is not valid")
        if href:
            # A link is allowed only to /ad/{CODE} for a code that is in the app list.
            if not ident or href != f"/ad/{ident}":
                raise ValueError(f"{who}: base {ident or href!r} must link to /ad/{{CODE}}")
            if href.startswith("/ad/") and not match_aerodrome(ident=ident):
                raise ValueError(f"{who}: base {ident} is not in the aerodrome list")
        else:
            label = b.get("name") or b.get("town") or ident or f"base {i}"
            if ident:
                warnings.append(f"{who}: aerodrome code {ident} is not in the aerodrome list")
            else:
                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 = count_certificates(ato.get("bases") or [])
    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=True):
    """Licences / Ratings / Other, matching the approved page. First 3 show; the rest sit behind More.
    Classify on the original course name, then maybe scrub "pilot" for display (decision D4).
    True (today's behaviour) removes the word from the label and About, so "Private Pilot Licence"
    still counts as a licence and reads "Private Licence". False keeps the licence's real name."""
    def display(text):
        if text is None:
            return text
        out = str(text)
        if scrub_courses:
            out = re.sub(r"\bpilot\b", "", out, flags=re.I)
        out = re.sub(r"\s+", " ", out)
        out = re.sub(r"\(\s*\)", "", out)
        return out.strip(" -")

    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:
        original = re.sub(r"\s+", " ", str(n)).strip() if n is not None else ""
        label = display(n)
        k = (label or "").lower()
        if not label or k in seen:
            continue
        seen.add(k)
        names.append((original, label))
    lic_words = re.compile(
        r"\b(spl|ppl|cpl|atpl|private\s+(pilot\s+)?licen[cs]e|commercial\s+(pilot\s+)?licen[cs]e|"
        r"airline\s+transport|national\s+pilot|student\s+(pilot\s+)?licen[cs]e)\b",
        re.I,
    )
    rat_words = re.compile(
        r"night|instrument|\bir\b|instructor|multi.?engine|aerotow|tug|heli|turbine|jet|"
        r"type rating|seaplane|aerobat|upset|uprt",
        re.I,
    )
    lic, rat, oth = [], [], []
    for original, label in names:
        low = original.lower()
        if lic_words.search(low):
            lic.append(label)
        elif rat_words.search(low):
            rat.append(label)
        else:
            oth.append(label)
    about = ato.get("about")
    if isinstance(about, str):
        ato["about"] = display(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=True, 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)
    prepare_bases(ato)
    for b in ato["bases"]:
        b.setdefault("certificate", None)
        b.setdefault("certificates", certs_of(b))
        b["certificate"] = b["certificates"][0] if b["certificates"] else None
        b.setdefault("anchor", None)
        b.setdefault("ident", None)
        b.setdefault("name", None)
        b.setdefault("town", None)
        for c in b["certificates"]:
            c.setdefault("updated", None)
            c.setdefault("date", None)
            c.setdefault("number", None)
            c.setdefault("valid_until", None)
    top = guest_top_reviews(reviews, now_ms=day_ms(today))
    for b in ato["bases"]:
        for c in b.get("certificates") or ([b["certificate"]] if b.get("certificate") else []):
            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")          # gold tick, Premium extras, posting and replying
    lapsed = status == "lapsed"                  # was paying, stopped: keeps claim and .official
    # verified / claimed includes lapsed so .official and existing replies stay (NEW-10).
    verified = status in ("paid", "verified", "gifted", "lapsed")
    can_reply = paid                             # lapsed loses posting and replying; old replies stay
    ato.setdefault("about", None)
    ato.setdefault("handle", None)
    ato.setdefault("status", 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']}"
    groups = course_groups(ato, scrub_courses)
    contact = ato.get("contact") or {}
    missing_contact = not (contact.get("phone") or contact.get("email"))
    missing_about = not str(ato.get("about") or "").strip()
    missing_aerodrome = (not ato["bases"]) or any(not (b.get("ident") or b.get("href")) for b in ato["bases"])
    missing_courses = not any(g.get("items") for g in groups)
    missing_expiry = False
    for b in ato["bases"]:
        for c in b.get("certificates") or ([]):
            if c and not c.get("date"):
                missing_expiry = True
                break
    claimed = verified
    show_claim_invite = (not claimed) and (
        missing_contact or missing_about or missing_aerodrome or missing_courses or missing_expiry
    )
    # No school-claim route exists yet; placeholder until that flow is built.
    claim_href = f"/ato/claim?slug={ato['slug']}"
    return {
        "ato": ato, "paid": paid, "verified": verified, "lapsed": lapsed, "can_reply": can_reply,
        "certificate_count": count_certificates(ato["bases"]),
        "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": groups,
        "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="")),
        "show_claim_invite": show_claim_invite, "claim_href": claim_href,
        "missing_contact": missing_contact, "missing_about": missing_about,
        "missing_aerodrome": missing_aerodrome, "missing_courses": missing_courses,
        "missing_expiry": missing_expiry,
        "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=True, 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)
    # Pages load /ato/_shared/topbar.js. If --out is already the /ato folder, write there.
    shared_src = HERE / "shared"
    if shared_src.exists():
        shared_dst = (out_dir / "_shared") if out_dir.name == "ato" else (out_dir / "ato" / "_shared")
        shared_dst.mkdir(parents=True, exist_ok=True)
        for f in shared_src.iterdir():
            if f.is_file():
                shutil.copy2(f, shared_dst / f.name)
    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='keep the word "pilot" in course names and About (decision D4). Default: removed, as before')
    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=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()
