#!/usr/bin/env python3
import sys, os, json, time
sys.path.insert(0, "/home/zyw/Downloads/dasiwa-h3-research")
import v18_pipeline as p

BASE = "/home/zyw/Downloads/dl-hub/100-长安Disco-场景图"
CFG = json.load(open(f"{BASE}/20条-配置.json", encoding="utf-8"))
BY = {c["id"]: c for c in CFG}

CAM = {
 "dolly_in": "The camera starts wide and pushes slowly straight in toward her, ending on a medium shot; the move is smooth and continuous, no shake.",
 "orbit": "The camera orbits slowly around her at a constant distance, keeping her centred; one smooth half-circle, no shake.",
 "low_angle": "The camera starts low near the wet ground and tilts up smoothly to her face; the move is one continuous tilt, no shake.",
 "whip_pan": "The camera whips quickly across the scene and lands on her with a short settle; the whip is fast, with motion blur, and stops cleanly.",
 "follow": "The camera follows her movement at a constant distance, tracking smoothly; no shake, no zoom.",
}

def prompt_for(c):
    cam = CAM.get(c["kind"])
    if c["kind"] == "dance":
        cam_line = ("Locked-off wide shot at chest height with a 35mm lens; her whole body including both shoes stays inside the frame at the same size; "
                    "no push-in, no pan, no zoom, no orbit, no handheld shake; both her shoes stay visible at the bottom of the frame and her height in frame never changes.")
    else:
        cam_line = cam + " Her whole body stays inside the frame."
    return f"""subject_definitions:
<Subject 1> is the environment shown in <Picture 1>: {c['scene']}. The place is otherwise empty around her; any visitors stay far in the background.
<Subject 2> is the stylized 3D animated young woman already standing in <Picture 1>, whose face and body come from <Picture 2> and <Picture 3>: long white hair in a high bun, large violet eyes, smooth pale skin; a white embroidered hanfu with wide sleeves and a long skirt, white cloth shoes. She holds nothing in her hands: no props, no fan, no umbrella. She keeps the exact position, distance and height in frame that she has in <Picture 1>.

summary:
[reference generation] A five-second widescreen clip in which <Subject 2> {('dances a ' + c['move']) if c['kind']=='dance' else ('is shown with a ' + c['move'] + ' camera move')} in front of <Subject 1>; the scene, her face and her white hanfu stay exactly as referenced.

retention_analysis:
<Subject 1> (appears in [Shot 1]): fully_preserved - the architecture, lanterns, lights and pavement keep the positions, scale and colour of <Picture 1>.
<Subject 2> (appears in [Shot 1]): fully_preserved - her white hair, violet eyes, white embroidered hanfu, wide sleeves, long skirt and white shoes stay identical to the references.

detailed_description:
[Shot 1] 0.00s-5.00s. {cam_line} <Subject 2> stands on the pavement, small against the wide scene. {c['desc']}. The light stays as in <Picture 1>: warm lanterns against the night, soft reflections on the ground.

overall_soundscape:
Night ambience: a low distant murmur of visitors, a faint breeze moving fabric, and the soft sound of her shoes and sleeves.

non_diegetic_music:
Mid-tempo disco at about 118 BPM: a steady four-on-the-floor kick, an octave-jumping bass line, crisp offbeat hi-hats and short string stabs; instrumental, no vocals.
"""

def run(cid, seed=20261018):
    c = BY[cid]
    prompt = prompt_for(c)
    open(f"{BASE}/h3/prompts-20/{cid}.txt", "w").write(prompt) if os.path.isdir(f"{BASE}/h3/prompts-20") else None
    res = p.run_pipeline(
        image_path=f"{BASE}/{c['plate']}",
        requirement=f"白发少女在白金汉服，在{ c['scene'][:20] }前跳舞/运镜（{cid}）",
        prompt_override=prompt,
        extra_images=[f"{BASE}/人物参考/白发-全身正面.jpg", f"{BASE}/人物参考/白发-面部正面.jpg"],
        width=1152, height=648, duration=5, seed=seed, steps=8, fps=24.0,
        topic=f"长安20条-{cid}", variant=c["kind"],
    )
    return res

if __name__ == "__main__":
    os.makedirs(f"{BASE}/h3/prompts-20", exist_ok=True)
    ids = sys.argv[1:]
    if ids == ["ALL"]:
        ids = [c["id"] for c in CFG]
    for cid in ids:
        t0 = time.time()
        try:
            r = run(cid)
            print(f"OK {cid} {time.time()-t0:.0f}s {r['video_local']}", flush=True)
        except Exception as e:
            print(f"FAIL {cid} {e}", flush=True)
