#!/usr/bin/env python3
"""PREVIEW ONLY (16 Nov 2026). Builds a local preview site:

  <out>/ato/43-air-school/index.html          the real guest page, exactly as generator.build() writes it
  <out>/ato/plans/<state>/index.html          Example Flight Academy (made-up school) + EXAMPLE reviews, per plan

The plan pages use the real templates and the generator's existing `viewer` mechanism (member view), then add a
preview ribbon and a "what this plan can do" card. Nothing here changes the default generated output, and nothing
is published. Reviews and reviewer names are made up (example data, not real people)."""
import copy, datetime as dt, json, os, shutil, sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
GEN = HERE.parents[1]
sys.path.insert(0, str(GEN))
import generator, rating, svg  # noqa: E402
from jinja2 import Environment, FileSystemLoader, select_autoescape, StrictUndefined  # noqa: E402
from markupsafe import Markup  # noqa: E402

TODAY = dt.date(2026, 11, 16)
# Real school for the default page only. Falls back to the repo's example school when the local copy is not there.
SCHOOL = Path(os.environ.get("ATO_PREVIEW_SCHOOL", "/workspace/ato_template_latest/data/two-schools/43-air-school.json"))
if not SCHOOL.exists():
    SCHOOL = GEN / "data" / "ato" / "example-air-school.json"
# Example reviews must never sit on a real school's data (REV-022 guard in generator.check), so the plan pages use
# the repo's made-up school, Example Flight Academy.
EXAMPLE_SCHOOL = GEN / "data" / "ato" / "example-flight-academy.json"
SITE = GEN.parent / "site"
OUT = Path(sys.argv[1] if len(sys.argv) > 1 else GEN / "preview-only" / "plans" / "out" / "site")
OLD = 1767225600000  # 1 Jan 2026: accounts older than 7 days, so their votes and ratings count

# ---- EXAMPLE reviews (fictional people). stars = the seven categories, 1-5; None = skipped. ----
def R(i, name, lic, badges, cats, up, pub, title, text, anon=False, edited=None):
    keys = ["org", "flt", "gnd", "ins", "saf", "val", "avl"]
    stars = {k: v for k, v in zip(keys, cats) if v is not None}
    overall = float(rating.overall_of(stars))
    rv = {"id": f"ex{i}", "author": {"name": name, "badges": badges, "licences": lic, "anonymous": anon},
          "stars": round(overall, 1), "up": up, "published_at": pub, "title": title, "text": text,
          "official_replies": [], "_stars": stars}
    if edited:
        rv.update(edited=True, edited_at=edited)
    return rv

FULL = [
    R(1, "lerato.k", ["CPL", "IR"], ["founding"], [5, 4, 5, 5, 5, 3, 4], 18, "2026-10-04",
      "Structured CPL, honest briefings",
      "Example review. Ground school followed a clear plan and every flight had a proper brief and debrief. Fuel surcharges were explained up front."),
    R(2, "", [], [], [4, 4, 5, 4, 5, 4, None], 12, "2026-09-18",
      "Safety first, even when it costs a slot",
      "Example review. Flights were cancelled when the wind picked up, which annoyed me then and makes sense now.", anon=True),
    R(3, "jaco.v", ["PPL"], [], [4, 3, 4, 5, 4, 4, 3], 9, "2026-10-21",
      "Great instructors, older fleet",
      "Example review. Instructors were patient. Two of the trainers showed their age, but snags were fixed quickly.", edited="2026-10-23"),
    R(4, "ayesha.p", ["PPL", "Night"], [], [5, 5, 4, 5, 5, 4, 5], 6, "2026-11-02",
      "Night rating done in three weeks",
      "Example review. Booking was easy and the night circuits were well organised."),
    R(5, "neo.m", ["Student"], [], [3, 4, 3, 4, 4, 3, 3], 3, "2026-11-09",
      "Good, but plan your weekends",
      "Example review. Weekend slots fill up a month ahead. Weekdays were fine."),
    R(6, "thabo.r", ["PPL"], [], [4, 4, None, 4, 5, 4, 4], 1, "2026-11-12", "", ""),   # stars only
]
FULL[0]["official_replies"] = [{"school": "exampleflight", "paid": True, "own": True, "when": "2026-10-06",
                                "text": "Example reply from the school. Thank you, we publish the fuel surcharge on every quote now."}]
LOW = [copy.deepcopy(FULL[2]), copy.deepcopy(FULL[4])]
LOW[0]["id"], LOW[1]["id"] = "ex-lo1", "ex-lo2"


def with_reviews(base, reviews):
    a = copy.deepcopy(base)
    a["_note"] = "EXAMPLE DATA. Reviews, names and numbers are made up for a preview. Not real Go Around reviews."
    ratings = [{"stars": r["_stars"], "status": "published", "text": r["text"], "account_created": "2026-01-01"} for r in reviews]
    a["rating"] = rating.summarise(ratings, TODAY, certificates=1)
    a["top_reviews"] = [{k: v for k, v in copy.deepcopy(r).items() if k != "_stars"} for r in reviews]
    a["visible_reviews"] = sum(1 for r in reviews if r["text"])
    return a


# ---- What each plan can see and do (newest documented rules; see RULES-USED.md) ----
def rows(plan, shown, count):
    score = (f"Shown: {count} reviews, at least 3 needed" if shown
             else f"Hidden: {count} of 3 reviews so far. Stars and bars appear at 3")
    if plan == "school":
        # DECISIONS-MASTER §4 / 16 Nov 13:12: owner and staff act as the ONE school voice; no star review from the school.
        return [("Read", "Every review on the page, plus the 7 category averages", "yes"),
                ("Write", "No. The school cannot star-review. Staff who fly use their own member account", "no"),
                ("Anonymous", "No. Every reply shows as the school (.official)", "no"),
                ("Vote", "Unlimited, as the school. 50 up-votes a day count toward rankings", "yes"),
                ("Reply", "Official replies on this page only, while Premium is paid", "yes"),
                ("Score", score, "yes" if shown else "no")]
    if plan == "guest":
        return [("Read", "Top 3 most-helpful written reviews, then a sign-in gate", "part"),
                ("Write", "No. Sign in free to write", "no"),
                ("Anonymous", "No", "no"),
                ("Vote", "No", "no"),
                ("Reply", "No", "no"),
                ("Score", score, "yes" if shown else "no")]
    if plan == "free":
        return [("Read", "Every review on the page, plus the 7 category averages", "yes"),
                ("Write", "5 reviews per rolling cycle · 3 left · resets 4 Dec", "part"),
                ("Anonymous", "No. Free posts with your name", "no"),
                ("Vote", "100 votes per cycle · 62 left", "part"),
                ("Reply", "Only in the thread of your own review", "part"),
                ("Score", score, "yes" if shown else "no")]
    anon = ("Yes. Chosen per thread, then locked for that thread" if plan == "pro"
            else "No. Trial posts with your name (Pro and Founding only)")
    used = {"trial": "20 reviews per rolling cycle · 19 left · trial ends 30 Nov",
            "pro": "20 reviews per rolling cycle · 17 left · resets 9 Dec"}[plan]
    return [("Read", "Every review on the page, plus the 7 category averages", "yes"),
            ("Write", used, "yes"),
            ("Anonymous", anon, "yes" if plan == "pro" else "no"),
            ("Vote", "Unlimited. 50 up-votes a day count toward rankings", "yes"),
            ("Reply", "In any review thread", "yes"),
            ("Score", score, "yes" if shown else "no")]


STATES = [
    # key, label, price, viewer, data, note
    ("guest", "Guest (not signed in)", "", None, "full",
     "Guests can read, never write, vote or reply. Google sees this view only."),
    ("free", "Free member", "R0", {"kind": "member", "plan": "free", "name": "kagiso.example", "quota_used": 2,
                                   "cycle_resets": "4 Dec", "form_ratings": {"org": 4, "ins": 5, "val": 3}}, "full",
     "Free = a signed-in member after the trial ends. Deleting a review does not give the slot back."),
    ("trial", "Trial (14 days of Pro, no card)", "R0 · once", {"kind": "member", "plan": "trial", "name": "kagiso.example",
                                                              "quota_used": 1, "cycle_resets": "30 Nov (trial ends)"}, "full",
     "Trial has every Pro tool except anonymous posting. When it ends the account becomes Free."),
    ("pro", "Pro / Founding Member", "R399 · Founding R299", {"kind": "member", "plan": "pro", "name": "kagiso.example",
                                                              "quota_used": 3, "cycle_resets": "9 Dec", "anonymous_on": True,
                                                              "form_ratings": {"org": 5, "flt": 4, "gnd": 5, "ins": 5, "saf": 5, "val": 4},
                                                              "form_text": "Example text. Clear briefings and a fair quote."}, "full",
     "Anonymous hides the name and badges from the public only. The account stays known to Go Around."),
    ("owner", "School owner / staff (own page)", "", {"kind": "member", "plan": "pro", "name": "exampleflight",
                                                       "_school": True}, "full",
     "PREVIEW ONLY, not designed yet (MT designs the ATO dashboard later). Staff are added by username and act as the "
     "school. The generator has no school view yet; this page shows the member view with posting turned off."),
    ("low-guest", "Guest · school with 2 reviews", "", None, "low",
     "Under 3 reviews: no score, no stars on cards, no 5-to-1 bars. Written reviews still show."),
    ("low-free", "Free member · school with 2 reviews", "R0", {"kind": "member", "plan": "free", "name": "kagiso.example",
                                                               "quota_used": 2, "cycle_resets": "4 Dec"}, "low",
     "Members see the same 'not enough reviews yet' state, and can write the third review."),
]


def main():
    base = json.loads(SCHOOL.read_text())
    ex_base = json.loads(EXAMPLE_SCHOOL.read_text())
    if OUT.exists():
        shutil.rmtree(OUT)
    ato_out = OUT / "ato"
    # 1) The real default guest page (no preview pieces at all).
    data = OUT.parent / "_data_default"
    shutil.rmtree(data, ignore_errors=True); data.mkdir(parents=True)
    (data / "43-air-school.json").write_text(json.dumps(base))
    generator.build(data, ato_out, "midnight", TODAY)
    # Shared site files the page links: /ato-v6/v6.css, /fonts, favicon.
    (OUT / "ato-v6").mkdir(parents=True, exist_ok=True)
    shutil.copy2(SITE / "ato-v6" / "v6.css", OUT / "ato-v6" / "v6.css")
    shutil.copytree(SITE / "fonts", OUT / "fonts", dirs_exist_ok=True)
    for f in ("favicon.ico", "logo-mark.png"):
        if (SITE / f).exists():
            shutil.copy2(SITE / f, OUT / f)
    shutil.copy2(HERE / "plans.css", ato_out / "_shared" / "plans-preview.css")

    # 2) Plan pages.
    env = Environment(loader=FileSystemLoader([GEN / "template", HERE]), autoescape=select_autoescape(["html", "j2"]),
                      undefined=StrictUndefined, trim_blocks=True, lstrip_blocks=True)
    env.globals.update(svg=svg, nice_date=generator.nice_date, nice_month=generator.nice_month)
    page_t, card_t = env.get_template("ato.html.j2"), env.get_template("plan_card.j2")
    tokens = Markup(generator.all_theme_tokens())
    for key, label, price, viewer, which, note in STATES:
        ato = with_reviews(ex_base, FULL if which == "full" else LOW)
        generator.check(ato)
        svg.IDS.n = 0
        m = generator.page_model(copy.deepcopy(ato), TODAY, viewer=copy.deepcopy(viewer) if viewer else None)
        if viewer and viewer.get("_school"):
            # Same shape the backend sends a school voice (getSchoolView: review false, anonymous false).
            m["can"].update(review=False, anonymous=False, reply="anywhere", plan="school")
        html = page_t.render(**m, theme="midnight", data_theme="night", data_pal="black", tokens=tokens, guest_theme_choice=False)
        plan = ("school" if viewer.get("_school") else viewer["plan"]) if viewer else "guest"
        st = {"key": key, "label": label, "price": price, "note": note,
              "rows": rows(plan, m["rating_shown"], ato["rating"]["count"])}
        card = card_t.render(st=st)
        ribbon = ('<div class="pv-ribbon" role="note"><b>Example data</b><span>Preview only. Reviews and names are made up, '
                  'not real people. Viewing as: ' + label + '.</span></div>')
        if plan == "guest":
            card += ('<div class="pv-guestform"><h3>Write a review</h3><p>Sign in free to rate this ATO on seven categories '
                     'and write about your training.</p><a class="ob-pill primary" href="#">Sign in free</a></div>')
        head_rev = '<div class="ob-hrow"><h2 class="ob-h">Reviews</h2><p class="ob-hs">Most helpful</p></div>'
        assert head_rev in html and '<div id="ob-page">' in html
        html = html.replace(head_rev, head_rev + "\n" + card, 1)
        html = html.replace('<div id="ob-page">', '<div id="ob-page">\n' + ribbon, 1)
        html = html.replace("</head>", '<link rel="stylesheet" href="/ato/_shared/plans-preview.css?v=20261116a">\n'
                                       '<meta name="robots" content="noindex,nofollow">\n</head>', 1)
        html = html.replace("<title>", "<title>[Preview] ", 1)
        dest = ato_out / "plans" / key / "index.html"
        dest.parent.mkdir(parents=True, exist_ok=True)
        dest.write_text(html)
        print("wrote", dest, "| member" if viewer else "| guest", "| shown" if m["rating_shown"] else "| hidden",
              "| cards", len(m["top"]), "| more", m["more"])


if __name__ == "__main__":
    main()
