#!/usr/bin/env python3
"""FastH3 Omni shot jobs for "The only photo" (RestoreBunny Snaptoon, 9:16).

Every shot gets reference pictures: the character sheet of each person in it (4-panel Z-Image sheets),
the location plate, and the photo prop when it is on screen. Each <Picture N> is given exactly one role.
Character and voice description lines are identical in every shot.
Settings = the Omni quality-test low-memory preset (same picture as 8-bit in the tests): 4-bit adaptive, native size, dense attention, refs 1 MP.
Environment: one Z-Image plate per shot (make_shot_envs.py).

usage: build_omni.py [--remote-dir ~/omni-test/rb]   -> prompts/omni/<gen>.json + prompts/omni/<gen>.txt
"""
import json
import pathlib
import sys

HERE = pathlib.Path(__file__).parent
REMOTE = "/Users/sarthakrawool/omni-test/rb"
if "--remote-dir" in sys.argv:
    REMOTE = sys.argv[sys.argv.index("--remote-dir") + 1]

SHEETS = {"nina": "nina_sheet.png", "greg": "greg_sheet.png", "dad": "dad_sheet.png", "mom": "mom_sheet.png"}
PLATES = {"kitchen_day": "plate_kitchen_day.png", "kitchen_night": "plate_kitchen_night.png", "living_xmas": "plate_living_xmas.png"}
PROPS = {"faded": "prop_faded.png", "restored": "prop_restored.png"}

WHO = {
    "nina": ("Nina", "a 45-year-old woman with shoulder-length curly dark-brown hair, reading glasses pushed up on her head, a mustard-yellow cardigan over a white T-shirt with a small green rabbit pin on the left chest, dark jeans",
             "an American woman in her mid forties with a warm, dry, quick-witted voice and a relaxed Midwestern accent, mid pitch"),
    "greg": ("Greg", "her older brother, a stocky balding man with grey-brown sides and stubble, a navy quarter-zip pullover, khaki trousers and a black smartwatch",
             "an American man in his late forties with a loud, smug, know-it-all voice and a Chicago accent, low-mid pitch"),
    "dad": ("Dad", "their father, a tall thin 75-year-old man with white hair, bushy white eyebrows, big ears, a red plaid flannel shirt with brown suspenders and grey trousers",
            "an American man in his mid seventies with a slow, gravelly, gentle voice and a Midwestern accent, low pitch"),
    "mom": ("Mom", "their mother, a short plump 71-year-old woman with a white curly perm, round glasses, a coral top and pearl earrings",
            "an American woman in her early seventies with a bright, cheeky, matter-of-fact voice and a Midwestern accent, mid-high pitch"),
}

STYLE = ("A stylised 3D animated feature film shot, vertical 9:16 frame: clean smooth cartoon characters with big round eyes and small mouths, "
         "natural moderately rich colour, warm skin against a softly blurred room, strong contrast with deep soft shadows. "
         "Snap-and-hold acting: each character moves in one or two quick sharp poses, then holds almost still. "
         "The characters look at each other while they talk, never into the camera. Everyone speaks fast in quick natural sentences, "
         "each speaker jumping in the moment the other finishes.")

SOUND = {
    "kitchen_day": "A quiet family kitchen in the morning: a fridge hum, a clock ticking, close natural voices.",
    "kitchen_night": "A quiet kitchen late at night: soft room tone, a laptop fan, close hushed voices.",
    "living_xmas": "A warm living room on Christmas morning: wrapping paper rustling, a soft crackle, close natural voices.",
}

# gen, location, people (in order), props on screen, camera + action text, lines [(who, words)]
GENS = [
    ("g01", "kitchen_day", ["greg", "nina"], ["faded"],
     "Medium two-shot. Greg stands by the blue recycling bin and snaps upright holding up the faded grey photo print from <PROP faded> in one hand, "
     "glaring at Nina. Nina, at the counter with a coffee mug, turns her head to him and shrugs. The camera rushes in quickly at the start, then holds.",
     [("greg", "Why is Dad's only photo of Grandma in the recycling bin?"),
      ("nina", "Because it's completely faded, Greg. You can't even see her face.")]),
    ("g02", "kitchen_day", ["dad", "nina", "greg"], ["faded"],
     "Medium close-up favouring Dad: Dad, tall and as big in frame as Nina, stands in the foreground on the right at the edge of the kitchen holding a mug, "
     "looking down at the faded print from <PROP faded> in Greg's hand. Nina, on the left, freezes, then turns to Dad, her face falling. "
     "Greg stands slightly behind them holding the print, looking down at it, guilty. Slow push-in on Dad's face while he speaks.",
     [("dad", "Nina, that's the only picture I've got of my mother."),
      ("nina", "Oh no, Dad. I'm so sorry. I'll fix it, I promise.")]),
    ("g03", "kitchen_night", ["greg", "nina"], ["faded"],
     "Night. Nina sits at the kitchen table under the pendant lamp; the faded print from <PROP faded> lies flat on the table top right in front of her hands. Greg leans on the table "
     "beside her, arms crossed, skeptical. Nina pulls a plain silver laptop with a smooth blank lid toward herself with both hands. The camera holds, then pushes in a little.",
     [("greg", "Fix it how? It's a grey square, and Christmas is tomorrow."),
      ("nina", "Then I've got one night. Pass me my laptop.")]),
    ("g04", "kitchen_night", ["nina", "greg"], ["restored"],
     "Night, over-the-shoulder from behind the laptop. The laptop screen faces the camera and shows the restored photo from <PROP restored>, sharp and clean, "
     "one rigid flat screen that stays the same. Nina, beside the laptop, points at the screen; Greg leans in close behind her, eyes going wide.",
     [("nina", "Okay, RestoreBunny's done. Look at the screen."),
      ("greg", "She's holding a baby. Dad always said he was the oldest.")]),
    ("g05", "kitchen_night", ["nina", "mom"], ["restored"],
     "Night. Mom has come into the kitchen in the lamp light. Nina turns the plain silver laptop with its smooth blank lid toward her; the screen shows the restored photo from <PROP restored>. "
     "Mom puts a hand on her chest, softens, and smiles a knowing smile. Medium two-shot that holds.",
     [("nina", "Mom, who's the baby in Grandma's arms?"),
      ("mom", "Oh, honey. Wrap that up and give it to your father.")]),
    ("g06", "living_xmas", ["dad", "mom"], ["restored"],
     "Christmas morning by the tree. Dad sits on the sofa holding an unwrapped wooden picture frame in both hands, the restored photo from <PROP restored> inside it, "
     "facing the camera. His eyes fill with tears. Mom sits beside him with a hand on his shoulder. Slow push-in on Dad's face.",
     [("dad", "That's my mother. And she's holding my big brother, Tommy."),
      ("mom", "Bill, nobody kept a single photo of him.")]),
    ("g07", "living_xmas", ["dad", "nina", "greg"], ["restored"],
     "Christmas morning. Dad holds the framed restored photo from <PROP restored> to his chest and looks up at Nina with a wet smile; Nina beams. "
     "Greg, standing behind them, snaps up a small wrapped present and pulls out a pair of grey socks, holding them up hopefully. The camera holds wide, then nudges in on Greg.",
     [("dad", "Seventy years, and I finally get to see his face."),
      ("greg", "Cool. So is anybody opening my socks?")]),
]


SEEDS = {"g03": 21, "g02": 21}


def build(gen):
    gid, loc, people, props, action, lines = gen
    refs, n = {}, 0
    tags = {}
    role_lines = []
    for p in people:
        n += 1; refs[f"ref_picture_{n}"] = f"{REMOTE}/refs/{SHEETS[p]}"; tags[p] = n
        name, look, _ = WHO[p]
        role_lines.append(f"{name} is the character in <Picture {n}> (face close-up, then outfit from front, back and side): {look}.")
    n += 1; refs[f"ref_picture_{n}"] = f"{REMOTE}/env/env_{gid}.png"
    role_lines.append(f"The room and camera view are the ones shown in <Picture {n}>.")
    for pr in props:
        n += 1; refs[f"ref_picture_{n}"] = f"{REMOTE}/refs/{PROPS[pr]}"; tags["PROP " + pr] = n
        role_lines.append(f"The photo print is exactly the one in <Picture {n}>.")
    act = action
    for k, v in tags.items():
        act = act.replace(f"<{k}>", f"<Picture {v}>")
    voices = " ".join(f"{WHO[p][0]} speaks with {WHO[p][2]}." for p in people if any(w == p for w, _ in lines))
    said = " ".join(f"({'S' + str(people.index(w) + 1)}) says: <d>[English] {t}</d>" for w, t in lines)
    speakers = " ".join(f"S{people.index(p) + 1} is {WHO[p][0]}." for p in people)
    prompt = (f"integrated_multimodal_description: [Shot 1] {STYLE} " + " ".join(role_lines) + f" {act} {speakers} {voices} {said}\n"
              f"overall_soundscape: {SOUND[loc]}\nnon_diegetic_music: N/A")
    return {"model": "fasth3-omni-8step-4bit", "prompt": prompt, "frames": 124, "seed": SEEDS.get(gid, 7), "inputs": refs,
            "output": f"{REMOTE}/clips/{gid}.mp4", "params": {"mode": "adaptive", "x2": False, "dense": True},
            "width": 704, "height": 1280}


out = HERE / "prompts" / "omni"; out.mkdir(parents=True, exist_ok=True)
for g in GENS:
    job = build(g)
    (out / f"{g[0]}.json").write_text(json.dumps(job, indent=1))
    (out / f"{g[0]}.txt").write_text(job["prompt"] + "\n\nrefs:\n" + "\n".join(f"{k}: {v}" for k, v in job["inputs"].items()) + "\n")
print(len(GENS), "jobs ->", out)
