#!/usr/bin/env python3
"""Role-view preview renderer for ATO pages.

The original generator in ../ato-generator/ is not modified. This folder is a separate
layer: it imports the original helpers (read-only) and renders role-aware pages from
MOCK getSchoolView-shaped data plus real school records from the master.

Correct school states (DECISIONS-MASTER + getSchoolView; the exporter at
tools/reviews/export_for_generator.mjs:30 is wrong and is not used here):

  unclaimed          — no claim. Claim invite. No gold tick, no .official, no Premium.
  claimed_unpaid     — claim approved, never paid. Claimed (no invite). No Premium,
                       no gold tick, no .official. Official starts after the first payment.
  paying             — claim approved and paying now (paid or gifted). Gold tick,
                       .official, official replies. Extras unlock only after 30 days paid.
  lapsed             — paid before, not now. NOT verified. No gold tick. Keeps .official.
                       No official replies. Extras go private. Can still vote.

Gold tick = claim approved AND currently paying. Sign-in = /signup/?next=/ato/{slug}/
Every mock review / rating / handle / Premium extra is labelled SAMPLE.
"""
from __future__ import annotations

import datetime as dt
import json
import shutil
import sys
from copy import deepcopy
from pathlib import Path
from urllib.parse import quote

from jinja2 import Environment, FileSystemLoader, select_autoescape, StrictUndefined
from markupsafe import Markup

HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
GEN = ROOT / "ato-generator"
MASTER_CANDIDATES = [
    Path("/workspace/database-MOVED-12nov/ato-data/ato-master-10nov.json"),
    ROOT.parent / "database-MOVED-12nov" / "ato-data" / "ato-master-10nov.json",
    HERE / "mock" / "master-slice.json",
]
OUT = HERE / "out"
TODAY = dt.date(2026, 11, 12)
SIGNIN = "/signup/?next={path}"  # MT rule — do not use the original /signin/?return=
PAID_DAYS_NEEDED = 30
SLUGS = ("central-flying-academy", "bucephalus-air", "lowveld-aero-club")

sys.path.insert(0, str(GEN))
import generator as G  # noqa: E402  (read-only import of the original)
import svg  # noqa: E402
import rating as rating_rules  # noqa: E402
from master_convert import convert_school  # noqa: E402

CATEGORIES = G.CATEGORIES  # (key, label, hint)


# Simple 13px stars for directory cards. The v6 glass SVG (svg.pyramid_line)
# is too ornate at 11px and a partial fill reads as a "1" next to an empty star.
_STAR = "M12 2.6 14.9 8.5 21.4 9.4 16.7 14 17.8 20.5 12 17.4 6.2 20.5 7.3 14 2.6 9.4 9.1 8.5Z"
_GOLD = "#F5B83D"
_EMPTY = "rgba(255,255,255,.22)"


def compact_stars(rating, kind="glass"):
    """Five simple stars in a row. Partial fills stay readable at 13px."""
    try:
        rating = float(rating)
    except (TypeError, ValueError):
        rating = 0.0
    fills = [0.0] * 5
    if kind != "empty":
        full = int(rating)
        frac = float(rating) - full
        for i in range(5):
            fills[i] = 1.0 if i < full else (frac if i == full else 0.0)
    parts = []
    for i, f in enumerate(fills):
        clip = ""
        fill = _GOLD if f >= 1 else (_EMPTY if f <= 0 else _GOLD)
        if 0 < f < 1:
            cid = f"cs{i}"
            clip = (
                f'<defs><clipPath id="{cid}">'
                f'<rect x="2" y="2" width="{20 * f:.2f}" height="20"/></clipPath></defs>'
            )
            parts.append(
                f'<svg viewBox="2 2 20 20" width="13" height="13" aria-hidden="true">{clip}'
                f'<path d="{_STAR}" fill="{_EMPTY}"/>'
                f'<path d="{_STAR}" fill="{_GOLD}" clip-path="url(#{cid})"/></svg>'
            )
        else:
            parts.append(
                f'<svg viewBox="2 2 20 20" width="13" height="13" aria-hidden="true">'
                f'<path d="{_STAR}" fill="{fill}"/></svg>'
            )
    label = "Rating not shown yet" if kind == "empty" else f"{rating} out of 5 stars"
    return Markup(
        f'<span class="stars-compact" role="img" aria-label="{label}">{"".join(parts)}</span>'
    )




def load_master():
    for p in MASTER_CANDIDATES:
        if p.exists():
            return json.loads(p.read_text()), p
    raise SystemExit("ATO master not found")


def public_school(master, slug, today):
    raw = next(s for s in master["schools"] if s["slug"] == slug)
    rec = convert_school(raw, today)
    rec.pop("_warnings", None)
    # Keep a small public extras pocket (not fed to generator.check).
    fleet = []
    for item in raw.get("fleet") or []:
        if isinstance(item, dict) and item.get("type"):
            fleet.append(item["type"])
        elif isinstance(item, str):
            fleet.append(item)
    return rec, {"fleet_types": fleet, "raw_name": raw.get("trading_name") or raw.get("official_name")}


def stars_overall(cats):
    vals = [v for v in cats.values() if v is not None]
    return sum(vals) / len(vals)


# ---------------------------------------------------------------------------
# SAMPLE reviews for Central Flying Academy (getSchoolView / publicReview shape)
# 23 ratings feed the summary; 8 written cards are drawn so the picture stays readable.
# IDs start with "sample-" (not "ex") so they never trip REV-022 on a real school id.
# ---------------------------------------------------------------------------
def cfa_rating_rows():
    """23 SAMPLE ratings: varied category sets, all aged > 7 days."""
    rows = []
    # Eight written reviews (also used as cards)
    written = [
        {"id": "sample-cfa-01", "stars": {"org": 5, "flt": 5, "gnd": 4, "ins": 5, "saf": 5, "val": 4, "avl": 5}, "text": "yes", "up": 18},
        {"id": "sample-cfa-02", "stars": {"org": 5, "flt": 4, "gnd": 5, "ins": 5, "saf": 4, "val": 5, "avl": 4}, "text": "yes", "up": 14},
        {"id": "sample-cfa-03", "stars": {"org": 4, "flt": 5, "gnd": 4, "ins": 4, "saf": 5, "val": 4, "avl": 4}, "text": "yes", "up": 11},
        {"id": "sample-cfa-04", "stars": {"org": 5, "ins": 5, "saf": 5, "gnd": 5}, "text": "yes", "up": 9},
        {"id": "sample-cfa-05", "stars": {"org": 3, "flt": 3, "gnd": 4, "ins": 3, "saf": 4, "val": 2, "avl": 3}, "text": "yes", "up": 6},
        {"id": "sample-cfa-06", "stars": {"org": 4, "flt": 4, "ins": 5, "val": 4, "avl": 5}, "text": "yes", "up": 5},
        {"id": "sample-cfa-07", "stars": {"org": 5, "flt": 5, "gnd": 5, "ins": 5, "saf": 5, "val": 5, "avl": 4}, "text": "yes", "up": 4},
        {"id": "sample-cfa-08", "stars": {"org": 4, "gnd": 4, "ins": 4, "val": 3}, "text": "yes", "up": 2},
    ]
    # One stars-only (member-visible, not a guest card)
    stars_only = {"id": "sample-cfa-09", "stars": {"org": 5, "ins": 4, "avl": 5}, "text": "", "up": 0}
    # Fourteen more stars that only count toward the average
    more = [
        {"org": 5, "flt": 4, "ins": 5, "val": 4},
        {"org": 4, "flt": 5, "gnd": 4, "saf": 5},
        {"org": 5, "ins": 5, "avl": 5},
        {"org": 4, "flt": 4, "gnd": 5, "ins": 4, "val": 4},
        {"org": 5, "saf": 5, "val": 5, "avl": 4},
        {"org": 3, "flt": 4, "ins": 3, "val": 3},
        {"org": 5, "flt": 5, "gnd": 4, "ins": 5},
        {"org": 4, "ins": 4, "saf": 4, "avl": 5},
        {"org": 5, "flt": 4, "val": 5},
        {"org": 4, "gnd": 5, "ins": 5, "saf": 4},
        {"org": 5, "flt": 5, "ins": 4, "avl": 4},
        {"org": 4, "val": 4, "avl": 3, "org": 4},
        {"org": 5, "ins": 5, "gnd": 5, "saf": 5},
        {"org": 4, "flt": 4, "ins": 4, "val": 4, "avl": 4},
    ]
    for r in written + [stars_only]:
        rows.append({"stars": r["stars"], "status": "published", "text": r["text"],
                     "account_created": "2025-06-01"})
    for i, st in enumerate(more, start=10):
        # fix accidental duplicate key in one dict above — already last org wins
        rows.append({"stars": st, "status": "published", "text": "", "account_created": "2025-03-01"})
    return rows, written, stars_only


def cfa_cards():
    """Eight written SAMPLE cards + one stars-only, in publicReview-ish form plus generator fields."""
    return [
        {
            "id": "sample-cfa-01", "up": 18, "stars": 4.7,
            "categories": {"org": 5, "flt": 5, "gnd": 4, "ins": 5, "saf": 5, "val": 4, "avl": 5},
            "title": "Clear briefings and a well-kept fleet",
            "text": "I did my PPL and night rating here. Briefings were clear, the aircraft came back cleaned, and they told me early if something was booked out. Office replies on the same day.",
            "published_at": "2026-08-12", "edited": False,
            "author": {"name": "Lerato M.", "anonymous": False, "badges": ["founding"], "licences": ["CPL", "Night"]},
            "official_replies": [{
                "school": "centralflying", "paid": True, "own": True, "when": "2026-08-14",
                "text": "Thank you, Lerato. We will keep the same standard on the next course."
            }],
            "member_replies": [],
        },
        {
            "id": "sample-cfa-02", "up": 14, "stars": 4.6,
            "categories": {"org": 5, "flt": 4, "gnd": 5, "ins": 5, "saf": 4, "val": 5, "avl": 4},
            "title": "Ground school that actually prepares you",
            "text": "The notes and exam prep were the strongest part. I sat the exams once. Hangar time can run tight on Saturday mornings, but they moved me when they could.",
            "published_at": "2026-07-03", "edited": True, "edited_at": "2026-07-03",
            "author": {"name": "James K.", "anonymous": False, "badges": ["dfe"], "licences": ["ATPL", "Instructor"]},
            "official_replies": [],
            "member_replies": [{
                "id": "sample-cfa-02-r1", "author": {"kind": "member", "label": "Sipho D.", "chips": ["PPL"]},
                "text": "Same on the Saturday slot. Mid-week was easier.", "date": "2026-07-05", "edited": None, "up": 3, "mine": False
            }],
        },
        {
            "id": "sample-cfa-03", "up": 11, "stars": 4.3,
            "categories": {"org": 4, "flt": 5, "gnd": 4, "ins": 4, "saf": 5, "val": 4, "avl": 4},
            "title": "Safety culture is taken seriously",
            "text": "Every flight had a proper brief and debrief. A snag I wrote up was fixed before my next booking. That is why I stayed.",
            "published_at": "2026-06-21", "edited": False,
            "author": {"name": "Anonymous", "anonymous": True, "badges": [], "licences": []},
            "official_replies": [],
            "member_replies": [],
        },
        {
            "id": "sample-cfa-04", "up": 9, "stars": 5.0,
            "categories": {"org": 5, "ins": 5, "saf": 5, "gnd": 5},
            "title": "Patient instructors",
            "text": "I was stuck on circuits for longer than I wanted. Nobody rushed me, and the next instructor had read the notes from the last one.",
            "published_at": "2026-05-18", "edited": False,
            "author": {"name": "Amina S.", "anonymous": False, "badges": [], "licences": ["PPL"]},
            "official_replies": [],
            "member_replies": [],
        },
        {
            "id": "sample-cfa-05", "up": 6, "stars": 3.1,
            "categories": {"org": 3, "flt": 3, "gnd": 4, "ins": 3, "saf": 4, "val": 2, "avl": 3},
            "title": "Good teaching, slow on invoices",
            "text": "The flying is fine. Getting a clear invoice took three weeks, and two bookings were moved with short notice. Worth knowing before you plan a rating in a hurry.",
            "published_at": "2026-04-09", "edited": False,
            "author": {"name": "Chris P.", "anonymous": False, "badges": [], "licences": ["PPL", "Night"]},
            "official_replies": [{
                "school": "centralflying", "paid": True, "own": True, "when": "2026-04-11",
                "text": "Chris, thank you for the honest note. We have changed how invoices go out and we are sorry for the wait."
            }],
            "member_replies": [],
        },
        {
            "id": "sample-cfa-06", "up": 5, "stars": 4.4,
            "categories": {"org": 4, "flt": 4, "ins": 5, "val": 4, "avl": 5},
            "title": None,
            "text": "Booked a week of flying in September and got the slots I asked for. Aircraft felt tidy. I would come back for the IR.",
            "published_at": "2026-09-02", "edited": False,
            "author": {"name": "Naledi T.", "anonymous": False, "badges": [], "licences": ["CPL"]},
            "official_replies": [],
            "member_replies": [],
            "mine": True,  # the signed-in Pro member's own review
        },
        {
            "id": "sample-cfa-07", "up": 4, "stars": 4.9,
            "categories": {"org": 5, "flt": 5, "gnd": 5, "ins": 5, "saf": 5, "val": 5, "avl": 4},
            "title": "Worth the drive to Rand",
            "text": "I travel in from the East Rand. It is worth it. Dispatch is organised and I never felt pushed to fly when the weather was off.",
            "published_at": "2026-03-28", "edited": False,
            "author": {"name": "Thabo R.", "anonymous": False, "badges": ["founding"], "licences": ["ATPL"]},
            "official_replies": [],
            "member_replies": [],
        },
        {
            "id": "sample-cfa-08", "up": 2, "stars": 3.8,
            "categories": {"org": 4, "gnd": 4, "ins": 4, "val": 3},
            "title": "Solid, not cheap",
            "text": "Teaching is consistent. Prices sit at the high end for Rand. If you budget for that, you will be fine.",
            "published_at": "2026-02-14", "edited": False, "text_added_at": "2026-02-16",
            "author": {"name": "Anonymous", "anonymous": True, "badges": [], "licences": []},
            "official_replies": [],
            "member_replies": [],
        },
        {
            "id": "sample-cfa-09", "up": 0, "stars": 4.7,
            "categories": {"org": 5, "ins": 4, "avl": 5},
            "title": None, "text": "", "published_at": "2026-10-01", "edited": False,
            "author": {"name": "Sam V.", "anonymous": False, "badges": [], "licences": ["SPL"]},
            "official_replies": [], "member_replies": [], "stars_only": True,
        },
    ]


def bucephalus_rows_and_cards():
    """A flatter school: enough reviews to show a sub-4.0 (flat, not gold) rating."""
    rows = [
        {"stars": {"org": 4, "ins": 4, "val": 3, "avl": 3}, "status": "published", "text": "yes", "account_created": "2025-01-01"},
        {"stars": {"org": 3, "flt": 4, "ins": 4, "saf": 4}, "status": "published", "text": "yes", "account_created": "2025-01-01"},
        {"stars": {"org": 4, "gnd": 3, "ins": 3, "val": 3, "avl": 4}, "status": "published", "text": "yes", "account_created": "2025-01-01"},
        {"stars": {"org": 4, "ins": 4, "saf": 3}, "status": "published", "text": "yes", "account_created": "2025-01-01"},
        {"stars": {"org": 3, "flt": 3, "val": 4, "avl": 3}, "status": "published", "text": "yes", "account_created": "2025-01-01"},
        {"stars": {"org": 4, "ins": 3, "gnd": 4}, "status": "published", "text": "yes", "account_created": "2025-01-01"},
        {"stars": {"org": 3, "val": 3, "avl": 4, "ins": 4}, "status": "published", "text": "", "account_created": "2025-01-01"},
        {"stars": {"org": 4, "flt": 4, "ins": 3, "saf": 3}, "status": "published", "text": "", "account_created": "2025-01-01"},
        {"stars": {"org": 3, "ins": 4, "val": 3}, "status": "published", "text": "", "account_created": "2025-01-01"},
    ]
    cards = [
        {
            "id": "sample-buc-01", "up": 7, "stars": 3.5,
            "categories": {"org": 4, "ins": 4, "val": 3, "avl": 3},
            "title": "Friendly base, mixed fleet days",
            "text": "People at the desk are helpful. I had two aircraft go tech in one week. They found me another slot, but it stretched the rating.",
            "published_at": "2026-08-01", "edited": False,
            "author": {"name": "Pieter H.", "anonymous": False, "badges": [], "licences": ["PPL"]},
            "official_replies": [], "member_replies": [],
        },
        {
            "id": "sample-buc-02", "up": 5, "stars": 3.8,
            "categories": {"org": 3, "flt": 4, "ins": 4, "saf": 4},
            "title": None,
            "text": "Instructors know the local fields well. Office hours are shorter than I expected, so book early in the week.",
            "published_at": "2026-06-15", "edited": False,
            "author": {"name": "Anonymous", "anonymous": True, "badges": [], "licences": []},
            "official_replies": [], "member_replies": [],
        },
        {
            "id": "sample-buc-03", "up": 4, "stars": 3.4,
            "categories": {"org": 4, "gnd": 3, "ins": 3, "val": 3, "avl": 4},
            "title": "Decent value if you are already nearby",
            "text": "Three bases is handy if you live in the area. Ground school was uneven between weeks.",
            "published_at": "2026-05-02", "edited": False,
            "author": {"name": "Megan L.", "anonymous": False, "badges": [], "licences": ["CPL"]},
            "official_replies": [], "member_replies": [],
        },
        {
            "id": "sample-buc-04", "up": 2, "stars": 3.7,
            "categories": {"org": 4, "ins": 4, "saf": 3},
            "title": "Would fly here again",
            "text": "Nothing fancy. Booking was straightforward and the briefing was honest about the weather.",
            "published_at": "2026-04-20", "edited": False,
            "author": {"name": "Kobus V.", "anonymous": False, "badges": [], "licences": ["PPL", "Night"]},
            "official_replies": [], "member_replies": [],
        },
    ]
    return rows, cards


def school_state(kind):
    """Canonical flags for one school-state. Never uses the exporter's verified/unclaimed mapping."""
    # kind: unclaimed | claimed_unpaid | paying | lapsed
    claim_approved = kind != "unclaimed"
    paying = kind == "paying"
    ever_paid = kind in ("paying", "lapsed")
    lapsed = kind == "lapsed"
    paid_days = 80 if kind == "paying" else (400 if kind == "lapsed" else 0)
    extras = paying and paid_days >= PAID_DAYS_NEEDED
    return {
        "state_kind": kind,
        "claim_approved": claim_approved,
        "paying": paying,
        "ever_paid": ever_paid,
        "lapsed": lapsed,
        "claimed_unpaid": kind == "claimed_unpaid",
        "unclaimed": kind == "unclaimed",
        # Gold tick: claim approved AND currently paying (paid or gifted). Lapsed is not verified.
        "gold_tick": claim_approved and paying,
        "verified": claim_approved and paying,  # same rule as getSchoolView
        "official": claim_approved and ever_paid,  # .official from first payment, stays after lapse
        "can_official_reply": claim_approved and paying,
        "premium_extras": extras,
        "paid_days": paid_days,
        "show_claim_invite": kind == "unclaimed",
        "handle": None,  # filled per school when official
    }


def attach_rating(ato, rows, visible_written, certificates):
    summary = rating_rules.summarise(rows, TODAY, certificates=certificates)
    ato["rating"] = summary
    ato["visible_reviews"] = visible_written
    return summary


def role_can(role, school_st, plan="pro"):
    """getSchoolView `can` object, plus flags the template needs."""
    if role == "guest":
        return {
            "review": False, "review_reason": "sign_in", "anonymous": False,
            "reply": "none", "vote": False, "edit": False, "report": True,
            "quota_left": 0, "quota": 0, "cycle_ends": None,
            "votes_left": 0, "votes_quota": 0, "official_reply": False,
        }
    if role == "admin":
        return {
            "review": False, "review_reason": "owner", "anonymous": False,
            "reply": "none", "vote": False, "edit": False, "report": True,
            "quota_left": 0, "quota": 0, "cycle_ends": None,
            "votes_left": None, "votes_quota": None, "official_reply": False,
            "admin_hide": True, "admin_remove": True,
        }
    if role in ("owner", "owner-lapsed", "owner-claimed-unpaid"):
        official_reply = school_st["can_official_reply"]
        vote = school_st["official"]  # lapsed still votes; claimed-unpaid does not
        return {
            "review": False, "review_reason": "school", "anonymous": False,
            "reply": "official" if official_reply else "none",
            "vote": vote, "edit": True, "report": True,
            "quota_left": 0, "quota": 0, "cycle_ends": None,
            "votes_left": None, "votes_quota": None,
            "official_reply": official_reply,
        }
    # member
    if plan == "free":
        return {
            "review": True, "review_reason": None, "anonymous": False,
            "reply": "own_thread", "vote": True, "edit": False, "report": True,
            "quota_left": 3, "quota": 5, "cycle_ends": "12 Dec 2026",
            "votes_left": 82, "votes_quota": 100,
            "official_reply": False,
        }
    if plan == "trial":
        return {
            "review": True, "review_reason": None, "anonymous": False,  # Trial cannot post anonymously
            "reply": "anywhere", "vote": True, "edit": True, "report": True,
            "quota_left": 17, "quota": 20, "cycle_ends": "26 Nov 2026",
            "votes_left": None, "votes_quota": None,
            "official_reply": False,
        }
    # pro / founding
    return {
        "review": True, "review_reason": None, "anonymous": True,
        "reply": "anywhere", "vote": True, "edit": True, "report": True,
        "quota_left": 18, "quota": 20, "cycle_ends": "12 Dec 2026",
        "votes_left": None, "votes_quota": None,
        "official_reply": False,
    }


def member_mine(plan="pro"):
    return {
        "id": "sample-cfa-06",
        "state": "published",
        "anonymous": False,
        "stars": "4.4",
        "categories": {"org": 4, "flt": 4, "ins": 5, "val": 4, "avl": 5},
        "title": None,
        "text": "Booked a week of flying in September and got the slots I asked for. Aircraft felt tidy. I would come back for the IR.",
        "posted": "2026-09-02",
        "edited": None,
        "text_added": None,
        "edit_until": None,  # outside 15-minute window
        "can_add_text": False,
        "can_delete": True,
        "replace_from": "2 Mar 2027",
    }


def premium_extras(school_slug, extras, unlocked):
    """SAMPLE Premium modules. Content is only sent when unlocked (paid ≥ 30 days)."""
    if school_slug != "central-flying-academy":
        types = ["Cessna 172"] if school_slug == "bucephalus-air" else []
    else:
        types = extras.get("fleet_types") or ["Cessna 172", "Cessna 172 RG"]
    payload = {
        "unlocked": unlocked,
        "unlocks_after_days": PAID_DAYS_NEEDED,
        "modules": [
            {"key": "fleet", "title": "Fleet", "rule": "ATO-06"},
            {"key": "announcements", "title": "Announcements", "rule": "ATO-03"},
            {"key": "prices", "title": "Course prices", "rule": "ATO-04"},
            {"key": "jobs", "title": "Jobs", "rule": "ATO-05"},
            {"key": "intake", "title": "Intake dates", "rule": "ATO-08"},
            {"key": "booking", "title": "Booking", "rule": "ATO-09"},
        ],
    }
    if not unlocked:
        return payload
    payload["fleet"] = [{"type": t, "count": n, "sample": True}
                        for t, n in zip(types, (6, 2, 1))]
    payload["announcements"] = [
        {"title": "Night-rating block in January", "when": "2 Nov 2026",
         "text": "Eight slots left for the January night-rating block. Book with the office."},
    ]
    payload["prices"] = [
        {"name": "PPL", "price": "R 12 500 / hour, wet", "updated": "1 Oct 2026"},
        {"name": "Night rating", "price": "R 11 800 / hour, wet", "updated": "1 Oct 2026"},
    ]
    payload["jobs"] = [{"title": "Grade II instructor", "when": "Open", "text": "One full-time seat from January."}]
    payload["intake"] = [{"name": "PPL intake", "date": "12 Jan 2027", "seats": "4 seats open"}]
    payload["booking"] = {"label": "Request a booking", "href": "mailto:info@cfasa.co.za"}
    return payload


def apply_state_to_ato(ato, st, handle):
    ato = deepcopy(ato)
    if st["official"] and handle:
        ato["handle"] = handle
    else:
        ato["handle"] = None
    # Status string is only for the original page_model. We override flags afterwards.
    if st["paying"]:
        ato["status"] = "paid"
    elif st["lapsed"]:
        ato["status"] = "lapsed"
    elif st["claimed_unpaid"]:
        # The original generator has no "claimed_unpaid". Feed "verified" would be the
        # exporter bug. Feed nothing paid-like; we override flags ourselves.
        ato["status"] = None
    else:
        ato["status"] = "unclaimed"
    return ato


def env():
    e = Environment(
        loader=FileSystemLoader(str(HERE / "template")),
        autoescape=select_autoescape(["html", "j2"]),
        undefined=StrictUndefined,
        trim_blocks=True,
        lstrip_blocks=True,
    )
    e.filters["replace"] = lambda s, a, b: str(s).replace(a, b)
    e.globals["svg"] = svg
    e.globals["compact_stars"] = compact_stars
    e.globals["nice_date"] = G.nice_date
    e.globals["nice_month"] = G.nice_month
    return e


def copy_assets(out):
    fonts = out / "fonts"
    if fonts.exists():
        shutil.rmtree(fonts)
    shutil.copytree(HERE / "assets" / "fonts", fonts)
    shutil.copytree(HERE / "assets" / "ato-v6", out / "ato-v6", dirs_exist_ok=True)
    shared = out / "ato" / "_shared"
    shared.mkdir(parents=True, exist_ok=True)
    for p in (HERE / "assets" / "ato" / "_shared").iterdir():
        shutil.copy2(p, shared / p.name)
    shutil.copy2(HERE / "assets" / "brand" / "logo-mark.png", out / "logo-mark.png")
    if (HERE / "assets" / "favicon.ico").exists():
        shutil.copy2(HERE / "assets" / "favicon.ico", out / "favicon.ico")
    # Role-layer CSS/JS
    (out / "roles").mkdir(exist_ok=True)
    shutil.copy2(HERE / "static" / "roles.css", out / "roles" / "roles.css")
    shutil.copy2(HERE / "static" / "roles.js", out / "roles" / "roles.js")
    shutil.copy2(HERE / "static" / "directory.css", out / "roles" / "directory.css")
    if (HERE / "assets" / "ato-guest.js").exists():
        shutil.copy2(HERE / "assets" / "ato-guest.js", out / "ato" / "_shared" / "ato-guest.js")


def role_meta(role, plan=None):
    labels = {
        "guest": ("Guest", "You are not signed in."),
        "member": ("Member · Pro", "Signed in as a Pro member. SAMPLE account."),
        "member-free": ("Member · Free", "Signed in as a Free member. SAMPLE account."),
        "member-trial": ("Member · Trial", "Signed in as a Trial member. SAMPLE account."),
        "owner": ("ATO owner · Premium", "School login, Premium paid more than 30 days. SAMPLE."),
        "owner-lapsed": ("ATO owner · lapsed", "School login. Premium has ended. Not verified. SAMPLE."),
        "owner-claimed-unpaid": ("ATO owner · claimed, no Premium", "Claim approved, no payment yet. SAMPLE."),
        "admin": ("Super Admin", "Owner controls. Hide and remove only. SAMPLE."),
    }
    kind = {"guest": "guest", "member": "member", "member-free": "member", "member-trial": "member",
            "owner": "school", "owner-lapsed": "school", "owner-claimed-unpaid": "school",
            "admin": "super_admin"}[role]
    plan_of = {"guest": "guest", "member": "pro", "member-free": "free", "member-trial": "trial",
               "owner": "ato", "owner-lapsed": "ato", "owner-claimed-unpaid": "ato", "admin": "admin"}[role]
    return {"role": role, "kind": kind, "plan": plan or plan_of, "label": labels[role][0], "blurb": labels[role][1]}


def build_page_context(ato_base, extras, cards, rating_rows, role, school_st, handle, written_count):
    meta = role_meta(role)
    ato = apply_state_to_ato(ato_base, school_st, handle)
    allowed = {"id","author","stars","title","text","status","published_at","edited","edited_at",
               "text_added_at","up","upvotes","official_replies"}
    def for_generator(card):
        row = {k: deepcopy(card[k]) for k in allowed if k in card}
        row.setdefault("status", "published")
        return row
    visible_cards = [c for c in cards if str(c.get("text") or "").strip()] if role == "guest" else list(cards)
    ato["top_reviews"] = [for_generator(c) for c in visible_cards]
    n_certs = G.count_certificates(ato.get("bases") or [])
    attach_rating(ato, rating_rows, written_count, n_certs)
    G.check(ato)
    model = G.page_model(ato, TODAY, site=None, index=False, scrub_courses=True, show_categories=True)
    # Override generator flags that follow the exporter-style status mapping.
    model["paid"] = school_st["gold_tick"]
    model["verified"] = school_st["verified"]  # paying only — lapsed is not verified
    model["lapsed"] = school_st["lapsed"]
    model["claimed_unpaid"] = school_st["claimed_unpaid"]
    model["unclaimed"] = school_st["unclaimed"]
    model["official"] = school_st["official"]
    model["gold_tick"] = school_st["gold_tick"]
    model["can_reply"] = school_st["can_official_reply"]
    model["show_claim_invite"] = school_st["show_claim_invite"]
    path = f"/ato/{ato['slug']}/"
    model["signin_href"] = SIGNIN.format(path=quote(path, safe=""))
    model["claim_href"] = f"/ato/claim?slug={ato['slug']}"
    # Role view
    plan = meta["plan"] if meta["kind"] == "member" else None
    can = role_can(role, school_st, plan=plan or "pro")
    signed_in = role != "guest"
    show_all = role != "guest"
    by_id = {c["id"]: c for c in cards}
    if show_all:
        reviews = deepcopy(cards)
    else:
        reviews = [deepcopy(by_id[r["id"]]) for r in model["top"] if r["id"] in by_id]
        model["top"] = reviews
    # Official replies exist only after a first payment. Already-public ones stay when lapsed.
    if school_st["claimed_unpaid"] or school_st["unclaimed"]:
        for r in reviews:
            r["official_replies"] = []
    # Guest: official replies only (already on official_replies). Member: all replies.
    model.update({
        "meta": meta,
        "can": can,
        "signed_in": signed_in,
        "show_all_reviews": show_all,
        "reviews": reviews,
        "mine": member_mine(plan) if role in ("member", "member-free", "member-trial") and ato["slug"] == "central-flying-academy" else None,
        "my_votes": {"review:sample-cfa-01": 1} if signed_in and meta["kind"] == "member" else {},
        "premium": premium_extras(ato["slug"], extras, school_st["premium_extras"]),
        "school_st": school_st,
        "sample": True,
        "preview_shown": len(reviews),
        "preview_total": written_count if ato["slug"] == "central-flying-academy" else (len(reviews) if written_count else 0),
        "data_theme": "night",
        "data_pal": "purple",
        "nav_locked_tools": meta["plan"] in ("guest", "free") or (meta["kind"] == "school" and not school_st["paying"]),
        "report_reasons": [
            ("spam", "Spam"), ("not_first_hand", "Not first-hand"), ("harassment", "Harassment"),
            ("private_info", "Private information"), ("illegal", "Illegal"), ("other", "Other"),
        ],
    })
    # Categories: guests never get them (NEW-13). page_model already built cat_rows.
    if role == "guest":
        model["cat_rows"] = []
        model["show_categories"] = False
    else:
        model["show_categories"] = True
    return model


def write_slice(master, path):
    schools = [s for s in master["schools"] if s["slug"] in SLUGS]
    slim = {"schema_version": master.get("schema_version"), "title": "Role-test slice (3 schools)",
            "note": "Public school fields only, copied from ato-master-10nov.json for a reproducible preview.",
            "schools": schools}
    path.write_text(json.dumps(slim, indent=2, ensure_ascii=False))


def build():
    master, src = load_master()
    (HERE / "mock").mkdir(exist_ok=True)
    write_slice(master, HERE / "mock" / "master-slice.json")

    cfa_rows, written, _ = cfa_rating_rows()
    cfa_cards_ = cfa_cards()
    buc_rows, buc_cards = bucephalus_rows_and_cards()

    packs = {}
    for slug in SLUGS:
        rec, extras = public_school(master, slug, TODAY)
        packs[slug] = {"ato": rec, "extras": extras}

    # Default school states for the three public pages (guest/member/owner/admin of each):
    # CFA = paying ≥ 30 days (main pictures). Bucephalus = paying too, flatter rating.
    # Lowveld = unclaimed, no reviews.
    default_state = {
        "central-flying-academy": school_state("paying"),
        "bucephalus-air": school_state("paying"),
        "lowveld-aero-club": school_state("unclaimed"),
    }
    handles = {
        "central-flying-academy": "centralflying",
        "bucephalus-air": "bucephalusair",
        "lowveld-aero-club": None,
    }
    reviews_of = {
        "central-flying-academy": (cfa_rows, cfa_cards_, 8),  # 8 written cards; 23 in the average
        "bucephalus-air": (buc_rows, buc_cards, 4),
        "lowveld-aero-club": ([], [], 0),
    }

    # Pages to emit
    # For CFA, also emit lapsed + claimed-unpaid owner views (same school, different state).
    jobs = []
    for slug in SLUGS:
        for role in ("guest", "member", "member-free", "owner", "admin"):
            jobs.append((slug, role, default_state[slug]))
    jobs.append(("central-flying-academy", "owner-lapsed", school_state("lapsed")))
    jobs.append(("central-flying-academy", "owner-claimed-unpaid", school_state("claimed_unpaid")))
    jobs.append(("central-flying-academy", "member-trial", default_state["central-flying-academy"]))

    OUT.mkdir(parents=True, exist_ok=True)
    copy_assets(OUT)
    jinja = env()
    tpl = jinja.get_template("ato.html.j2")
    written_pages = []
    for slug, role, st in jobs:
        st = dict(st)
        st["handle"] = handles[slug] if st["official"] else None
        rows, cards, written_n = reviews_of[slug]
        ctx = build_page_context(packs[slug]["ato"], packs[slug]["extras"], cards, rows, role, st, handles[slug], written_n)
        html = tpl.render(**ctx)
        dest_dir = OUT / "ato" / slug
        dest_dir.mkdir(parents=True, exist_ok=True)
        dest = dest_dir / f"{role}.html"
        dest.write_text(html)
        written_pages.append(dest)

    # Directory
    dir_cards = []
    for slug in SLUGS:
        st = default_state[slug]
        ato = apply_state_to_ato(packs[slug]["ato"], st, handles[slug])
        rows, cards, written_n = reviews_of[slug]
        n_certs = G.count_certificates(ato.get("bases") or [])
        summary = attach_rating(ato, rows, written_n, n_certs)
        G.check(ato)
        model = G.page_model(ato, TODAY, scrub_courses=True, show_categories=False)
        b0 = (ato.get("bases") or [{}])[0]
        cert = None
        if b0.get("certificates"):
            cert = b0["certificates"][0]
        elif b0.get("certificate"):
            cert = b0["certificate"]
        dir_cards.append({
            "slug": slug,
            "name": ato["name"],
            "cert": (cert or {}).get("number") or "",
            "place": ", ".join([p for p in (b0.get("name"), b0.get("town")) if p]),
            "icao": b0.get("ident"),
            "until": (cert or {}).get("date") or ((cert or {}).get("valid_until") and G.nice_date(cert["valid_until"])),
            "current": (cert or {}).get("current"),
            "courses": sum(len(g["items"]) for g in model["course_groups"]),
            "rating_shown": summary["shown"],
            "score": summary["score"],
            "gold": summary["gold"],
            "count": summary["count"],
            "kind": "empty" if not summary["shown"] else ("glass" if summary["gold"] else "flat"),
            "official": st["official"] and handles[slug],
            "handle": handles[slug] if st["official"] else None,
            "gold_tick": st["gold_tick"],
            "href": f"/ato/{slug}/guest.html",
        })
    dir_html = jinja.get_template("directory.html.j2").render(
        cards=dir_cards, sample=True, data_theme="night", data_pal="purple",
        signin_href="/signup/?next=/ato/",
    )
    (OUT / "directory.html").write_text(dir_html)

    # Index
    index = jinja.get_template("index.html.j2").render(
        pages=[{
            "slug": slug, "name": packs[slug]["ato"]["name"],
            "roles": ["guest", "member", "member-free", "owner", "admin"]
                     + (["owner-lapsed", "owner-claimed-unpaid", "member-trial"] if slug == "central-flying-academy" else []),
        } for slug in SLUGS],
        data_theme="night", data_pal="purple",
    )
    (OUT / "index.html").write_text(index)

    # Save mock views for the coverage doc / later agents
    (HERE / "mock" / "views-note.json").write_text(json.dumps({
        "note": "SAMPLE getSchoolView-shaped flags used by render.py. No D1.",
        "signin": "/signup/?next=/ato/{slug}/",
        "gold_tick": "claim approved AND currently paying. Lapsed is not verified.",
        "exporter_bug": "export_for_generator.mjs:30 maps .official-without-tick to verified (hides lapsed) and never-paid claims to unclaimed (shows a Claim invite).",
        "pages": [str(p.relative_to(OUT)) for p in written_pages],
    }, indent=2))
    print(f"Wrote {len(written_pages)} role pages + directory + index → {OUT}")
    for p in written_pages:
        print(" ", p.relative_to(OUT))


if __name__ == "__main__":
    build()
