#!/usr/bin/env python3
"""W2 Turnaround 放量批 — 8 锁区 × v14 五列整板单发 (Kai 1020 定谳: B线换道 + 顺色修复 + 补背面)
126 已有试点 tr_pilot_126_v14_gray5.png, 本批补齐其余 8 锁区.
配方: qwen21 t2i 2752x1536 · 中灰底强对比 · Col1近身正/Col2全身正/Col3 45°/Col4侧/Col5背 · seed=combo_id
"""
import json, time, os, urllib.request

ROOT = "/home/kai/shared/virtual-idol/week1"
OUT = f"{ROOT}/W2_lockup/tr_v14"
os.makedirs(OUT, exist_ok=True)
LEDGER = open(f"{ROOT}/manifest/w2_lockup_ledger.jsonl", "a")

LOCKED = [
    (66,  "A3", "B2", "C1"),
    (90,  "A3", "B6", "C5"),
    (102, "A4", "B3", "C2"),
    (121, "A5", "B1", "C1"),
    (125, "A5", "B1", "C5"),
    (140, "A5", "B4", "C5"),
    (186, "A7", "B2", "C1"),
    (191, "A7", "B3", "C1"),
]
AXIS = {
    "A3": "short asymmetric bob with neon underglow",
    "A4": "traditional Chinese updo with mechanical hairpins",
    "A5": "waist-length straight black hair dissolving into glowing data particles at the tips",
    "A7": "shaved sides with a long braided topknot",
    "B1": "reimagined hanfu with holographic translucent layers, crossed collar and wide water-sleeves, jade-white and gold color scheme",
    "B2": "white ceremonial robe with dark circuit-line embroidery and jade-cyan bioluminescence accents",
    "B3": "tech-wear qipao with LED piping",
    "B4": "flowing ink-painting dress, fabric made of light",
    "B6": "armored opera costume, porcelain-textured plates with gold-leaf accents",
}

def led(rec):
    rec["ts"] = time.time()
    LEDGER.write(json.dumps(rec, ensure_ascii=False) + "\n"); LEDGER.flush()

def gen(cid, prompt):
    out = f"{OUT}/tr_v14_{cid:03d}.png"
    body = json.dumps({"prompt": prompt, "seed": cid, "width": 2752, "height": 1536}).encode()
    req = urllib.request.Request("http://127.0.0.1:10588/api/production/qwen21/generate", data=body,
        headers={"Content-Type": "application/json"})
    t0 = time.time()
    with urllib.request.urlopen(req, timeout=900) as r:
        j = json.load(r)
    img = j["data"]["images"][0]
    src = (img.get("url") or "").replace("localhost", "127.0.0.1")
    urllib.request.urlretrieve(src, out)
    led({"event": "gen", "phase": "W2-tr-v14", "asset_id": f"tr_v14_{cid:03d}", "engine": "qwen21",
         "mode": "t2i", "seed": cid, "final_prompt": prompt, "output_path": out,
         "elapsed": round(time.time()-t0, 1), "status": "ok"})
    return out

ok = fail = 0
for cid, a, b, c in LOCKED:
    prompt = (
        "Professional character turnaround reference sheet. Plain darker medium-gray studio background (mid-gray #8a8a8a), "
        "even soft lighting, subtle floor shadow, STRONG value contrast between the costume and the background, "
        "crisp silhouette edge separation, the costume must never blend into the background. "
        f"The SAME character in ALL five columns: a young Eastern female singer, unconventional non-standard beauty, "
        f"ethereal sci-fi oriental aesthetic, {AXIS[a]}, wearing {AXIS[b]}. "
        "Semi-realistic illustration, realistic skin shading and fine fabric weave texture. "
        "Column 1: upper-body close-up, FRONT view facing camera (head to waist). "
        "Column 2: FULL BODY front view facing camera, complete head to toe. "
        "Column 3: FULL BODY three-quarter view turned 45 degrees to the right, same turning direction as the previous column. "
        "Column 4: FULL BODY side profile turned 90 degrees to the right, same turning direction as the previous column. "
        "Column 5: FULL BODY BACK view showing the back of the costume and the hair from behind. "
        "Thin white separator lines between columns, even spacing, identical figure height. "
        "No text, no watermark.")
    print(f"[{time.strftime('%H:%M:%S')}] RUN tr_v14_{cid:03d} ({a}/{b}/{c})")
    try:
        out = gen(cid, prompt)
        print(f"  OK {out} {os.path.getsize(out)//1024}KB")
        ok += 1
    except Exception as e:
        print(f"  FAIL {cid}: {str(e)[:200]}")
        led({"event": "gen", "phase": "W2-tr-v14", "asset_id": f"tr_v14_{cid:03d}", "status": "fail", "err": str(e)[:200]})
        fail += 1
print(f"TR_V14_DONE ok={ok} fail={fail}")
