#!/usr/bin/env python3
"""Writes one prompt file per starter template, plus the list in README.md. Each prompt can be pasted on its own into a
new Bash.tv space. The shared rules live in COMMON below, so they stay the same in every prompt.

  python3 template-prompts/build-prompts.py          write
  python3 template-prompts/build-prompts.py --check  fail if a prompt file or the list is out of date
"""
import os
import re
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
SITE = "https://bash.l00.pw"

# slug, name, technology, docs size, uses the GPU, components, what to build, must haves
T = [
    ("vanilla-html5", "Vanilla HTML5 Game", "HTML, CSS and JavaScript ES modules, no build step", "full", False,
     ["input-manager", "touch-controller", "scene-manager", "save-manager", "settings-manager", "audio-manager", "responsive-layout", "timer-manager", "error-handler", "event-bus"],
     "A top-down sample: move a square around a room, collect 10 dots before a 60 second timer runs out, best time saved.",
     ["Files: `index.html`, `style.css`, `src/main.js`, `src/config.js`, `src/scenes/` (title, play, pause, gameover), `src/components/`.",
      "No bundler, no npm packages. It must run from any static file server.",
      "Settings screen with music and effects volume and screen shake, saved with the Settings Manager."]),
    ("typescript", "TypeScript Game", "TypeScript with Vite (strict mode), built to `dist/`", "full", False,
     ["input-manager", "touch-controller", "scene-manager", "save-manager", "settings-manager", "audio-manager", "responsive-layout", "timer-manager", "error-handler", "event-bus"],
     "The same top-down collect sample as the vanilla template, written in TypeScript.",
     ["`tsconfig.json` with `strict: true`. The toolkit components are JavaScript: add `allowJs` and a `src/components/components.d.ts` with types for the functions you use.",
      "Scripts: `npm run dev`, `npm run build` (type check, then build), `npm test` (Vitest or node --test on the built game logic).",
      "Pin exact versions in `package.json` and commit `package-lock.json`.",
      "The quality gates run against the built `dist/` folder."]),
    ("single-html-file", "Single HTML File Game", "One self-contained `index.html`: HTML, CSS and JavaScript inline", "lite", False,
     ["input-manager", "touch-controller", "save-manager", "audio-manager", "responsive-layout"],
     "A one-screen dodge game: move left and right to avoid falling blocks, score is time survived, best score saved.",
     ["Everything in one `index.html`, including the components, pasted inside one `<script type=\"module\">` with a comment above each one: `// component: input-manager (toolkit)`.",
      "No other files are needed to play: it must work from a web server and when the file is opened directly from disk.",
      "Keep the file under 60 KB."]),
    ("canvas-2d", "Canvas 2D Game", "Canvas 2D API with plain JavaScript modules", "full", False,
     ["input-manager", "touch-controller", "scene-manager", "camera-controller", "particle-engine", "animation-manager", "collision-engine", "object-pool", "performance-monitor", "responsive-layout"],
     "A small scrolling arena bigger than the screen: the camera follows the player, enemies wander, touching one gives a hit with particles and shake.",
     ["A fixed-step update (60 steps a second) with drawing every animation frame, so speed is the same on 60 Hz and 120 Hz screens.",
      "Sharp on high-density screens (device pixel ratio, capped at 2).",
      "Layers drawn in order: background, world, effects, HUD. Skip drawing things outside `camera.view`.",
      "Sprite animation frames drawn with shapes in code, through the Animation Manager, so real sprite sheets drop in later."]),
    ("phaser", "Phaser Game", "Phaser 3 (current stable release from npm) with Vite", "full", True,
     ["settings-manager", "save-manager", "achievement-manager", "accessibility-manager", "localization-manager", "platform-adapter", "error-handler"],
     "A short platformer level: run, jump, collect 5 coins, reach the flag. Built with Phaser scenes and Arcade Physics.",
     ["Use Phaser's own scenes, input, loader, tweens and Scale Manager (FIT, centred). Use the toolkit components only for what Phaser doesn't have.",
      "On-screen touch buttons on phones (Phaser input), keyboard and gamepad on desktop.",
      "Pin the exact Phaser version in `package.json`.",
      "Phaser uses WebGL: don't load it in the sandbox browser. Check it in the viewer's preview or with `check_gpu_render`, and record those checks in `.project/evidence.json`."]),
    ("pixijs", "PixiJS Game", "PixiJS v8 with Vite", "full", True,
     ["input-manager", "touch-controller", "scene-manager", "animation-manager", "camera-controller", "collision-engine", "object-pool", "responsive-layout", "performance-monitor"],
     "A top-down collect sample drawn with Pixi Graphics and Containers: one container per scene, a world container moved by the camera.",
     ["Scenes show and hide Pixi containers in `enter()` and `exit()`.",
      "Use `computeLayout` from the Responsive Layout Manager with `app.renderer.resize()`; draw at the game's design size.",
      "Tweens from the Animation Manager on Pixi objects (position, alpha, scale).",
      "Pin the exact PixiJS version. PixiJS uses WebGL or WebGPU: check it in the viewer's preview or with `check_gpu_render`, not the sandbox browser."]),
    ("threejs", "Three.js Game", "Three.js with Vite", "full", True,
     ["input-manager", "touch-controller", "audio-manager", "settings-manager", "timer-manager", "performance-monitor", "error-handler"],
     "A small 3D collect sample: a capsule player on a flat arena with a few boxes, a follow camera, 8 glowing spheres to collect.",
     ["Simple shapes and materials made in code (no model files).",
      "Renderer pixel ratio capped at 2, resize on window and orientation changes, `renderer.setAnimationLoop`.",
      "Touch: left thumb stick to move, drag on the right half to turn the camera.",
      "Handle `webglcontextlost` and `webglcontextrestored`.",
      "Register `window.bash.preview.onCapture` so the Bash preview can capture the canvas (see the bash-js-sdk skill).",
      "Check it in the viewer's preview or with `check_gpu_render`, not the sandbox browser."]),
    ("webgl", "WebGL Game", "Raw WebGL 2 with a small renderer written for the template", "full", True,
     ["input-manager", "touch-controller", "scene-manager", "camera-controller", "collision-engine", "object-pool", "responsive-layout", "performance-monitor", "error-handler"],
     "A 2D sample drawn with WebGL: a batched sprite renderer (coloured quads) showing a player and 500 moving particles.",
     ["`src/gl/` with a shader helper (clear compile and link errors), a quad batch renderer and an orthographic camera.",
      "If WebGL 2 isn't available, show a plain message explaining that, instead of a blank page.",
      "Handle context loss and restore, rebuilding the buffers and shaders.",
      "Register `window.bash.preview.onCapture` (see the bash-js-sdk skill). Check it in the viewer's preview or with `check_gpu_render`."]),
    ("webgpu", "WebGPU Game", "WebGPU with a WebGL 2 fallback", "full", True,
     ["input-manager", "touch-controller", "scene-manager", "camera-controller", "responsive-layout", "performance-monitor", "error-handler"],
     "The same 2D sample as the WebGL template (player and many moving quads), rendered with WebGPU.",
     ["Use WebGPU when `navigator.gpu` and an adapter are available; otherwise fall back to a WebGL 2 renderer with the same interface. Show which one is running in the debug overlay.",
      "Handle `device.lost` by rebuilding the renderer.",
      "Keep the renderer interface small (begin, draw quads, end) so game code doesn't care which backend runs.",
      "Register `window.bash.preview.onCapture`. Check both backends in the viewer's preview or with `check_gpu_render`."]),
    ("mobile-first", "Mobile-First Game", "Canvas 2D, designed for one-thumb phone play first", "full", False,
     ["input-manager", "touch-controller", "scene-manager", "save-manager", "settings-manager", "audio-manager", "responsive-layout", "accessibility-manager", "notification-manager"],
     "A one-thumb sample: drag anywhere to steer a ball through gaps, tap to boost.",
     ["Designed for a 390 x 844 phone first, then made to work on tablets and desktops (mouse drag and arrow keys).",
      "Every button at least 44 x 44 CSS pixels, inside thumb reach, clear of notches (safe areas).",
      "Works in portrait and landscape. Pauses when the tab is hidden or the phone rotates mid-game.",
      "Vibration only if `navigator.vibrate` exists and the player hasn't turned it off; never required.",
      "`touch-action: none` on the canvas, no page scrolling or zooming during play."]),
    ("portrait", "Portrait Game", "Canvas 2D with a fixed portrait layout (9:16)", "full", False,
     ["input-manager", "touch-controller", "scene-manager", "save-manager", "responsive-layout", "timer-manager", "particle-engine"],
     "A vertical dodge sample: blocks fall from the top; move left and right; speed rises over time.",
     ["Design size 360 x 640, Responsive Layout Manager in `expand` mode so taller phones see more, never less.",
      "On desktop and in landscape, the game sits in a centred column with a plain background around it; it never stretches.",
      "Controls: drag or tap left and right halves on phones, arrow keys and A / D on desktop."]),
    ("landscape", "Landscape Game", "Canvas 2D with a fixed landscape layout (16:9)", "full", False,
     ["input-manager", "touch-controller", "scene-manager", "save-manager", "responsive-layout", "camera-controller", "collision-engine"],
     "A side-scrolling sample: run right, jump over gaps, reach the end of a short level.",
     ["Design size 640 x 360, `fit` mode with bars when the shape differs.",
      "On a phone held upright, pause and show a plain \"Turn your phone sideways\" message; resume when it's turned.",
      "Touch: stick on the left, jump button on the right. Keyboard and gamepad on desktop."]),
    ("multiplayer", "Multiplayer Game", "Node.js WebSocket server (server decides what happens) and a Canvas 2D client", "full", False,
     ["network-manager", "input-manager", "touch-controller", "scene-manager", "responsive-layout", "error-handler"],
     "Rooms with 4-letter codes; up to 4 players move dots around an arena and tag each other. The server runs the game; clients send inputs and draw what the server sends.",
     ["One Node server serves the client files and the WebSocket on the same port, so it works behind the Bash preview. Use the `ws` package, pinned.",
      "The server checks every message (type, size, rate) and never trusts the client. Snapshots 20 times a second; clients smooth between them.",
      "Reconnect after a dropped connection keeps the player's place for 30 seconds.",
      "Tests for the server's game rules and message checks with `node --test`, plus a test that starts the server and connects two clients.",
      "Start the server with tmux, open the preview, and play it with two browser tabs."]),
    ("local-multiplayer", "Local Multiplayer Game", "Canvas 2D, 2 to 4 players on one device", "full", False,
     ["input-manager", "touch-controller", "scene-manager", "responsive-layout", "rng"],
     "A join screen (press a button to join), then a short round where each player pushes a ball into the others' goals.",
     ["Keyboard split: player 1 WASD and Space, player 2 arrows and Enter.",
      "Each gamepad is its own player: give each player their own Input Manager with `gamepads: () => [navigator.getGamepads()[i]]`.",
      "On tablets, each player gets one corner of the screen with their own touch stick (one Touch Controller per corner area).",
      "Players can join and leave on the join screen; colours and shapes tell players apart (not colour alone)."]),
    ("ps1-horror", "PS1 Horror Game", "Three.js with a low-resolution retro look", "full", True,
     ["input-manager", "touch-controller", "audio-manager", "settings-manager", "accessibility-manager", "timer-manager", "error-handler"],
     "A short dark corridor walk with a flashlight; find a key and reach the door. Rooms built from boxes and planes in code.",
     ["Render to a 320 x 240 target and scale it up with nearest-neighbour filtering; wobbly vertices (snap positions in the vertex shader); thick fog; low-resolution textures made from code patterns only.",
      "Settings for brightness, a \"no jump scares\" option, no flashing, and reduced motion, all on by default where the device asks for them.",
      "Touch: stick to move, drag to look, a flashlight button.",
      "Register `window.bash.preview.onCapture`. Check it in the viewer's preview or with `check_gpu_render`."]),
    ("pixel-art-rpg", "Pixel Art RPG", "Canvas 2D, tile-based, pixel-perfect scaling", "full", False,
     ["input-manager", "touch-controller", "scene-manager", "save-manager", "camera-controller", "collision-engine", "animation-manager", "state-machine", "notification-manager", "localization-manager"],
     "A small village map: walk on a tile grid, talk to 2 characters, pick up an item, open a chest that needs it. Save and load from the pause menu.",
     ["Design size 320 x 180, Responsive Layout Manager with `pixelArt: true` (whole-number scaling, no smoothing).",
      "Tiles and characters drawn as simple coloured pixel shapes in code, from a small palette, so a real tileset drops in later. Map data in `src/data/map.json`.",
      "Dialogue boxes with text in `src/data/dialogue.json` through the Localization Manager.",
      "Grid movement with the Collision Engine's tile collision; touch stick snaps to 4 directions."]),
    ("arcade-shooter", "Arcade Shooter", "Canvas 2D", "full", False,
     ["input-manager", "touch-controller", "scene-manager", "save-manager", "object-pool", "collision-engine", "particle-engine", "camera-controller", "timer-manager", "rng", "accessibility-manager"],
     "A vertical shooter sample: 3 waves of enemies with 2 movement patterns, one power-up, a high score.",
     ["Bullets, enemies and effects come from Object Pools; collisions use layers (player shots hit enemies, enemy shots hit the player).",
      "Waves defined as data in `src/data/waves.json`; seeded randomness so a run can be replayed.",
      "Screen shake and flashes follow the accessibility settings.",
      "Touch: drag to move, firing is automatic on phones; keyboard and gamepad on desktop."]),
    ("tower-defense", "Tower Defense", "Canvas 2D", "full", False,
     ["input-manager", "touch-controller", "scene-manager", "save-manager", "timer-manager", "object-pool", "collision-engine", "state-machine", "rng", "notification-manager"],
     "One map with a fixed path, 5 waves, 2 tower types with one upgrade each, sell for half price.",
     ["Targeting choice per tower: first, strongest, nearest.",
      "Place towers by tapping a grid cell (shows range first, tap again to confirm) so it works on phones without hover.",
      "Waves, towers and enemies defined as data in `src/data/`.",
      "Speed buttons (1x, 2x) using the Timer Manager's time scale; pause stops everything."]),
    ("card-game", "Card Game", "HTML and CSS for the cards (DOM), JavaScript modules", "full", False,
     ["input-manager", "scene-manager", "save-manager", "state-machine", "rng", "animation-manager", "localization-manager", "accessibility-manager"],
     "A simple two-player duel against a basic computer player: draw, play cards with costs, attack, first to 0 health loses. 12 card types.",
     ["Cards defined as data in `src/data/cards.json`; turn phases run by the State Machine.",
      "Play a card by dragging it or by tapping it and then tapping the target, so it works with mouse, touch and keyboard (Tab and Enter).",
      "Cards are buttons with readable names for screen readers.",
      "Seeded shuffles so a game can be replayed; the save keeps a game in progress."]),
    ("visual-novel", "Visual Novel", "HTML and CSS (DOM), JavaScript modules", "full", False,
     ["input-manager", "scene-manager", "save-manager", "settings-manager", "localization-manager", "accessibility-manager", "audio-manager"],
     "A short sample story: about 30 lines, 2 choices that change one later line, 2 endings.",
     ["Script in a plain text format in `src/story/` (one line per line of dialogue, simple markers for choices and flags), read by a small parser with tests.",
      "Dialogue box with text speed, auto and skip, a backlog of past lines, and 3 save slots.",
      "Characters shown as name tags with colours; backgrounds as CSS colours or gradients, so real art drops in later.",
      "Click, tap, Space or Enter to continue; choices work with keyboard and touch."]),
    ("game-jam-starter", "Game Jam Starter", "Plain JavaScript modules, as little setup as possible", "lite", False,
     ["input-manager", "touch-controller", "scene-manager", "save-manager", "audio-manager", "responsive-layout"],
     "Title, play and game over screens with a placeholder \"press to score\" game in the middle, ready to replace.",
     ["Fewer than 12 files. All tuning in `src/config.js`. The play scene is one file that's clearly the part to replace.",
      "A one-line export to an itch.io zip: `python3 scripts/make-zip.py` writes `builds/game.zip` with `index.html` at the top.",
      "Lite project docs only."]),
    ("pwa", "PWA Game", "HTML5 game that can be installed and played offline", "full", False,
     ["input-manager", "touch-controller", "scene-manager", "save-manager", "settings-manager", "responsive-layout", "error-handler", "notification-manager"],
     "The top-down collect sample from the vanilla template, made installable and playable offline.",
     ["`manifest.webmanifest` with name, colours and display `standalone` or `fullscreen`. Icons: one plain placeholder made in code (a solid colour square with the game's first letter, as SVG and 192 / 512 PNG), clearly marked for replacing.",
      "Service worker with a versioned cache of the game files; a new version shows a \"New version, tap to update\" message instead of changing mid-game.",
      "Register the service worker only on the game's own site, never inside the Bash preview or another site's iframe.",
      "Saves keep working offline. Test offline play with the sandbox browser set to offline."]),
]

COMMON = """\
## Rules for every template

- Read the `apps-and-games` and `bash-js-sdk` skills first. Load Bash.js in `index.html`. Don't use alert, confirm or prompt.
- This is a **template**: a small, clean, working starting point for new games, not a finished game. Build only what this prompt asks for. No extra modes, levels, pages or demos.
- The sample gameplay is short and clearly marked as the part to replace. Keep tunable numbers in `src/config.js`.
- No generated art or music. Draw shapes in code. Leave sound wired up through the Audio Manager with no sound files, and say in the README where to add them.
- Keyboard, mouse and touch all work (and gamepad where the Input Manager is used). The game pauses when the tab is hidden.
- Title, play, pause and game over screens, and restarting without reloading the page.
- Set the test hook: `window.__game = {{ state, pause, resume, restart, gameOver }}` (details in the quality gates guide).
- Wrap the game loop with the Error Handler's `guard()` so one error doesn't freeze the game.

## The toolkit

Download the toolkit once and use its parts instead of writing them again:

```bash
curl -fsSL {site}/toolkit/toolkit.zip -o /tmp/toolkit.zip
python3 -c "import zipfile; zipfile.ZipFile('/tmp/toolkit.zip').extractall('/tmp')"
```

- Components: copy these from `/tmp/toolkit/components/<name>/<name>.js` into `src/components/` unchanged:
  {components}.
  Each one's README (`/tmp/toolkit/components/<name>/README.md`, or {site}/toolkit/components/) shows how to use it.
  If a component needs a change, don't edit it in place; note it in the template's `docs/TECHNICAL_DEBT.md`.
- Project docs: `python3 /tmp/toolkit/project-docs/new-project.py . --name "{name}"{lite_flag}`, then fill every file in for this template. No template text may be left.
- Quality gates: `python3 scripts/run-gates.py .{gates_flags}` (guide: {site}/toolkit/quality-gates/).

## Proving it works

- Run the quality gates and keep the report ({report}). Each gate must be PASS, FAIL, NOT TESTED or NOT APPLICABLE, with evidence. Never mark something PASS because the code looks right.
- Fix every FAIL. Anything still NOT TESTED needs a reason in the report.
- {gpu_rule}
- Check the phone layout with the viewer's preview at phone size, and restore their setting afterwards.

## README for people using the template

The template's `README.md` must say: what's included, how to run it, the controls, which files to change first to make a new game from it, which toolkit components it uses, and the latest quality gates summary.

## Done when

- [ ] The sample plays from title to game over and back, on desktop and on a phone.
- [ ] All the must-haves above are in.
- [ ] Project docs filled in, with no template text left.
- [ ] Quality gates: no FAIL, and every NOT TESTED explained.
- [ ] Committed with a clear message.

When it's done, tell me in plain words what the template includes, what to change first to start a new game, and anything that is still NOT TESTED.
"""


def prompt(slug, name, tech, docs, gpu, comps, sample, musts):
    lite = docs == "lite"
    comps = list(comps) + [c for c in ("audio-manager", "error-handler") if c not in comps]   # every template wires these up
    gates_flags = (" --lite" if lite else "") + (" --root dist --build \"npm run build\"" if "Vite" in tech else "")
    gpu_rule = ("This template uses the GPU. Never load it in the sandbox browser. Check it in the viewer's preview (`look_at_preview`) or with `check_gpu_render`, "
                "and record what you checked by hand in the evidence file " + ("(`evidence.json`)." if lite else "(`.project/evidence.json`).")) if gpu else \
        "Test in the sandbox browser with Playwright at phone and desktop sizes; the gates already do most of this."
    body = f"""# Template prompt: {name}

Paste everything below into a new Bash.tv space.

---

Make a starter template: **{name}**.

- **Technology:** {tech}
- **Sample gameplay:** {sample}
- **Project docs:** {"lite (game jam size)" if lite else "full"}

## Must haves

""" + "\n".join(f"- {m}" for m in musts) + "\n\n" + COMMON.format(
        site=SITE, name=f"{name} template", components=", ".join(f"`{c}`" for c in comps), lite_flag=" --lite" if lite else "",
        gates_flags=gates_flags, report="`VALIDATION.md`" if lite else "`.project/VALIDATION_REPORT.md`", gpu_rule=gpu_rule)
    return body


def main():
    check = "--check" in sys.argv
    problems = []
    comps_dir = os.path.join(os.path.dirname(HERE), "toolkit", "components")
    rows = []
    for i, t in enumerate(T, 1):
        slug, name, tech, docs, gpu, comps = t[:6]
        for c in comps:
            if not os.path.isfile(os.path.join(comps_dir, c, c + ".js")):
                problems.append(f"{slug}: no component called {c}")
        fn = f"{i:02d}-{slug}.md"
        text = prompt(*t)
        path = os.path.join(HERE, fn)
        if check:
            if not os.path.isfile(path) or open(path).read() != text:
                problems.append(f"{fn} is out of date")
        else:
            open(path, "w").write(text)
        rows.append(f"| {i} | [{name}]({fn}) | {tech} | {'lite' if docs == 'lite' else 'full'} | {'yes' if gpu else 'no'} |")
    for f in os.listdir(HERE):
        if re.match(r"\d\d-.*\.md$", f) and f not in {f"{i:02d}-{t[0]}.md" for i, t in enumerate(T, 1)}:
            problems.append(f"{f} isn't in the list any more")
    readme = os.path.join(HERE, "README.md")
    cur = open(readme).read()
    table = "<!-- list:start -->\n\n| # | Template | Technology | Docs | Needs a GPU browser to check |\n|---|---|---|---|---|\n" + "\n".join(rows) + "\n\n<!-- list:end -->"
    new = re.sub(r"<!-- list:start -->[\s\S]*?<!-- list:end -->", table, cur)
    if check and new != cur:
        problems.append("README.md list is out of date")
    if not check:
        open(readme, "w").write(new)
    print(f"{len(T)} template prompts {'checked' if check else 'written'}, {len(problems)} problem(s)")
    for p in problems:
        print("  " + p)
    sys.exit(1 if problems else 0)


main()
