#!/usr/bin/env python3
"""Build 10 Option A ATO test pages into serve/. Does not touch any git repo."""
from __future__ import annotations

import datetime as dt
import shutil
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent
GEN = Path("/tmp/ato-option-a/launch-option-a/ato-generator-v2-test")
SITE = Path("/tmp/ato-option-a/launch-option-a/site")
SERVE = ROOT / "serve"
TODAY = dt.date(2026, 11, 13)
CAPE = "demo-cape-town-flight-academy"

sys.path.insert(0, str(GEN))
import generator  # noqa: E402

PAGES = [
    {
        "n": "01",
        "title": "Demo Cape Town Flight Academy",
        "view": "Guest",
        "status": "Paid · official",
        "base": "FACT · FAGG",
        "href": f"/ato/{CAPE}/?preview-sun=night",
        "day": f"/ato/{CAPE}/?preview-sun=day",
        "tests": "Hero-first 4.3 glass score with sweep, gold tick, .official handle, Call / Email / Website, two bases with one expired certificate, own-school official reply (foreign reply hidden), Anonymous month-only, Edited tag, DFE and Founding badges, Licences / Ratings / Other with More, sign-in gate for the remaining reviews.",
    },
    {
        "n": "02",
        "title": "Demo Stellenbosch Aero Club",
        "view": "Guest",
        "status": "Verified · unpaid",
        "base": "FASH",
        "href": "/ato/demo-stellenbosch-aero-club/?preview-sun=night",
        "day": "/ato/demo-stellenbosch-aero-club/?preview-sun=day",
        "tests": "Under the 3-review threshold: score hidden, “2 of 3 reviews needed”, no gold tick, handle stays, one written review plus a stars-only card, DFE wins over Founding on the reviewer badge.",
    },
    {
        "n": "03",
        "title": "Demo Garden Route Flight Centre",
        "view": "Guest",
        "status": "Unclaimed",
        "base": "FAGG",
        "href": "/ato/demo-garden-route-flight-centre/?preview-sun=night",
        "day": "/ato/demo-garden-route-flight-centre/?preview-sun=day",
        "tests": "Empty unclaimed page: “Not claimed by the school yet”, claim step, disabled Call / Email / Website, no About, no courses, no reviews, “Sign in free to write the first one”.",
    },
    {
        "n": "04",
        "title": "Demo Lanseria Flying School",
        "view": "Guest",
        "status": "Lapsed",
        "base": "FALA",
        "href": "/ato/demo-lanseria-flying-school/?preview-sun=night",
        "day": "/ato/demo-lanseria-flying-school/?preview-sun=day",
        "tests": "Lapsed paid plan: .official handle remains, gold tick is off, expired certificate, old official reply still opens, score 4.2 still shows.",
    },
    {
        "n": "05",
        "title": "Demo Algoa Bay Aviation",
        "view": "Guest",
        "status": "Verified · flat score",
        "base": "FAPE · FAPA",
        "href": "/ato/demo-algoa-bay-aviation/?preview-sun=night",
        "day": "/ato/demo-algoa-bay-aviation/?preview-sun=day",
        "tests": "Score 3.6 with flat (not glass) stars, Rated 4.0+ = 1, two bases including Port Alfred → /ad/FAPA, no gold tick.",
    },
    {
        "n": "06",
        "title": "Demo Rand Airport Training",
        "view": "Guest",
        "status": "Gifted Premium",
        "base": "FAGM",
        "href": "/ato/demo-rand-airport-training/?preview-sun=night",
        "day": "/ato/demo-rand-airport-training/?preview-sun=day",
        "tests": "Gifted Premium gold tick, exact 4.0 shiny boundary, one stars-only review in the count, sign-in gate after the guest top 3.",
    },
    {
        "n": "07",
        "title": "Demo Grand Central Wings",
        "view": "Guest",
        "status": "Verified · shown off",
        "base": "FAGC",
        "href": "/ato/demo-grand-central-wings/?preview-sun=night",
        "day": "/ato/demo-grand-central-wings/?preview-sun=day",
        "tests": "Five written reviews but server shown flag is off (7-day aged-reviewer rule). Score stays hidden; written cards still show; wait copy explains the threshold.",
    },
    {
        "n": "08",
        "title": "Western Cape Advanced Multi-Engine and Instrument Training Organisation",
        "view": "Guest",
        "status": "Unclaimed · gaps",
        "base": "Kloofendal private strip",
        "href": "/ato/demo-wc-advanced-mei-training/?preview-sun=night",
        "day": "/ato/demo-wc-advanced-mei-training/?preview-sun=day",
        "tests": "Long name wrap, unclaimed claim step, rejected contacts (bad phone / email / website never become links), base without an ICAO code stays plain text, certificate expiry Unknown.",
    },
    {
        "n": "09",
        "title": "Cape Town Flight Academy — Pro member",
        "view": "Member · Pro",
        "status": "Paid · signed in",
        "base": "FACT · FAGG",
        "href": f"/member-pro/ato/{CAPE}/?view=member&theme=night&pal=black",
        "day": f"/member-pro/ato/{CAPE}/?view=member&theme=day&pal=white",
        "tests": "All 8 written reviews (no sign-in gate, stars-only ratings never shown), seven category averages, write-a-review form with Overall number on top of its stars, Pro anonymous toggle, votes / report / reply on written reviews only, Appearance sheet (Midnight, Amethyst, Pearl, Champagne).",
    },
    {
        "n": "10",
        "title": "Cape Town Flight Academy — Founding, anonymous",
        "view": "Member · Founding",
        "status": "Paid · anonymous on",
        "base": "FACT · FAGG",
        "href": f"/member-founding/ato/{CAPE}/?view=member&theme=night&pal=black",
        "day": f"/member-founding/ato/{CAPE}/?view=member&theme=day&pal=white",
        "tests": "Founding member who already posted stars only: their private “Your rating” slot (only they see it, no votes) with Add your written review, the form in add-text mode (stars locked, no quota used), posting as Anonymous, same written-only review list with votes and replies.",
    },
]


INJECT = """
<link rel="stylesheet" href="/preview/test-chrome.css">
<script src="/preview/test-interact.js" defer></script>
"""

GUEST_BOOT = """<script>/* preview pack: default Midnight unless a preview-sun is already set */
(function(){var q=new URLSearchParams(location.search);if(!q.get("preview-sun")&&!q.get("view")){q.set("preview-sun","night");history.replaceState(null,"",location.pathname+"?"+q.toString()+location.hash);}})();
</script>
"""

MEMBER_BOOT = """<script>/* preview pack: keep member theme controls on */
(function(){var q=new URLSearchParams(location.search);if(q.get("view")!=="member"){q.set("view","member");if(!q.get("theme"))q.set("theme","night");if(!q.get("pal"))q.set("pal","black");history.replaceState(null,"",location.pathname+"?"+q.toString()+location.hash);}})();
</script>
"""


def clean_serve():
    if SERVE.exists():
        shutil.rmtree(SERVE)
    SERVE.mkdir(parents=True)


def generate():
    data = ROOT / "data"
    generator.build(data, SERVE / "ato", "midnight", TODAY, scrub_courses=True, show_categories=False)
    cape = data / f"{CAPE}.json"
    tmp = ROOT / ".tmp-cape"
    if tmp.exists():
        shutil.rmtree(tmp)
    tmp.mkdir()
    shutil.copy2(cape, tmp / cape.name)
    generator.build(
        tmp, SERVE / "member-pro" / "ato", "midnight", TODAY, scrub_courses=True,
        viewer={"kind": "member", "plan": "pro", "name": "pilot.five", "anonymous_on": False,
                "form_ratings": {"org": 4, "flt": 5, "gnd": 4, "ins": 5, "val": 4, "avl": 3}},
    )
    generator.build(
        tmp, SERVE / "member-founding" / "ato", "midnight", TODAY, scrub_courses=True,
        viewer={"kind": "member", "plan": "founding", "name": "pilot.five", "anonymous_on": True,
                "form_text": "The dispatch desk held us on the ground this morning until the ceiling lifted. That is the school I want to fly with.",
                "form_title": "Weather limits were taken seriously",
                # MT t333u: this member already posted stars only. Only they see that rating, with no votes;
                # the form adds their written review to it (stars locked, no quota used).
                "own_rating": {"ratings": {"org": 5, "flt": 4, "gnd": 4, "ins": 5, "saf": 5, "val": 4, "avl": 4},
                               "published_at": "2026-11-09", "anonymous": True}},
    )
    shutil.rmtree(tmp)


def copy_assets():
    fonts_src = SITE / "fonts"
    fonts_dst = SERVE / "fonts"
    if fonts_dst.exists():
        shutil.rmtree(fonts_dst)
    shutil.copytree(fonts_src, fonts_dst)
    (SERVE / "ato-v6").mkdir(parents=True, exist_ok=True)
    shutil.copy2(SITE / "ato-v6" / "v6.css", SERVE / "ato-v6" / "v6.css")
    shutil.copy2(SITE / "favicon.ico", SERVE / "favicon.ico")
    shutil.copy2(SITE / "logo-mark.png", SERVE / "logo-mark.png")
    # topbar.css requests /fonts/bebas-neue.woff2 (palette labels on the member Appearance sheet).
    bebas_src = SITE / "fonts" / "app" / "bebas-neue-400.441b026d.woff2"
    if bebas_src.exists():
        shutil.copy2(bebas_src, fonts_dst / "bebas-neue.woff2")
    prev = SERVE / "preview"
    prev.mkdir(parents=True, exist_ok=True)
    shutil.copy2(ROOT / "preview" / "test-chrome.css", prev / "test-chrome.css")
    shutil.copy2(ROOT / "preview" / "test-interact.js", prev / "test-interact.js")
    # Shared CSS already lands under ato/_shared from the generator.


def polish_pages():
    guests = list((SERVE / "ato").glob("*/index.html"))
    members = list((SERVE / "member-pro").glob("ato/*/index.html")) + list((SERVE / "member-founding").glob("ato/*/index.html"))
    for p in guests:
        html = p.read_text()
        html = html.replace("<head>", "<head>\n" + GUEST_BOOT, 1)
        html = html.replace("</head>", INJECT + "</head>", 1)
        p.write_text(html)
    for p in members:
        html = p.read_text()
        html = html.replace("<head>", "<head>\n" + MEMBER_BOOT, 1)
        html = html.replace("</head>", INJECT + "</head>", 1)
        p.write_text(html)


def write_stub(path: Path, title: str, lead: str, back="/"):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(f"""<!doctype html>
<html lang="en" data-theme="night" data-pal="black">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<meta name="robots" content="noindex,nofollow">
<title>{title} · ATO test pack</title>
<link rel="icon" href="/favicon.ico" sizes="any">
<link rel="stylesheet" href="/fonts/wm-fonts.css">
<style>
  html,body{{margin:0;background:#000;color:#F5F5F7;font:400 16px/1.5 Satoshi,system-ui,sans-serif}}
  main{{max-width:560px;margin:0 auto;padding:48px 20px}}
  .mark{{display:inline-block;margin:0 0 14px;padding:4px 8px;border-radius:8px;background:rgba(255,255,255,.08);color:#F5F5F7;font:600 10px/1 "General Sans",sans-serif;letter-spacing:.08em;text-transform:uppercase}}
  h1{{margin:0 0 10px;font:600 clamp(28px,5vw,44px)/1.1 "Clash Display",Satoshi,sans-serif;letter-spacing:-.03em}}
  p{{margin:0 0 22px;color:rgba(245,245,247,.7);max-width:42ch}}
  a{{color:#9aa3ff;text-decoration:none}}
  a.back{{display:inline-flex;align-items:center;min-height:44px}}
</style>
</head>
<body>
<main>
  <span class="mark">Preview · demo only</span>
  <h1>{title}</h1>
  <p>{lead}</p>
  <a class="back" href="{back}">Back to the test pages</a>
</main>
</body>
</html>
""")


def write_stubs():
    write_stub(
        SERVE / "signup" / "index.html",
        "Sign in",
        "Preview only. The live sign-in and sign-up flow is not wired in this test pack. Use the index to open the guest or member school pages.",
    )
    write_stub(
        SERVE / "ato" / "claim" / "index.html",
        "Claim this page",
        "The school-claim route is not built yet. This placeholder exists so the “Claim this page” control on unclaimed schools has somewhere to go.",
    )
    idents = {
        "FACT": "Cape Town International",
        "FAGG": "George",
        "FASH": "Stellenbosch",
        "FALA": "Lanseria International",
        "FAPE": "Chief Dawid Stuurman International",
        "FAPA": "Port Alfred",
        "FAGM": "Rand",
        "FAGC": "Grand Central",
    }
    for code, name in idents.items():
        write_stub(
            SERVE / "ad" / code / "index.html",
            f"{code}",
            f"Preview stub for {name} ({code}). The live aerodrome page is not included in this ATO test pack.",
        )
    # Directory back target
    cards = "\n".join(
        f'<a href="{p["href"]}">{p["n"]} · {p["title"]}<small>{p["status"]} · {p["view"]}</small></a>'
        for p in PAGES
    )
    (SERVE / "c").mkdir(parents=True, exist_ok=True)
    (SERVE / "c" / "app.html").write_text(f"""<!doctype html>
<html lang="en" data-theme="night" data-pal="black">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<meta name="robots" content="noindex,nofollow">
<title>ATO directory · test pack</title>
<link rel="icon" href="/favicon.ico" sizes="any">
<link rel="stylesheet" href="/fonts/wm-fonts.css">
<style>
  html,body{{margin:0;background:#000;color:#F5F5F7;font:400 16px/1.5 Satoshi,system-ui,sans-serif}}
  main{{max-width:560px;margin:0 auto;padding:48px 20px 64px}}
  .mark{{display:inline-block;margin:0 0 14px;padding:4px 8px;border-radius:8px;background:rgba(255,255,255,.08);font:600 10px/1 "General Sans",sans-serif;letter-spacing:.08em;text-transform:uppercase}}
  h1{{margin:0 0 8px;font:600 36px/1.1 "Clash Display",Satoshi,sans-serif;letter-spacing:-.03em}}
  p{{margin:0 0 20px;color:rgba(245,245,247,.7)}}
  a{{display:block;margin:0 0 8px;padding:14px 16px;border-radius:16px;background:rgba(28,28,30,.7);box-shadow:inset 0 0 0 .5px rgba(255,255,255,.1);color:#F5F5F7;text-decoration:none;font:600 15px/1.3 Satoshi,sans-serif}}
  a small{{display:block;margin-top:4px;font:500 12px/1.3 Satoshi,sans-serif;color:rgba(245,245,247,.58)}}
</style>
</head>
<body>
<main>
  <span class="mark">Preview · demo only</span>
  <h1>ATO test pages</h1>
  <p>Stub for the directory back button. These ten pages use the locked Option A design.</p>
  {cards}
  <a href="/">Index of all ten</a>
</main>
</body>
</html>
""")


def write_index():
    items = []
    for p in PAGES:
        items.append(
            f"""<article class="card">
  <div class="meta"><span class="num">{p['n']}</span><span class="view">{p['view']}</span></div>
  <h2>{p['title']}</h2>
  <p class="who">{p['status']} · {p['base']}</p>
  <p class="tests">{p['tests']}</p>
  <div class="acts">
    <a class="primary" href="{p['href']}">Open in Midnight</a>
    <a href="{p['day']}">Pearl (day)</a>
  </div>
</article>"""
        )
    html = f"""<!doctype html>
<html lang="en" data-theme="night" data-pal="black">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<meta name="robots" content="noindex,nofollow">
<title>ATO test pages · Option A</title>
<link rel="icon" href="/favicon.ico" sizes="any">
<link rel="stylesheet" href="/fonts/wm-fonts.css">
<style>
  :root{{--bg:#000;--tx:#F5F5F7;--tx2:rgba(245,245,247,.62);--ln:rgba(255,255,255,.1);--gl:rgba(28,28,30,.72);--acc:#9aa3ff}}
  *{{box-sizing:border-box}}
  html,body{{margin:0;background:var(--bg);color:var(--tx);font:400 16px/1.55 Satoshi,system-ui,sans-serif}}
  body{{min-height:100dvh}}
  ::selection{{background:rgba(107,120,255,.35)}}
  :focus-visible{{outline:2px solid var(--acc);outline-offset:3px}}
  header,footer,main{{width:min(1080px,calc(100% - 40px));margin-left:auto;margin-right:auto}}
  header{{padding:36px 0 8px}}
  .mark{{display:inline-block;margin:0 0 14px;padding:4px 8px;border-radius:8px;background:rgba(255,255,255,.08);font:600 10px/1 "General Sans",sans-serif;letter-spacing:.08em;text-transform:uppercase;color:var(--tx)}}
  h1{{margin:0 0 10px;font:600 clamp(36px,6vw,64px)/1.05 "Clash Display",Satoshi,sans-serif;letter-spacing:-.03em}}
  .lede{{margin:0;max-width:58ch;color:var(--tx2)}}
  main{{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px;padding:28px 0 64px}}
  .card{{padding:20px 20px 18px;border-radius:20px;background:var(--gl);box-shadow:inset 0 1px 0 rgba(255,255,255,.08), inset 0 0 0 .5px var(--ln)}}
  .meta{{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:10px}}
  .num{{font:600 11px/1 "General Sans",sans-serif;letter-spacing:.08em;text-transform:uppercase;color:var(--tx2)}}
  .view{{font:600 11px/1 "General Sans",sans-serif;letter-spacing:.04em;color:var(--tx)}}
  h2{{margin:0 0 6px;font:600 22px/1.2 Satoshi,sans-serif;letter-spacing:-.02em}}
  .who{{margin:0 0 10px;font:500 13px/1.3 Satoshi,sans-serif;color:var(--tx2)}}
  .tests{{margin:0 0 16px;color:rgba(245,245,247,.78);font:400 14px/1.5 Satoshi,sans-serif}}
  .acts{{display:flex;flex-wrap:wrap;gap:8px}}
  .acts a{{display:inline-flex;align-items:center;min-height:40px;padding:0 14px;border-radius:999px;text-decoration:none;font:600 13px/1 Satoshi,sans-serif;color:var(--tx);box-shadow:inset 0 0 0 .5px var(--ln)}}
  .acts a.primary{{background:#F5F5F7;color:#111}}
  footer{{padding:0 0 48px;color:var(--tx2);font:400 13px/1.5 Satoshi,sans-serif}}
  @media (max-width:720px){{
    header,footer,main{{width:min(1080px,calc(100% - 32px))}}
    main{{grid-template-columns:1fr}}
  }}
</style>
</head>
<body>
<header>
  <span class="mark">Preview · demo data only</span>
  <h1>Ten ATO pages, Option A</h1>
  <p class="lede">Locked Hero-first design from 13 Nov 2026, generated from <code>locked/ato-option-a-13nov</code>. All schools, people and reviews are made up. Nothing here was published, and no git branch was changed. Midnight is the default; Pearl is the day theme.</p>
</header>
<main>
{''.join(items)}
</main>
<footer>
  Option 2 (the 12 Nov locked v2) is preserved in the same branches and is not used here. Theme confirmation is still outstanding before real school pages are generated.
</footer>
</body>
</html>
"""
    (SERVE / "index.html").write_text(html)


def main():
    clean_serve()
    generate()
    copy_assets()
    polish_pages()
    write_stubs()
    write_index()
    print("built", SERVE)
    for p in sorted((SERVE / "ato").glob("*/index.html")):
        print(" ", p.relative_to(SERVE))
    print("  member-pro/ato/" + CAPE + "/")
    print("  member-founding/ato/" + CAPE + "/")


if __name__ == "__main__":
    main()
