import json, time, os, urllib.request, urllib.parse, urllib.error

API="http://192.168.31.31:8189"
OUT=os.path.dirname(os.path.abspath(__file__))
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}))

ZH=("国风仙侠人物插画，一位少女剑仙亭亭立于云端石台：乌黑长发挽成双髻，缀白玉簪与红绳，齐刘海，眉眼清亮，唇色樱红，"
    "身着青白渐变的齐胸襦裙与薄纱外披，腰束朱红长绦，袖口领缘绣银线云雷纹，足踏白绫靴；"
    "右手并指作剑诀，左手斜挽一柄长剑，剑身泛冷青辉、剑穗垂朱缨。"
    "背景是云雾翻涌的黛青群山、飞瀑与苍松，逆光穿破云海洒下丁达尔光柱，衣袂与发丝被山风扬起，几片桃瓣与光尘悬浮。"
    "电影级布光，低饱和青绿主调点缀朱红，胶片颗粒，超细发丝与轻纱织物质感，居中偏三分构图，浅景深，4K 细节，全年龄向角色设计。")
EN=("Chinese xianxia character illustration: a young sword immortal standing on a stone terrace above a sea of clouds, "
    "black hair in twin buns with a white jade hairpin and red cord, straight bangs, bright clear eyes, cherry lips, "
    "wearing a celadon-and-white gradient chest-wrap hanfu with a sheer outer robe, crimson sash, silver cloud-and-thunder embroidery on cuffs and collar, white silk boots; "
    "right hand forming a sword mudra, left hand holding a long sword with a cold cyan glow and a crimson tassel. "
    "Background: misty indigo mountains, a waterfall, ancient pines, backlight breaking through the cloud sea in god rays, robes and hair lifted by mountain wind, floating peach petals and light dust. "
    "cinematic lighting, low-saturation celadon palette with crimson accents, film grain, ultra-fine hair and sheer fabric texture, rule-of-thirds composition, shallow depth of field, 4K detail, all-ages character design.")

LORA_SUB=[("krea/krea2-masterpieces-v51.safetensors",0.60),
          ("krea/realism_engine_krea2_v3.1.safetensors",0.40),
          ("krea2_darkbrush.safetensors",0.20),
          ("krea/krea2filterbypass3.safetensors",0.40),
          ("krea/krea2-bloomgirls-realism-step00004000.safetensors",0.30),
          ("krea/snofs_krea_v1_1.safetensors",0.25)]
LORA_ORIG=[("krea/Krea_2_zidiusArt_Melancholy_v2.safetensors",0.60),
           ("krea/cinematic_movie_still_krea2.safetensors",0.20),
           ("krea/krea2_detail_slider.safetensors",0.60),
           ("krea/realism_engine_krea2_v3.1.safetensors",0.50),
           ("krea/krea2-Cc-MJ-影视柔光.safetensors",0.55),
           ("krea/krea2-Cc-MJ-风格滤镜.safetensors",0.60)]
REFUSAL=("krea/refusal_reduction_v2_full_rank.safetensors",0.80)
BAL="1.0,1.0,1.0,1.0,1.0,1.0,1.0,2.5,5.0,1.1,4.0,1.0"
DET="0.8,0.8,0.9,0.9,1.0,1.0,1.2,3.0,6.0,1.5,5.0,1.2"
SEED=88135264906

def build(loras, text, rebal=None, w=1248, h=1664, tag="x"):
    p={"1":{"class_type":"UNETLoader","inputs":{"unet_name":"krea2_turbo_fp8_scaled.safetensors","weight_dtype":"default"}},
       "2":{"class_type":"CLIPLoader","inputs":{"clip_name":"qwen3vl_4b_fp8_scaled.safetensors","type":"krea2"}},
       "3":{"class_type":"VAELoader","inputs":{"vae_name":"qwen_image_vae.safetensors"}}}
    pm,pc="1",("2",0)
    for i,(n,s) in enumerate(loras):
        nid=str(4+i)
        p[nid]={"class_type":"LoraLoader","inputs":{"model":[pm,0],"clip":[pc[0],pc[1]],"lora_name":n,"strength_model":s,"strength_clip":0.0}}
        pm=nid; pc=(nid,1)
    b=4+len(loras)
    p[str(b)]={"class_type":"CLIPTextEncode","inputs":{"clip":[pm,1],"text":text}}
    p[str(b+1)]={"class_type":"ConditioningZeroOut","inputs":{"conditioning":[str(b),0]}}
    pos=str(b)
    if rebal:
        p[str(b+2)]={"class_type":"ConditioningKrea2Rebalance","inputs":{"conditioning":[str(b),0],"multiplier":1.0,"per_layer_weights":rebal}}
        pos=str(b+2)
    p[str(b+3)]={"class_type":"EmptyLatentImage","inputs":{"width":w,"height":h,"batch_size":1}}
    p[str(b+4)]={"class_type":"KSampler","inputs":{"model":[pm,0],"positive":[pos,0],"negative":[str(b+1),0],"latent_image":[str(b+3),0],
                 "seed":SEED,"steps":8,"cfg":1.0,"sampler_name":"euler","scheduler":"simple","denoise":1.0}}
    p[str(b+5)]={"class_type":"VAEDecode","inputs":{"samples":[str(b+4),0],"vae":["3",0]}}
    p[str(b+6)]={"class_type":"SaveImage","inputs":{"images":[str(b+5),0],"filename_prefix":"loli_"+tag}}
    return {"prompt":p,"client_id":"dsh-loli"}

CFG=[
 ("A1-替身6LoRA-条件控制balanced", LORA_SUB,  ZH, BAL, 1248,1664),
 ("A2-原片6LoRA-条件控制balanced", LORA_ORIG, ZH, BAL, 1248,1664),
 ("B1-原片6LoRA-关掉条件控制",     LORA_ORIG, ZH, None,1248,1664),
 ("B2-原片6LoRA-条件控制detail",   LORA_ORIG, ZH, DET, 1248,1664),
 ("C1-原片6LoRA+拒答抑制0.8",      LORA_ORIG+[REFUSAL], ZH, BAL, 1248,1664),
 ("D1-原片6LoRA-英文提示词",       LORA_ORIG, EN, BAL, 1248,1664),
 ("E1-原片6LoRA+拒答-4MP终稿",     LORA_ORIG+[REFUSAL], ZH, BAL, 1776,2368),
]
def post(body):
    req=urllib.request.Request(API+"/prompt", data=json.dumps(body).encode(), headers={"Content-Type":"application/json"})
    return json.load(opener.open(req, timeout=30))

ids=[]
for name,loras,text,rb,w,h in CFG:
    tag=name.split("-")[0].lower()
    r=post(build(loras,text,rb,w,h,tag))
    ids.append((name,r["prompt_id"]))
    print("queued",name,r["prompt_id"], flush=True)

files={}
t0=time.time()
while len(files)<len(ids) and time.time()-t0<1800:
    time.sleep(10)
    for name,pid in ids:
        if name in files: continue
        try:
            d=json.load(opener.open(API+"/history/"+pid, timeout=20))
        except Exception: continue
        if not d: continue
        v=list(d.values())[0]
        st=v.get("status",{}).get("status_str")
        if st=="success":
            for n in (v.get("outputs") or {}).values():
                for im in n.get("images",[]):
                    files[name]=im["filename"]
            print("done",name,files[name], round(time.time()-t0),"s",flush=True)
        elif st=="error":
            files[name]=None
            print("ERROR",name,flush=True)

for name,fn in files.items():
    if not fn: continue
    url=API+"/view?"+urllib.parse.urlencode({"filename":fn,"type":"output","subfolder":""})
    data=opener.open(url, timeout=120).read()
    path=os.path.join(OUT, name+".png")
    open(path,"wb").write(data)
    print("saved",path,len(data),flush=True)
print("ALL DONE", files)
