---
name: creator-screenshots-ad
description: "Your creator ad machine. Drop in a product link and Claude researches it, writes the script and casts an AI creator, then edits a 45-second ad: the creator cut out over the screenshots that prove every claim, with a title and captions. One finished video, ready to post."
---

# Creator screenshots ad

**What it makes:** a 9:16, ~45 s ad. A creator films a fast, low-angle selfie, spilling something she just found out. In the edit she's cut out (greenscreen look), placed small-to-medium over full-screen phone screenshots that change every 3–4 s (one screen per thought), moved to a new size and position on every cut, and on every third shot dragged around as if by a thumb on a phone. Opening: a hook title in white text on a black box, with 1–2 emojis (it reads over the white screens most ads open on). Captions: plain white words, 2–3 per cue. No music. The screens are the *research*: the viewer learns a real, specific fact; the product arrives late (50–70% in) as the easy answer.

**Split of work:** the Arcads MCP does every generation (video, images, background removal, title, captions). Claude does research, writing, Playwright captures, HTML screen builds and the edit (ffmpeg via `csa.py`).

## 0. Setup (first run)
1. The toolbox `csa.py` sits next to this file. If it's missing (e.g. this skill was shared as one .md), write the code block in **Appendix A** to `csa.py` beside this SKILL.md, byte for byte.
2. `python csa.py deps`. It needs: ffmpeg with libvpx-vp9 (Windows `winget install Gyan.FFmpeg`, Mac `brew install ffmpeg`), Python 3.10+, `pip install numpy pillow faster-whisper playwright`, Google Chrome (or `playwright install chromium` and pass `--browser chromium`). Tell the user in one line before installing anything.
3. The Arcads connector must be connected. Its tools are often deferred: load them with ToolSearch (`arcads_get_upload_url`, `arcads_generate_video_seedance_25`, `arcads_generate_image`, `arcads_remove_background`, `arcads_get_asset`, `arcads_add_text_overlay`, `arcads_add_subtitles`, `arcads_list_products`, `arcads_create_project`).
4. Job folder in the current directory: `<Brand> ad/` with `assets/ narrator/ screens/ edit/ NOTES.md`.

## How to talk to the user
- The user sees only: **(1) the intake question → (2) the script picker → (3) the cost quote and one "go" → (4) the finished video.** Plus a real blocker. Nothing in between: no previews, clip approvals, progress reports, QC notes, method talk or file paths.
- Short messages. The user's script edits are final: never question, fact-check or caveat a line they wrote or changed.
- Final message: the video plus at most one line; list known issues only if they'd spot them on first watch.

## 1. Intake (one message)
Ask for the product (link and/or name; a product image if they have one) and, in the same message, three optional things (AskUserQuestion where available):
- "Do you have a script, or should I write 3 options?"
- "Do you have a character image (a photo of the creator), or should I create one?"
- "Any screenshots you'd like in the background? Drop them in — optional."
If they give a photo of a real person, ask once: "Is this you, or someone who's agreed to appear?" A yes is enough. Never use a real person on our own initiative.
Default length 45 s (two narrator clips). Accept any length the user asks for (one clip up to 30 s).

## 2. Research (silent)
- Capture the product page: `python csa.py capture "<url>" "<job>/assets/page"` (Playwright only; see the 429 rule in §6).
- Search the web for the product facts and for the *lesson*: a real, surprising, checkable fact about the viewer's world that the product answers (a study, a number, a name for something, how something is made).
- Write `<job>/facts.md`: what the product is, price/offer, proof the brand states, **what we must not claim** (health effects, guarantees, competitor names), and each lesson fact with its source URL.

## 3. Script
**If the user gave a script:** use it word for word. Split it for the clips (below) and move on.

**Otherwise write 3 options, each in a different frame:**

| Frame | Hook skeleton | Body |
| --- | --- | --- |
| Myth vs fact | "Everyone thinks [belief]. The research says [twist]." | 2–3 beliefs, each corrected by a source; the last leads to the product |
| There's a name for this | "There's an actual name for [thing everyone does]." | the name → the study → the surprising number → what to do → product |
| Rabbit hole | "I went down a rabbit hole on [topic] and it's mad." | 3 escalating facts, each with a source, then what it means for you |
| Read the label | "Flip over your [product type]. That first ingredient…" | an unbranded bad label, look each thing up; then ours |
| Starting again | "If I had to [goal] from zero, knowing what I know now…" | 3–4 moves, each backed by something specific learned |

Rules for every option:
- **Every line teaches.** A specific fact, number, name or mechanism that a screen can prove. If anyone could say the line without looking something up, rewrite it.
- **Hook = gossip/leak energy, first words,** written fresh for this product from its most surprising fact. Never open on "Okay", "So", "Hi guys", and never reuse an opener from an example or an earlier job. Each of the 3 options opens differently: a claim ("Your [thing] is lying to you."), a confession ("I've been doing [thing] wrong for ten years."), a number ("Eleven seconds. That's how long…"), a question ("Why does nobody tell you…?"), overheard/leak ("Apparently [group] are…"), a direct order ("Stop [doing X]."). Pet names ("babe", "girl") at most in one option, never as the default.
- **Frame choice:** the 3 options use 3 different frames, chosen for how naturally the product fits; no frame is the default. When picking for the user, pick on the strongest hook and most surprising fact, not the first option.
- **Length:** 45 s ≈ 150–165 words (3.4–3.7 words/s). Short spoken sentences, fragments allowed ("Five and a half. Each!"). Numbers written as said ("twenty fourteen"). Brand names easy to say.
- **One screen per thought:** each sentence names something that can be shown (a search, a study, a post, a label).
- **Product enters at 50–70%** with a clear break, never as one more list item: "Okay, forget the science.", "Easier way:", "Which is why I switched to…". Then what it is and one or two brand-stated facts. Never a claim from "must not claim".
- **Close:** a comment-keyword CTA ("Comment '[keyword]' and I'll send you the sources") or a follow; whatever it promises must exist.
- No real people named; say "a 2014 study", "researchers at Stanford".
- **Clip split:** split at a sentence end nearest the middle, each part ≤ 28 s by word count (words ÷ 3.5); never split inside the hook or between the product's name and what it does.

**Show all three at once** (an inline widget with tabs and an editable textarea per option, if widgets are available; otherwise the three scripts in full as text). For each: a 1–2 word tab name, a hook of ≤ 6 words, the on-screen title (with 1–2 emojis) and the spoken paragraph. The user picks or edits one; that text is final.

## 4. Character (only if the user has none)
Arcads `arcads_generate_image`, model `gpt-image-2-6-sunburst`, aspectRatio `9:16`, one image. An invented, ordinary-looking person who suits the product's buyer; never a lookalike of anyone real. Order: style line → person (age, genre) → face shape → skin → eyes/brows → lips → hair → clothes/accessories → expression + eye line → framing → room → LIGHTING → realism line. Example:

> Casual iPhone front-camera selfie, profile picture style. A 24-year-old woman, ordinary girl-next-door, not a model. Soft oval face with full cheeks and a slightly rounded chin, light olive skin with visible pores and a few faint freckles across the nose. Warm hazel eyes, slightly hooded, natural thick brows, no eyeliner. Medium-full lips with a soft cupid's bow, bare with a little balm. Shoulder-length dark brown hair with a natural wave, middle part, a few loose strands across her forehead, tucked behind one ear. Oversized faded grey crewneck sweatshirt, small gold hoop earrings. Relaxed half-smile, looking straight into the lens. Head and shoulders, camera held low, slightly below the chin. Her bedroom behind her, unmade bed and a plant slightly out of focus.
> LIGHTING: daylight from a window on camera-left, soft key on the left of her face, gentle shadow on the right cheek and under the jaw, the room behind a little darker.
> Real phone photo: slight wide-angle distortion, natural skin texture, mild noise, no retouching, no studio lighting, no bokeh effect.

Don't show it for approval; it goes straight into the narrator generation.

## 5. Quote and go
`python csa.py quote --clips <s1> <s2> --images <n screens to generate + 1 if character>`. Paste the lines, ask one "Go?". Nothing spends credits before the yes.
Arcads needs a `productId` on generations (a tag only): use `arcads_list_products` and pick the matching product or any existing one. Create one project per job with `arcads_create_project`, passing that product id as `brandId` (without it the call fails with PRODUCT_SELECTION_REQUIRED), and pass the project id to every generation.

## 6. Generate (after the yes, all in parallel, nothing shown)
Run independent tracks as background sub-agents (one per track, named "<BRAND>: <track>"), each briefed with the exact section of this file it needs, the job folder and the inputs. One generation per item, no re-rolls; report errors only.

**If you can't start sub-agents, do it in this order** (the slow Arcads jobs never wait on you): write + submit narrator clip 1 → make the screens while it renders → clip 1 done: submit clip 2 and cutout 1 → transcribe clip 1, edit part 1 → clip 2 done: submit cutout 2, transcribe clip 2 → cutout 2 done: whole-ad steps (§7.4 on).

| Track | Starts | Section |
| --- | --- | --- |
| Narrator clip 1 → clip 2 → cutouts | after "go" | 6A |
| Screens | after "go" | 6B |
| Edit part 1 | when clip 1's cutout and the screens are ready | 7 |

File inputs: anything already on Arcads (a generated clip, an image) is passed by its **asset id** directly, no upload (e.g. clip 1's id as clip 2's reference video, a clip's id to `arcads_remove_background`). For a local file, pass its path: the tool replies with a presigned URL and a curl command; run that curl as given (a bare `curl -X PUT --data-binary @<file> "<url>"` also works), then call the tool again with the returned `external-api-temp-uploads/...` path. Temp uploads are single-use: upload again for every call. Poll with `arcads_get_asset` (`waitSeconds` 40), repeated.

### 6A. Narrator (Seedance 2.5, pure prompt)
Clip 1: `arcads_generate_video_seedance_25` with `prompt`, `referenceImages=[character]`, `aspectRatio "9:16"`, `duration` = clip seconds (4–30, round up), `resolution "720p"`, `audioEnabled true`, `bitrateMode "high"`, `nbGenerations 1`, `productId`. Cost 42 credits/s.
Clip 2 (starts when clip 1 is done): same, plus clip 1 uploaded as the reference video, and the line "@video1: the same person, voice, room, light and camera from the previous take; continue it seamlessly." Same wardrobe/location/lighting/voice text; script = clip 2's lines only. +360 credits flat.
Cutouts: as each clip lands, upload it and run `arcads_remove_background` (`mediaType: video`, 80 credits, usually 4–7 min, sometimes 15+; don't resubmit before 20 min). Download the transparent `.webm` to `narrator/cutoutN.webm`, the clip to `narrator/clipN.mp4`.

**The prompt (14 blocks, this order, 4.5k–6k characters):**

```
References: @image1 = character

SCENE CONTEXT
<Who, where, what they're doing.> Filmed on her/his own front-facing camera, held low and close below the chin, looking down into the lens as she/he talks, telling <the listener> <the topic> straight to the lens, fast and animated, the way people talk on social media. One continuous <N>-second selfie take.

ACTIVE REFERENCES
@image1: her/his face, hair, skin and colouring come entirely from the reference and stay identical to it in every frame: <3–5 visible features: hair colour and texture, freckles, eye colour, earrings>. Only the identity comes from @image1: the setting, wardrobe, lighting, framing and pose all come from this prompt.

WARDROBE
<One line, everyday clothes that suit the character and contrast with hair and background.>

LOCATION MAP
Foreground: face and shoulders close to the lens, seen from below. Midground: <one or two objects right behind them>. Background: <the room, soft, mid-tone, uncluttered>.

FIRST FRAME / BLOCKING
Frame one: <a move already under way: pushing hair off the face, settling back onto the sofa, one hand mid-gesture>, mouth already open on the first word, eyes already on the lens. The hook is caught mid-action: in motion on the very first frame, never a still or neutral pose. Fully animated from the very first frame. Chest-up framing, face large in frame, a little headroom.

CAMERA
One continuous shot, the camera does not cut. LOW ANGLE LOOKING UP AT THE CREATOR FROM BELOW: the camera sits low, below the chin and close to the body, tilted up at the face. She/He tilts her/his head down slightly and looks DOWN into the lens the whole time; we see a little under the jaw and chin, and the upper wall and a strip of ceiling behind the head. Front-camera wide lens, mild edge rounding, face sharp, background soft. HANDHELD SHAKY CAMERA MOVEMENT THROUGHOUT: constant small irregular shake and wobble, little tilts of the horizon, the face drifting off-centre and being re-centred, bigger jolts on the emphatic words, a quick reframe around <N> seconds, light focus breathing. The shot is never locked or perfectly stable, not for a single second. Everyday auto-exposure, fine sensor noise in the shadows.

ACTION
She/He talks fast and never stops moving; all business happens while speaking.
0.0s to X.Xs - "<exact line>" <one physical action>, <delivery>.
... 3–6 beats (10 s ≈ 4 beats), each ≥ 1 s, each with the exact line, ONE action and the delivery ...
The take ends on the word "<last word>" at about <duration − 0.4> s.

PERFORMANCE
<Who they're talking to and their objective (e.g. telling her best friend something she can't believe).> A tactic per sentence, every change visible. Two truths at once (<e.g. scandalised and loving it>). Never still: small head tilts, eyebrow lifts, shoulder shrugs, leaning in to the lens, a hand counting or spreading open. Hands stay open and expressive, palms and fingers counting. Eyes alive: quick natural blinks, catch-lights, the gaze flicking off the lens and back right before the key line. Skin rendering: real pores, <freckles/marks true to @image1>, faint under-eye shadows, peach fuzz lit from the side, a light natural shine, nothing smoothed.

PHYSICS
Hair moves with the head and settles with real inertia. Clothes fold and shift when she/he moves.

LIGHTING
One motivated source: <e.g. soft window daylight at 5000K from camera-left>, one side of the face brighter with a gentle shadow down the nose, the background a stop darker than the face. The light stays the same for the whole take.

AUDIO
The entire soundtrack is the <room>: her/his voice close and clear, recorded right in front of her/him, fast and animated, in clear natural <American/British> English. She/He says exactly, and nothing else: "<full script of this clip>" Under it, <1–2 quiet room sounds>. Every sound comes from something in the scene. No music.

Her/His voice: "<age>-year-old <woman/man> from <city>, <accent>, <timbre>, fast, talking at real social-media speed to a friend rather than an audience."

STYLE
Photoreal low-angle, handheld, shaky front-camera selfie video, everyday auto-exposure, fine sensor noise, real time, the look of something posted straight away.

POSITIVE LOCKS
One person in frame, alone, face identical to @image1 throughout.
The frame is exactly what the front camera sees; the camera itself is never in frame.
Low angle looking up at the creator from below for the whole take, the face looking down into the lens.
Handheld shaky camera movement from the first frame to the last; never locked off.
Only one hand ever appears, gesturing near the face or chest; no arm reaches toward the lens.
Chest-up framing for the whole take; the head and shoulders stay inside the frame.
Every spoken word is in clear natural <American/British> English.
The take ends on the last word.
```

**Prompt rules (each learned from a failed take):**
- **Say "camera", never "phone".** Any phone wording ("the phone in her right hand", "phone mic", "set down / propped") makes Seedance show a phone in her hand.
- **Never "arm's length":** it generates a long forearm reaching into shot. Don't describe the holding arm at all.
- **@image1 is identity only.** A studio headshot or a selfie elsewhere: never copy its background, light, crop, expression or pose. If it has a pose that must not carry over (hand on face), say it's gone by frame one.
- **Setting for the cutout:** mid-tone, uncluttered background clearly separate from hair and clothes. Blonde/white hair → mid-grey or muted blue; red/auburn → slate blue, sage or grey (never orange); dark hair → light grey, warm beige or soft sage. No other people.
- **Voice:** accent = the product's market (UK → British, else American); age from the image; a city typical for that accent.
- **Beats:** timed by word count at ~3.5 words/s; lines under ~1 s merge into a neighbouring beat; write times in seconds. No asked-for pauses between lines (they become dead air); at most one deadpan silent beat, with a lock.
- **Props** only if the script needs one: "completely plain and blank, no label, no sticker, no writing", with the seconds it appears.
- Describe a light's effect, never a lamp "just out of frame" (it appears).
- Script text is exact: never rewrite, shorten or expand it.

### 6B. Screens
Plan first in `screens/MEDIA.md`: one row per screen → the line it sits under, route, source, **where the key element sits (top / middle / bottom)**, light or dark. Count: one per thought, 11–14 for 45 s. Make each at 1080×1920 as `screens/sNN_<route>_<short>.png` (or `.mp4` for a scroll).

| Route | For | How |
| --- | --- | --- |
| **USER** | Screenshots the user dropped in | Used first, on the lines they fit |
| **SCREENSHOT** | Real public pages that say what we need: the product page, articles, studies, Wikipedia, App Store | `python csa.py capture "<url>" screens/<name>` → hero.png (still) or scroll.mp4 (movement). Crop out any face, competitor or claim we can't make |
| **BUILD** | Exact text we write, or UI you can't capture: Google results / Images grid, AI Overview, Reddit post, YouTube results, iMessage, Notes checklist, stat card, App Store card for a fictional brand | A self-contained HTML page copying the native mobile UI exactly (system fonts, real spacing, light or dark), photos inside it from Wikimedia Commons or GENERATE, then `python csa.py html page.html out.png [--dark]` |
| **GENERATE** | Image tiles and photos with little or no text; a full Google Images results screen | `arcads_generate_image`, `gpt-image-2-6-sunburst`, 9:16, written as "a real iPhone screenshot of …". Never a sentence that matters inside an AI image |

Hard rules:
- **Native and recognisable only:** every screen is something the viewer sees on their own phone. No abstract stock imagery, no standalone photos.
- **About half are visual** (Google Images grids, image-led articles/posts, YouTube thumbnails, product photos); never more than 2–3 text-heavy screens in a row; max 3 from any one source type; mix light and dark mode.
- **The opening screen is the most hook-y visual one.** No empty or near-blank screens: each carries a result, fact, photo or message.
- **Real pages via Playwright only.** On a 429 / "too many requests": wait 60 s and retry, up to 3 times. Never use WebFetch and never build a fake copy of a real page instead. Still blocked → another real page with the same fact.
- **Never solve or bypass a CAPTCHA or bot check.** Google Search and Google Images are BUILT or GENERATED by design.
- **No real or famous people** in any screen: crop or rebuild faces; invented accounts and usernames only.
- No competitor promoted; no claim from "must not claim"; read every screenshot's small print.
- Annotations where they help: a red hand-drawn circle on the key number or word, a yellow highlighter behind the key phrase. On a real page or a built HTML screen: `python csa.py annotate "<url or page.html>" screens/<name>.png --find "<exact phrase>" --mark highlight|circle|both` (scrolls the phrase to the middle of the screen, marks it, screenshots). The phrase must be copied exactly as the page writes it and sit inside one run of text (not across a link).

## 7. Edit
Start part 1 as soon as clip 1's cutout and the screens exist; add clip 2 when it lands; run the whole-ad steps once.

1. **Words:** `python csa.py words narrator/clip1.mp4 edit/words1.json` (and clip 2). Compare with the script.
2. **EDL** `edit/edl.json`, paths relative to it:
```json
{"out": "full.mp4", "loudness": -14,
 "takes": [{"cutout": "../narrator/cutout1.webm", "audio": "../narrator/clip1.mp4", "duration": 23.6},
           {"cutout": "../narrator/cutout2.webm", "audio": "../narrator/clip2.mp4", "duration": 21.9}],
 "segments": [{"start": 0, "end": 3.9, "src": "../screens/s01_gen_gimages.png", "keep": "top"},
              {"start": 3.9, "end": 6.1, "src": "../screens/s02_build_reddit.png", "keep": "middle"}],
 "overlays": []}
```
   - `takes` play back to back; `duration` = where the speech ends + 0.2 s (`offset` skips a bad start).
   - `segments` run 0 → total with no gaps, one per thought (~3–4 s; max 4.5 s for a still). Cut on the noun that names the screen ("look this up" → Google). When the next line continues the same idea, keep one screen across both.
   - `keep` = where the screen's key element is (from MEDIA.md), so the cutout avoids it.
   - Optional per segment: `w, x, y` (cutout width and top-left, px), `drag: true`, `pos: "HIDE"` (no narrator, e.g. a page that must read), `pos: "FULL"` (full-frame narrator, hook or CTA only, ≤ 15% of runtime), `src_offset` for a video.
3. **Layout:** `python csa.py layout edit/edl.json` fills `w/x/y/drag`:
   - opening: big and central (700–760 px wide) over the hook screen;
   - then a new size and position on every cut, 480–760 px wide, roughly a third each top / middle / bottom, left / right / centre, sometimes pushed half off the side;
   - every third shot `drag`: a simulated thumb pressing and dragging the cutout (bursts, stops, direction changes, the odd rough circle, slight tremor);
   - the cutout's bottom edge always ≥ 60 px above the frame bottom; never over the `keep` area.
   Look at the result and adjust any segment by hand where the cutout would cover the key element.
4. `python csa.py snap edit/edl.json` (moves every cut to the quietest point of the voice), `python csa.py render edit/edl.json`.
5. **Self-review (always):** `python csa.py contact edit/edl.json edit/contact.jpg` and look: cutout off every key element, face, product and price; each screen matches its line; neighbours look different; nothing banned in small print. Fix in the EDL (swap/move/hide), never by regenerating unless a line is missing or mispronounced.
6. **Tighten:** `python csa.py tighten edit/edl.json edit/edl_tight.json` → `snap` it → `render` it → `python csa.py check edit/edl_tight.json edit/full_tight.mp4`. "Cuts on speech" and "touching the bottom" must PASS. Target ≥ 3.7 words/s.
7. **Captions cues:** `python csa.py words edit/full_tight.mp4 edit/words_tight.json`, then `python csa.py cues edit/cues.json edit/words_tight.json:0`. Fix spellings against the script (brand names, numbers).
8. **Title + captions on Arcads (one chain):** `python csa.py prep edit/edl_tight.json --title "<hook line with 1–2 emojis, ≤ 3 lines>" --cues edit/cues.json --name "<Brand> - <Concept> - v1" --product <productId> [--project <id>]`. It renders a clean copy and writes `edit/finish_calls.json`. Make call 1 (`arcads_add_text_overlay`, args as written: style `insta-dark` = white text on a black box, fontSize 18, top, margins 0.1, first 3.5 s; not `tiktok-dark`/`tiktok-light`, which render as outlined text with no box), wait; make call 2 (`arcads_add_subtitles`, style `tiktok-none`, your cues as `segments`, `sourceVideoAssetId` = call 1's asset id), wait.
9. **Fetch:** `python csa.py fetch "<downloadUrl>" --name "<same name>" --edit-dir edit`. Look at `check_title.jpg` (black box, white text, above the face, ≤ 3 lines) and `check_caption.jpg`. Deliver.

## Checks before delivery
1. No real or famous person we chose, anywhere (a user-supplied creator is fine).
2. Every readable text on a screen is exact (real page or HTML), and none breaks "must not claim".
3. Median shot ≤ 3.5 s; no still over 4.5 s; a new cutout size/position every cut; ≥ 30% drag shots; cutout never covers a key element or touches the bottom.
4. No cut on speech; ends on the CTA's last word, not clipped.
5. Product first named at 50–70% of runtime.

---

## Appendix A: csa.py
Write this to `csa.py` next to this file if it isn't there.

```python
"""csa.py: the local toolbox for the creator-screenshots-ad skill (one file, no install beyond deps).

  python csa.py deps                                   check ffmpeg / Python packages / Chrome
  python csa.py quote --clips 24 22 [--images 14]      credit quote (clip 1 prompt-only, clip 2 +ref)
  python csa.py capture <url> <out_dir> [--seconds 6]  real page -> hero.png, fullpage.jpg, scroll.mp4
  python csa.py html <page.html> <out.png> [--dark]    render a built HTML screen at 1080x1920
  python csa.py annotate <url|page.html> <out.png> --find "phrase" [--mark highlight|circle|both]
                                                       scroll a page to a phrase, mark it, screenshot
  python csa.py words <media> <words.json>             word timings (faster-whisper small.en)
  python csa.py layout <edl.json>                      fill cutout size/position/drag per segment
  python csa.py snap <edl.json>                        move every cut to the quietest point of the voice
  python csa.py render <edl.json>                      render the EDL with ffmpeg
  python csa.py tighten <edl.json> <edl_tight.json>    trim pauses at cuts to ~0.2 s, end on last word
  python csa.py check <edl.json> <render.mp4>          shot lengths, cuts on speech, loudness, freezes
  python csa.py contact <edl.json|video> <out.jpg>     one frame per segment (or 8 frames of a video)
  python csa.py cues <cues.json> <words.json>:<offset>[:<limit>] ...   2-3 word caption cues
  python csa.py prep <edl.json> --title "..." --cues cues.json --name "Brand - Concept - v1" --product <id>
  python csa.py fetch <url> --name "Brand - Concept - v1" --edit-dir <dir>
"""
import argparse, datetime, json, math, os, random, re, shutil, subprocess, sys, tempfile, time, urllib.request

W, H, FPS = 1080, 1920, 30
BOTTOM_GAP = 60
RATES = {"sec_720p": 42, "ref_flat": 360, "cutout": 80}


def ff(*a, **k):
    return subprocess.run(["ffmpeg", "-v", "error", "-y", *a], check=True, **k)


def dur(path):
    return float(subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", path],
                                capture_output=True, text=True).stdout.strip())


def load(p):
    return json.load(open(p, encoding="utf-8"))


def save(o, p):
    json.dump(o, open(p, "w", encoding="utf-8"), indent=1, ensure_ascii=False)


# ---------------------------------------------------------------- deps / quote
def cmd_deps(a):
    ok = True
    for exe in ("ffmpeg", "ffprobe"):
        f = shutil.which(exe); print(("OK  " if f else "MISS"), exe, f or "-> install ffmpeg (winget install Gyan.FFmpeg / brew install ffmpeg)"); ok &= bool(f)
    if shutil.which("ffmpeg"):
        enc = subprocess.run(["ffmpeg", "-hide_banner", "-encoders"], capture_output=True, text=True).stdout
        dec = subprocess.run(["ffmpeg", "-hide_banner", "-decoders"], capture_output=True, text=True).stdout
        v = "libvpx-vp9" in dec or "libvpx-vp9" in enc
        print("OK  " if v else "MISS", "libvpx-vp9 (needed to read transparent cutouts)"); ok &= v
    for mod, pipn in (("numpy", "numpy"), ("PIL", "pillow"), ("faster_whisper", "faster-whisper"), ("playwright", "playwright")):
        try:
            __import__(mod); print("OK  ", mod)
        except Exception:
            print("MISS", mod, f"-> pip install {pipn}"); ok = False
    chrome = any(os.path.exists(p) for p in [r"C:\Program Files\Google\Chrome\Application\chrome.exe",
                                             r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
                                             "/Applications/Google Chrome.app"]) or shutil.which("google-chrome")
    print("OK  " if chrome else "MISS", "Google Chrome", "" if chrome else "-> install Chrome, or `playwright install chromium` and pass --browser chromium")
    print("ALL OK" if ok else "Install what's missing (tell the user first).")


def cmd_quote(a):
    lines, total = [], 0
    for i, s in enumerate(a.clips, 1):
        c = round(s * RATES["sec_720p"]) + (RATES["ref_flat"] if i > 1 else 0)
        lines.append(f"Narrator clip {i} ({s:g} s, 720p{', continues clip 1' if i > 1 else ''}): {c:,}"); total += c
    c = len(a.clips) * RATES["cutout"]; lines.append(f"Greenscreen cutouts ({len(a.clips)} x {RATES['cutout']}): {c:,}"); total += c
    lines.append(f"Character + screen images ({a.images}, GPT Image 2.6): free within the daily allowance")
    lines.append("Title + captions: 0")
    lines.append(f"TOTAL: about {total:,} credits")
    print("\n".join(lines))


# ---------------------------------------------------------------- capture / html
UA = ("Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 "
      "(KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1")
DECLINE = ["decline", "reject", "necessary only", "only necessary", "essential only", "no thanks", "not now", "maybe later"]
HIDE_JS = r"""() => { const hits = [];
  const pat = /cookie|consent|gdpr|onetrust|klaviyo|popup|pop-up|newsletter|modal|overlay|chat-widget|intercom|gorgias/i;
  for (const el of document.querySelectorAll('body *')) { const cs = getComputedStyle(el);
    if (cs.position !== 'fixed' && cs.position !== 'sticky') continue;
    const tag = (el.id + ' ' + el.className + ' ' + (el.getAttribute('aria-label') || '')).toString();
    const r = el.getBoundingClientRect(); const big = r.width * r.height > 0.25 * innerWidth * innerHeight;
    const dialog = el.getAttribute('role') === 'dialog' || el.tagName === 'DIALOG';
    const consent = /cookie|privacy policy|consent/i.test((el.innerText || '').slice(0, 400)) && r.height < innerHeight * 0.7;
    if (pat.test(tag) || dialog || consent || (big && cs.position === 'fixed' && +cs.zIndex > 100)) {
      el.style.setProperty('display', 'none', 'important'); hits.push(tag.trim().slice(0, 60) || el.tagName); } }
  document.documentElement.style.overflow = 'auto'; document.body.style.overflow = 'auto'; return hits; }"""


def _browser(p, which):
    kw = {"headless": True}
    if which == "chrome":
        kw["channel"] = "chrome"
    return p.chromium.launch(**kw)


def cmd_capture(a):
    from playwright.sync_api import sync_playwright
    os.makedirs(a.out_dir, exist_ok=True)
    frames = os.path.join(a.out_dir, "_frames"); shutil.rmtree(frames, ignore_errors=True); os.makedirs(frames)
    log = {"url": a.url, "dismissed": [], "hidden": []}
    ease = lambda t: 0.5 - 0.5 * math.cos(math.pi * t)
    with sync_playwright() as p:
        b = _browser(p, a.browser)
        page = b.new_context(viewport={"width": 360, "height": 640}, device_scale_factor=3, is_mobile=True,
                             has_touch=True, user_agent=UA, locale="en-GB").new_page()
        resp = page.goto(a.url, wait_until="domcontentloaded", timeout=60000)
        log["status"] = resp.status if resp else None
        if log["status"] == 429:
            print(json.dumps(log)); sys.exit("429 Too Many Requests: wait 60 s and run again (max 3 tries). Never WebFetch or rebuild the page.")
        try:
            page.wait_for_load_state("networkidle", timeout=15000)
        except Exception:
            pass
        page.wait_for_timeout(2500)
        for word in DECLINE:
            try:
                btn = page.get_by_role("button", name=word, exact=False).first
                if btn.is_visible(timeout=500):
                    btn.click(timeout=1500); log["dismissed"].append(word); page.wait_for_timeout(500)
            except Exception:
                pass
        total = page.evaluate("document.documentElement.scrollHeight"); y = 0
        while y < total:
            page.evaluate(f"window.scrollTo(0,{y})"); page.wait_for_timeout(250); y += 640
        page.evaluate("window.scrollTo(0,0)"); page.wait_for_timeout(1500)
        log["hidden"] = page.evaluate(HIDE_JS); log["title"] = page.title()
        total = page.evaluate("document.documentElement.scrollHeight")
        page.screenshot(path=os.path.join(a.out_dir, "hero.png"))
        page.screenshot(path=os.path.join(a.out_dir, "fullpage.jpg"), full_page=True, type="jpeg", quality=88)
        dist = max(0, min(a.max_scroll, total - 640)); n = int(a.seconds * FPS); hold = FPS // 2
        for i in range(n):
            t = 0 if i < hold else 1 if i >= n - hold else (i - hold) / max(1, n - 2 * hold - 1)
            if i % 30 == 0:
                page.evaluate(HIDE_JS)
            page.evaluate(f"window.scrollTo(0,{dist * ease(t):.2f})")
            page.screenshot(path=os.path.join(frames, f"f{i:05d}.jpg"), type="jpeg", quality=92)
        b.close()
    ff("-framerate", str(FPS), "-i", os.path.join(frames, "f%05d.jpg"), "-vf", f"scale={W}:{H}", "-c:v", "libx264",
       "-crf", "16", "-pix_fmt", "yuv420p", os.path.join(a.out_dir, "scroll.mp4"))
    shutil.rmtree(frames, ignore_errors=True)
    save(log, os.path.join(a.out_dir, "capture.json")); print(json.dumps(log, indent=1))


def cmd_html(a):
    from playwright.sync_api import sync_playwright
    with sync_playwright() as p:
        b = _browser(p, a.browser)
        page = b.new_context(viewport={"width": 360, "height": 640}, device_scale_factor=3,
                             color_scheme="dark" if a.dark else "light").new_page()
        page.goto("file:///" + os.path.abspath(a.html).replace("\\", "/")); page.wait_for_timeout(1200)
        page.screenshot(path=a.out); b.close()
    print("wrote", a.out)


ANNOTATE_JS = r"""([phrase, mark]) => {
  const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
  const low = phrase.toLowerCase(); let node;
  while ((node = walker.nextNode())) {
    const i = node.textContent.toLowerCase().indexOf(low);
    if (i < 0 || !node.parentElement || !node.parentElement.offsetParent) continue;
    const r = document.createRange(); r.setStart(node, i); r.setEnd(node, i + phrase.length);
    const span = document.createElement('span'); r.surroundContents(span);
    if (mark !== 'circle') { span.style.background = 'rgba(255,224,102,0.75)'; span.style.boxShadow = '0 0 0 2px rgba(255,224,102,0.75)'; span.style.borderRadius = '3px'; }
    span.scrollIntoView({block: 'center'});
    if (mark !== 'highlight') {
      const b = span.getBoundingClientRect(); const ns = 'http://www.w3.org/2000/svg';
      const svg = document.createElementNS(ns, 'svg'); const pad = 10;
      svg.setAttribute('style', `position:fixed;left:${b.left - pad}px;top:${b.top - pad}px;width:${b.width + 2 * pad}px;height:${b.height + 2 * pad}px;overflow:visible;z-index:2147483647;pointer-events:none`);
      const w = b.width + 2 * pad, h = b.height + 2 * pad;
      const path = document.createElementNS(ns, 'path');
      path.setAttribute('d', `M ${w * 0.08} ${h * 0.25} C ${w * 0.3} ${-h * 0.15}, ${w * 0.9} ${-h * 0.1}, ${w * 0.98} ${h * 0.45} C ${w * 1.04} ${h * 0.95}, ${w * 0.35} ${h * 1.12}, ${w * 0.06} ${h * 0.8} C ${-w * 0.04} ${h * 0.6}, ${w * 0.05} ${h * 0.2}, ${w * 0.22} ${h * 0.08}`);
      path.setAttribute('fill', 'none'); path.setAttribute('stroke', '#E53935'); path.setAttribute('stroke-width', '2.4'); path.setAttribute('stroke-linecap', 'round');
      svg.appendChild(path); document.body.appendChild(svg);
    }
    return true;
  }
  return false; }"""


def cmd_annotate(a):
    from playwright.sync_api import sync_playwright
    src = a.src if a.src.startswith("http") else "file:///" + os.path.abspath(a.src).replace("\\", "/")
    with sync_playwright() as p:
        b = _browser(p, a.browser)
        page = b.new_context(viewport={"width": 360, "height": 640}, device_scale_factor=3, is_mobile=True,
                             has_touch=True, user_agent=UA, locale="en-GB").new_page()
        resp = page.goto(src, wait_until="domcontentloaded", timeout=60000)
        if resp and resp.status == 429:
            sys.exit("429 Too Many Requests: wait 60 s and run again (max 3 tries). Never WebFetch or rebuild the page.")
        page.wait_for_timeout(2500)
        for word in DECLINE:
            try:
                btn = page.get_by_role("button", name=word, exact=False).first
                if btn.is_visible(timeout=400):
                    btn.click(timeout=1500); page.wait_for_timeout(400)
            except Exception:
                pass
        page.evaluate(HIDE_JS)
        if not page.evaluate(ANNOTATE_JS, [a.find, a.mark]):
            b.close(); sys.exit(f'phrase not found on the page: "{a.find}" (copy it exactly as the page writes it)')
        page.wait_for_timeout(500); page.evaluate(HIDE_JS); page.screenshot(path=a.out); b.close()
    print("wrote", a.out)


# ---------------------------------------------------------------- words / cues
def cmd_words(a):
    from faster_whisper import WhisperModel
    wav = os.path.join(tempfile.mkdtemp(), "a.wav")
    ff("-i", a.media, "-vn", "-ac", "1", "-ar", "16000", wav)
    segs, _ = WhisperModel("small.en", device="cpu", compute_type="int8").transcribe(wav, word_timestamps=True)
    w = [{"w": x.word.strip(), "s": round(x.start, 2), "e": round(x.end, 2)} for s in segs for x in s.words]
    save(w, a.out); print(f"{len(w)} words -> {a.out}\n" + " ".join(x["w"] for x in w))


def cmd_cues(a):
    words = []
    for spec in a.specs:
        m = re.match(r"^(.*?):([\d.]+)(?::([\d.]+))?$", spec)
        path, off, lim = m.group(1), float(m.group(2)), float(m.group(3) or 1e9)
        words += [dict(w, s=w["s"] + off, e=min(w["e"], lim) + off) for w in load(path) if w["s"] < lim]
    # split into clauses at punctuation or pauses, then chunk each clause into 2-3 word cues
    clauses, cur = [], []
    for i, w in enumerate(words):
        cur.append(w)
        nxt = words[i + 1] if i + 1 < len(words) else None
        if not nxt or re.search(r"[.,?!;:]$", w["w"]) or nxt["s"] - w["e"] > 0.35:
            clauses.append(cur); cur = []
    cues = []
    for c in clauses:
        n = len(c)
        sizes = [n] if n <= 3 else [3] * (n // 3) + ([n % 3] if n % 3 else [])
        if len(sizes) > 1 and sizes[-1] == 1:
            sizes[-1] = 2; sizes[-2] -= 1
        k = 0
        for z in sizes:
            cues.append(c[k:k + z]); k += z
    out = []
    for c in cues:
        text = " ".join(re.sub(r"[^\w'\-%$£€]", "", x["w"]) for x in c).strip()
        out.append({"text": text, "startSeconds": round(c[0]["s"], 2), "endSeconds": round(c[-1]["e"], 2)})
    for x, y in zip(out, out[1:]):
        x["endSeconds"] = min(y["startSeconds"], round(x["endSeconds"] + 0.25, 2))
    if out:
        out[-1]["endSeconds"] = round(out[-1]["endSeconds"] + 0.3, 2)
    save(out, a.out); print(f"{len(out)} cues -> {a.out}\n" + " | ".join(c["text"] for c in out))


# ---------------------------------------------------------------- layout (cutout placement + drag)
def cmd_layout(a):
    """Fill w/x/y/drag for segments that lack them, following the approved motion rules.
    Optional per-segment hint "keep": "top"|"middle"|"bottom" = where the screen's key element is
    (the cutout goes elsewhere). Existing w/x/y are kept. Deterministic (seeded)."""
    e = load(a.edl); segs = sorted(e["segments"], key=lambda s: s["start"]); rnd = random.Random(7)
    bands = ["top", "middle", "bottom"]; prev = None
    for k, s in enumerate(segs):
        if "w" in s or s.get("pos") in ("HIDE", "FULL"):
            prev = (s.get("w"), s.get("x"), s.get("y")); continue
        if k == 0:  # opening: big and central over the hook screen
            w = rnd.randint(700, 760); s.update(w=w, x=(W - w) // 2, y=H - round(w * 16 / 9) - 200, pos="FREE")
            prev = (s["w"], s["x"], s["y"]); continue
        for _ in range(20):
            band = bands[k % 3] if rnd.random() < 0.7 else rnd.choice(bands)
            if s.get("keep") == band:
                continue
            w = rnd.choice([480, 520, 560, 600, 640, 680, 720, 760] if band != "middle" else [480, 520, 560, 600])
            h = round(w * 16 / 9)
            side = rnd.choice(["left", "right", "centre"] if w < 640 else ["left", "right"])
            x = {"left": rnd.randint(-40, 30), "right": W - w + rnd.randint(-30, 40), "centre": (W - w) // 2}[side]
            y = {"top": rnd.randint(-260, -120), "middle": rnd.randint(250, 480), "bottom": H - h - BOTTOM_GAP - rnd.randint(0, 60)}[band]
            y = min(y, H - h - BOTTOM_GAP)
            if (w, x, y) != prev and (prev is None or abs(w - (prev[0] or 0)) >= 40):
                break
        s.update(w=w, x=x, y=y, pos="FREE")
        if k % 3 == 2:  # every third shot is dragged by the "thumb"
            s["drag"] = True
        prev = (w, x, y)
    e["segments"] = segs; save(e, a.edl)
    n = sum(1 for s in segs if s.get("drag"))
    print(f"laid out {len(segs)} segments, {n} drag ({n / max(1, len(segs)):.0%})")
    for s in segs:
        print(f"{s['start']:6.2f}-{s['end']:6.2f}  w{s.get('w')} x{s.get('x')} y{s.get('y')} {'DRAG' if s.get('drag') else ''}  {os.path.basename(str(s.get('src')))}")


def drag_path(s):
    """A thumb pressing and dragging the cutout: momentum, bursts, holds, rough loops, tremor. 15 keys/s."""
    if "path" in s:
        return s["path"]
    rnd = random.Random(int(s["start"] * 1000) + 7)
    d = s["end"] - s["start"]; w = int(s["w"]); h = round(w * 16 / 9)
    x0, y0 = s["x"], s["y"]; rx, ry = s.get("drag_x", 240), s.get("drag_y", 300)
    dt = 1 / 15; x, y = float(x0), float(y0); vx = vy = 0.0; pts = [(0.0, x, y)]; t = 0.0
    plan, tt = [], rnd.uniform(0.0, 0.4)
    while tt < d:
        kind = rnd.choices(["hold", "drag", "loop"], [0.30, 0.52, 0.18])[0]
        du = {"hold": rnd.uniform(0.25, 0.8), "drag": rnd.uniform(0.6, 1.6), "loop": rnd.uniform(0.8, 1.4)}[kind]
        plan.append((tt, min(d, tt + du), kind, rnd.random())); tt += du
    target, loop_c = (x0, y0), None
    while t < d - 1e-6:
        t += dt
        ts, te, kind, seed = next((p for p in plan if p[0] <= t < p[1]), (0, d, "hold", 0))
        u = (t - ts) / max(te - ts, 1e-3)
        if kind == "hold":
            vx *= 0.55; vy *= 0.55
        elif kind == "drag":
            if u < dt * 2 / max(te - ts, 1e-3) or rnd.random() < 0.08:
                target = (x0 + rnd.uniform(-1, 1) * rx, y0 + rnd.uniform(-1, 1) * ry)
            sp = 0.5 + 1.6 * abs(math.sin(math.pi * u * (1 + seed)))
            vx = vx * 0.82 + (target[0] - x) * 6.0 * sp * dt; vy = vy * 0.82 + (target[1] - y) * 6.0 * sp * dt
        else:
            if loop_c is None or u < dt * 1.5:
                r = rnd.uniform(70, 150); a0 = rnd.uniform(0, 2 * math.pi)
                loop_c = (x - r * math.cos(a0), y - r * math.sin(a0), r, a0, rnd.choice([-1, 1]))
            cx, cy, r, a0, sg = loop_c
            ang = a0 + sg * 2 * math.pi * (u ** 0.9) * (1 + 0.15 * math.sin(7 * u))
            tx = cx + r * (1 + 0.15 * math.sin(3 * ang)) * math.cos(ang); ty = cy + r * 0.85 * math.sin(ang)
            vx = (tx - x) / dt * 0.7 + vx * 0.3; vy = (ty - y) / dt * 0.7 + vy * 0.3
        if kind != "loop":
            loop_c = None
        x += vx * dt + rnd.gauss(0, 1.6); y += vy * dt + rnd.gauss(0, 1.6)
        x = min(max(x, -w * 0.2), W - w * 0.8); y = min(max(y, -h * 0.15), H - h - BOTTOM_GAP)
        pts.append((round(t, 3), round(x, 1), round(y, 1)))
    return pts


# ---------------------------------------------------------------- render
def cmd_render(a, edl_path=None):
    edl_path = os.path.abspath(edl_path or a.edl); root = os.path.dirname(edl_path); e = load(edl_path)
    P = lambda p: p if os.path.isabs(p) else os.path.join(root, p)
    takes = e["takes"]; total = round(sum(t["duration"] for t in takes), 3)
    segs = sorted(e["segments"], key=lambda s: s["start"])
    if abs(segs[0]["start"]) > 1e-6 or abs(segs[-1]["end"] - total) > 0.05:
        sys.exit(f"segments must run 0..{total}; got {segs[0]['start']}..{segs[-1]['end']}")
    for x, y in zip(segs, segs[1:]):
        if abs(x["end"] - y["start"]) > 1e-3:
            sys.exit(f"gap/overlap at {x['end']}/{y['start']}")
    cmd, fc, idx = ["ffmpeg", "-v", "error", "-y"], [], 0
    for i, s in enumerate(segs):
        d = s["end"] - s["start"]; src = P(s["src"])
        if src.lower().endswith((".mp4", ".mov", ".webm")):
            cmd += ["-ss", str(s.get("src_offset", 0)), "-t", f"{d + 0.5:.3f}", "-i", src]
            fc.append(f"[{idx}:v]scale={W}:{H}:force_original_aspect_ratio=increase,crop={W}:{H},setsar=1,tpad=stop_mode=clone:stop_duration=5,"
                      f"trim=duration={d:.3f},setpts=PTS-STARTPTS,fps={FPS},format=yuv420p[b{i}]")
        else:
            cmd += ["-loop", "1", "-framerate", str(FPS), "-t", f"{d:.3f}", "-i", src]
            fc.append(f"[{idx}:v]scale={W}:{H}:force_original_aspect_ratio=increase,crop={W}:{H},setsar=1,fps={FPS},format=yuv420p[b{i}]")
        idx += 1
    fc.append("".join(f"[b{i}]" for i in range(len(segs))) + f"concat=n={len(segs)}:v=1:a=0[bg]")
    vt, at = [], []
    for k, t in enumerate(takes):
        off = t.get("offset", 0)
        cmd += ["-c:v", "libvpx-vp9", "-i", P(t["cutout"])]
        fc.append(f"[{idx}:v]trim=start={off}:duration={t['duration']},setpts=PTS-STARTPTS,fps={FPS},format=yuva420p[nv{k}]"); vt.append(f"[nv{k}]"); idx += 1
        cmd += ["-i", P(t["audio"])]
        fc.append(f"[{idx}:a]atrim=start={off}:duration={t['duration']},asetpts=PTS-STARTPTS,aresample=48000[na{k}]"); at.append(f"[na{k}]"); idx += 1
    fc.append("".join(vt) + f"concat=n={len(takes)}:v=1:a=0[nar]")
    fc.append("".join(at) + f"concat=n={len(takes)}:v=0:a=1[voice]")
    free = [s for s in segs if "w" in s and s.get("pos") != "HIDE"]
    full = [s for s in segs if s.get("pos") == "FULL"]
    widths = sorted({int(s["w"]) for s in free})
    n_out = len(widths) + (1 if full else 0) or 1
    fc.append(f"[nar]split={n_out}" + "".join(f"[n{i}]" for i in range(n_out)))
    btw = lambda s: f"between(t,{s['start']:.3f},{s['end']:.3f})"
    cur = "bg"
    if not widths and not full:
        fc.append("[n0]nullsink")
    for i, w in enumerate(widths):
        fc.append(f"[n{i}]scale={w}:-2[w{w}]")

    def pexpr(s, k):
        pts = drag_path(s); a0 = s["start"]; ex = f"{pts[-1][k]:.1f}"
        for (ta, *pa), (tb, *pb) in reversed(list(zip(pts, pts[1:]))):
            va, vb = pa[k - 1], pb[k - 1]
            piece = f"({va:.1f}+({vb - va:.1f})*(t-{a0 + ta:.3f})/{max(tb - ta, 1e-3):.3f})" if va != vb else f"{vb:.1f}"
            ex = f"if(lt(t,{a0 + tb:.3f}),{piece},{ex})"
        return ex
    for w in widths:
        grp = [s for s in free if int(s["w"]) == w]; xs = ys = "0"
        for s in reversed(grp):
            mv = s.get("drag") or "path" in s
            xs = f"if({btw(s)},{pexpr(s, 1) if mv else s['x']},{xs})"; ys = f"if({btw(s)},{pexpr(s, 2) if mv else s['y']},{ys})"
        fc.append(f"[{cur}][w{w}]overlay=x='{xs}':y='{ys}':enable='{'+'.join(btw(s) for s in grp)}':eof_action=pass[v{w}]"); cur = f"v{w}"
    if full:  # full-frame narrator (cutout scaled to fill, on its own background image)
        fc.append(f"[n{len(widths)}]scale={W}:-2[nfull]")
        fc.append(f"[{cur}][nfull]overlay=x=0:y=0:enable='{'+'.join(btw(s) for s in full)}':eof_action=pass[vfull]"); cur = "vfull"
    for j, o in enumerate(e.get("overlays", [])):
        cmd += ["-loop", "1", "-framerate", str(FPS), "-t", f"{total}", "-i", P(o["src"])]
        fc.append(f"[{cur}][{idx}:v]overlay=0:0:enable='between(t,{o['start']},{o['end']})'[ov{j}]"); cur = f"ov{j}"; idx += 1
    fc.append(f"[voice]loudnorm=I={e.get('loudness', -14)}:TP=-1.5:LRA=11,aresample=48000[aout]")
    out = P(e.get("out", "out.mp4")); fcp = out + ".filter.txt"
    open(fcp, "w", encoding="utf-8").write(";".join(fc))
    cmd += ["-filter_complex_script", fcp, "-map", f"[{cur}]", "-map", "[aout]", "-t", f"{total}", "-c:v", "libx264", "-preset", "medium",
            "-crf", "18", "-pix_fmt", "yuv420p", "-r", str(FPS), "-c:a", "aac", "-b:a", "192k", "-movflags", "+faststart", out]
    subprocess.run(cmd, check=True); os.remove(fcp)
    print(f"wrote {out} ({total} s, {len(segs)} segments, {len(takes)} takes)")
    return out


# ---------------------------------------------------------------- snap / tighten / check
def _voice(e, root, sr=16000):
    import numpy as np
    parts = []
    for t in e["takes"]:
        p = t["audio"] if os.path.isabs(t["audio"]) else os.path.join(root, t["audio"])
        raw = subprocess.run(["ffmpeg", "-v", "error", "-ss", str(t.get("offset", 0)), "-t", str(t["duration"]), "-i", p,
                              "-ac", "1", "-ar", str(sr), "-f", "f32le", "-"], capture_output=True, check=True).stdout
        x = np.frombuffer(raw, dtype=np.float32); n = int(round(t["duration"] * sr))
        parts.append(np.pad(x, (0, max(0, n - len(x))))[:n])
    return np.concatenate(parts)


def _env(x, sr=16000):
    import numpy as np
    h = sr // 100; n = len(x) // h
    r = np.sqrt(np.mean(x[:n * h].reshape(n, h) ** 2, axis=1) + 1e-12)
    return 20 * np.log10(r / r.max())


def cmd_snap(a):
    import numpy as np
    root = os.path.dirname(os.path.abspath(a.edl)); e = load(a.edl); env = _env(_voice(e, root))
    segs = sorted(e["segments"], key=lambda s: s["start"]); joins, acc = [], 0
    for t in e["takes"][:-1]:
        acc += t["duration"]; joins.append(acc)
    for x, y in zip(segs, segs[1:]):
        c = y["start"]
        if any(abs(c - j) < 0.3 for j in joins):
            continue
        lo = max(int((c - 0.3) * 100), int(x["start"] * 100) + 40); hi = min(int((c + 0.3) * 100), int(y["end"] * 100) - 40)
        if hi <= lo:
            continue
        i = lo + int(np.argmin(env[lo:hi])); new = round(i / 100 + 0.005, 3)
        print(f"cut {c:7.2f} -> {new:7.2f}  ({env[min(int(c * 100), len(env) - 1)]:5.1f} -> {env[i]:5.1f} dB)")
        x["end"] = y["start"] = new
    e["segments"] = segs; save(e, a.edl)


def _silences(path):
    r = subprocess.run(["ffmpeg", "-i", path, "-af", "silencedetect=noise=-35dB:d=0.2", "-f", "null", "-"], capture_output=True, text=True).stderr
    return list(zip([float(v) for v in re.findall(r"silence_start: ([\d.]+)", r)], [float(v) for v in re.findall(r"silence_end: ([\d.]+)", r)]))


def cmd_tighten(a):
    root = os.path.dirname(os.path.abspath(a.edl)); e = load(a.edl)
    P = lambda p: p if os.path.isabs(p) else os.path.join(root, p)
    T, tk = 0, []
    for t in e["takes"]:
        tk.append((T, T + t["duration"], t.get("offset", 0))); T += t["duration"]

    def to_src(x):
        for i, (s0, s1, o) in enumerate(tk):
            if x < s1 - 1e-6 or i == len(tk) - 1:
                return i, x - s0 + o
    sil = [_silences(P(t["audio"])) for t in e["takes"]]
    segs = sorted(e["segments"], key=lambda s: s["start"]); wins = []
    for s in segs:
        i, x0 = to_src(s["start"]); j, x1 = to_src(s["end"] - 1e-4); x1 += 1e-4
        if j != i:
            x1 = tk[i][2] + tk[i][1] - tk[i][0]
        wins.append([i, x0, x1])
    for k in range(len(wins)):
        i, x0, x1 = wins[k]
        if k == len(wins) - 1 or wins[k + 1][0] != i:
            tail = [ss for ss, se in sil[i] if x0 + 0.5 < ss < x1]
            if tail:
                wins[k][2] = min(x1, tail[-1] + 0.12)
            continue
        near = [(ss, se) for ss, se in sil[i] if x1 - 0.8 <= ss <= x1 + 0.4]
        if near:
            ss, se = min(near, key=lambda p: abs((p[0] + p[1]) / 2 - x1))
            if se - ss > 0.25:
                wins[k][2] = ss + 0.10; wins[k + 1][1] = se - 0.10
            else:
                wins[k][2] = wins[k + 1][1] = (ss + se) / 2
    takes, t0, new = [], 0, []
    for s, (i, x0, x1) in zip(segs, wins):
        src = e["takes"][i]; d = round(x1 - x0, 3)
        takes.append({"cutout": src["cutout"], "audio": src["audio"], "offset": round(x0, 3), "duration": d})
        n = dict(s); n["start"] = round(t0, 3); n["end"] = round(t0 + d, 3); new.append(n); t0 += d
    e["takes"], e["segments"] = takes, new
    for o in e.get("overlays", []):
        o["end"] = new[0]["end"]
    e["out"] = e.get("out", "out.mp4").replace(".mp4", "_tight.mp4"); save(e, a.out)
    print(f"{T:.2f}s -> {t0:.2f}s; now run snap on {a.out}, render, check, re-transcribe")


def cmd_check(a):
    import numpy as np
    e = load(a.edl); segs = sorted(e["segments"], key=lambda s: s["start"]); res = []
    L = [round(s["end"] - s["start"], 2) for s in segs]
    longs = [(s["start"], l) for s, l in zip(segs, L) if l > 4.5 and not str(s["src"]).endswith(".mp4")]
    res.append(("WARN" if longs else "PASS", f"{len(segs)} shots, median {sorted(L)[len(L) // 2]:.2f} s; stills over 4.5 s: {longs or 'none'}"))
    key = lambda s: (s.get("w"), s.get("x"), s.get("y"))
    res.append(("WARN" if any(key(x) == key(y) for x, y in zip(segs, segs[1:])) else "PASS", "cutout placement changes every shot"))
    dr = sum(1 for s in segs if s.get("drag")) / len(segs)
    res.append(("PASS" if dr >= 0.3 else "WARN", f"drag shots {dr:.0%} (want >= 30%)"))
    low = [s["start"] for s in segs if "w" in s and s["y"] + round(s["w"] * 16 / 9) > H - BOTTOM_GAP]
    res.append(("FAIL" if low else "PASS", f"cutout touching the bottom: {low or 'none'}"))
    raw = subprocess.run(["ffmpeg", "-v", "error", "-i", a.video, "-ac", "1", "-ar", "16000", "-f", "f32le", "-"], capture_output=True).stdout
    x = np.frombuffer(raw, dtype=np.float32); h = 160; n = len(x) // h
    db = 20 * np.log10(np.sqrt(np.mean(x[:n * h].reshape(n, h) ** 2, axis=1) + 1e-12) / (np.abs(x).max() + 1e-9))
    loud = [round(s["start"], 2) for s in segs[1:] if db[max(0, int(s["start"] * 100) - 1):int(s["start"] * 100) + 2].max() > -35]
    res.append(("FAIL" if loud else "PASS", f"cuts on speech (run snap): {loud or 'none'}"))
    err = subprocess.run(["ffmpeg", "-i", a.video, "-af", "ebur128", "-vn", "-f", "null", "-"], capture_output=True, text=True).stderr
    li = re.findall(r"I:\s+(-?[\d.]+) LUFS", err)
    if li:
        res.append(("PASS" if abs(float(li[-1]) - e.get("loudness", -14)) <= 1.5 else "WARN", f"loudness {li[-1]} LUFS"))
    err = subprocess.run(["ffmpeg", "-i", a.video, "-vf", "blackdetect=d=0.1:pix_th=0.10", "-an", "-f", "null", "-"], capture_output=True, text=True).stderr
    bl = re.findall(r"black_start:([\d.]+)", err); res.append(("WARN" if bl else "PASS", f"black frames {bl or 'none'}"))
    res.append(("PASS", f"duration {dur(a.video):.2f} s"))
    for s, m in res:
        print(f"{s:4}  {m}")


def cmd_contact(a):
    from PIL import Image
    tmp = tempfile.mkdtemp()
    if a.src.endswith(".json"):
        e = load(a.src); root = os.path.dirname(os.path.abspath(a.src))
        video = os.path.join(root, e.get("out", "out.mp4")); times = [(s["start"] + s["end"]) / 2 for s in sorted(e["segments"], key=lambda s: s["start"])]
    else:
        video = a.src; d = dur(video); times = [d * (i + 0.5) / 8 for i in range(8)]
    ims = []
    for i, t in enumerate(times):
        p = os.path.join(tmp, f"{i}.jpg"); ff("-ss", f"{t:.2f}", "-i", video, "-frames:v", "1", "-vf", "scale=270:-2", p); ims.append(Image.open(p))
    cols = min(len(ims), 8); rows = math.ceil(len(ims) / cols); w, h = ims[0].size
    sheet = Image.new("RGB", (cols * w, rows * h), "white")
    for i, im in enumerate(ims):
        sheet.paste(im, ((i % cols) * w, (i // cols) * h))
    sheet.save(a.out, quality=85); print("wrote", a.out)


# ---------------------------------------------------------------- finish (Arcads title + captions)
TITLE = {"style": "insta-dark", "fontSize": 18, "position": "top", "textAlign": "center", "margin": {"top": 0.1, "left": 0.1, "right": 0.1}}
CAPS = {"style": "tiktok-none", "maxWordsPerSegment": 4}


def cmd_prep(a):
    edl_path = os.path.abspath(a.edl); d0 = os.path.dirname(edl_path); e = load(edl_path)
    e["overlays"] = []; e["out"] = f"{a.name}_notitle.mp4"
    tmp = os.path.join(d0, "edl.finish.json"); save(e, tmp); out = cmd_render(a, tmp); d = dur(out)
    cues = load(a.cues); bad = [c for c in cues if c["endSeconds"] > d + 0.05]
    if bad:
        sys.exit(f"cues past the end of the render ({d:.2f} s): {bad[:2]}")
    slug = re.sub(r"[^a-z0-9]+", "_", a.name.lower()).strip("_")
    proj = {"projectId": a.project} if a.project else {}
    calls = {"call_1_arcads_add_text_overlay": {"mediaPath": out, "mediaType": "video", "text": a.title, "start": 0, "duration": a.title_dur,
                                                **TITLE, "productId": a.product, **proj, "title": slug + "_title"},
             "call_2_arcads_add_subtitles": {"sourceVideoAssetId": "<asset id from call 1>", **CAPS, "segments": cues,
                                             "productId": a.product, **proj, "title": slug},
             "then": f'python csa.py fetch "<downloadUrl of call 2>" --name "{a.name}" --edit-dir "{d0}"'}
    save(calls, os.path.join(d0, "finish_calls.json")); print(f"render {out} ({d:.2f} s); wrote finish_calls.json")


def cmd_fetch(a):
    d0 = os.path.abspath(a.edit_dir); final = os.path.join(d0, f"{a.name}.mp4")
    urllib.request.urlretrieve(a.url, final); d = dur(final)
    for t, n in ((1.0, "check_title.jpg"), (d / 2, "check_caption.jpg")):
        ff("-ss", f"{t:.2f}", "-i", final, "-frames:v", "1", "-vf", "scale=540:-2", os.path.join(d0, n))
    with open(os.path.join(os.path.dirname(d0), "NOTES.md"), "a", encoding="utf-8") as f:
        f.write(f"\n- {datetime.date.today()}: final `{a.name}.mp4` ({d:.1f} s)\n")
    print(f"final {final} ({d:.2f} s); look at check_title.jpg and check_caption.jpg")


def main():
    ap = argparse.ArgumentParser(); sp = ap.add_subparsers(dest="cmd", required=True)
    sp.add_parser("deps")
    p = sp.add_parser("quote"); p.add_argument("--clips", type=float, nargs="+", required=True); p.add_argument("--images", type=int, default=0)
    p = sp.add_parser("capture"); p.add_argument("url"); p.add_argument("out_dir"); p.add_argument("--seconds", type=float, default=6)
    p.add_argument("--max-scroll", type=int, default=2400); p.add_argument("--browser", default="chrome", choices=["chrome", "chromium"])
    p = sp.add_parser("html"); p.add_argument("html"); p.add_argument("out"); p.add_argument("--dark", action="store_true")
    p.add_argument("--browser", default="chrome", choices=["chrome", "chromium"])
    p = sp.add_parser("annotate"); p.add_argument("src"); p.add_argument("out"); p.add_argument("--find", required=True)
    p.add_argument("--mark", default="both", choices=["highlight", "circle", "both"]); p.add_argument("--browser", default="chrome", choices=["chrome", "chromium"])
    p = sp.add_parser("words"); p.add_argument("media"); p.add_argument("out")
    p = sp.add_parser("cues"); p.add_argument("out"); p.add_argument("specs", nargs="+")
    for c in ("layout", "snap", "render"):
        p = sp.add_parser(c); p.add_argument("edl")
    p = sp.add_parser("tighten"); p.add_argument("edl"); p.add_argument("out")
    p = sp.add_parser("check"); p.add_argument("edl"); p.add_argument("video")
    p = sp.add_parser("contact"); p.add_argument("src"); p.add_argument("out")
    p = sp.add_parser("prep"); p.add_argument("edl"); p.add_argument("--title", required=True); p.add_argument("--cues", required=True)
    p.add_argument("--name", required=True); p.add_argument("--title-dur", type=float, default=3.5)
    p.add_argument("--product", required=True); p.add_argument("--project", default=None)
    p = sp.add_parser("fetch"); p.add_argument("url"); p.add_argument("--name", required=True); p.add_argument("--edit-dir", default=".")
    a = ap.parse_args()
    globals()["cmd_" + a.cmd](a)


if __name__ == "__main__":
    main()
```
