#!/usr/bin/env python3
"""Shared FastH3 Omni prompt builder for the overnight RestoreBunny reels.

Same cast, wardrobe and world as The Argument; exaggerated articulation spec from the 1x run:
wide open mouths on stressed vowels, visible jaw/lip/tongue shaping, brows that leap and knit,
eyes wide then squint, head tilts and shoulder swings, one or two sharp poses then a hold.
"""
import json, pathlib

REELS = pathlib.Path("/Users/sarthakrawool/Documents/Agency/products/restorebunny/reels")
OMNI = pathlib.Path("/Users/sarthakrawool/omni-test")

WHO = {
    "priya": (
        "Priya",
        "a mature adult woman in her late thirties with a soft rounded face, warm brown skin, "
        "shoulder-length wavy black hair, a plain teal raincoat over a plain cream top, dark trousers",
        "a warm low-pitched American woman in her late thirties with a dry, quick voice",
    ),
    "sam": (
        "Sam",
        "a middle-aged adult man in his early fifties with a soft rounded face, light-brown skin, "
        "short grey-flecked hair, a plain olive jacket over a plain white shirt, dark jeans",
        "a blunt American man in his early fifties with a quick, skeptical mid-low voice",
    ),
    "nan": (
        "Nan",
        "an elderly 74-year-old grandmother with a soft rounded face, deep smile lines, warm brown skin, "
        "silver hair in a loose braid, a plain soft lavender cardigan over a plain grey dress",
        "a soft American grandmother in her seventies with a slow, warm, amused voice",
    ),
}

STYLE = (
    "A stylised 3D animated feature film shot, vertical 9:16 frame: Pixar-style clean smooth cartoon grown-ups on adult proportions, "
    "soft rounded oval faces and big round eyes, natural moderately rich colour, warm skin against a softly blurred room, strong contrast with deep soft shadows. "
    "Big theatrical acting: wide mouths that open clearly on every stressed vowel, visible teeth and tongue shaping, strong jaw drops and lip rounds as each word lands, "
    "eyebrows that leap and knit, eyes that go wide then squint, heads that tilt and shoulders that swing with the beat. "
    "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 bright kitchen in the morning: a kettle coming up, birds outside, close natural voices.",
    "kitchen_night": "A quiet kitchen at night: a fridge hum, a clock, close hushed voices.",
}

PROPS = {"faded": "prop_faded.png", "stylised": "prop_stylised.png"}
PLATES = {"kitchen_day": "plate_kitchen_day.png", "kitchen_night": "plate_kitchen_night.png"}
ENVF = {"kitchen_day": "plate_kitchen_day.png", "kitchen_night": "plate_kitchen_night.png"}


def build(reel, gen):
    gid, loc, people, props, action, line, speaker = gen
    remote = f"{OMNI}/{reel}"
    refs, n, tags, role_lines = {}, 0, {}, []
    for p in people:
        n += 1
        refs[f"ref_picture_{n}"] = f"{remote}/refs/{p}_sheet.png"
        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/{ENVF[loc]}"
    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("The photo print is exactly the one in <Picture %d>." % 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 p == speaker
    )
    said = f"(S{people.index(speaker) + 1}) says: <d>[English] {line}</d>"
    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": 7,
        "inputs": refs,
        "output": f"{remote}/clips/{gid}.mp4",
        "params": {"mode": "adaptive", "x2": False, "dense": True},
        "width": 704,
        "height": 1280,
    }


def write_reel(reel, gens):
    out = REELS / reel / "prompts" / "omni"
    out.mkdir(parents=True, exist_ok=True)
    for g in gens:
        job = build(reel, 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(f"{reel}: {len(gens)} jobs")
