import os, base64, time, requests, json
from pathlib import Path

ROOT = Path(r"C:\Users\Usuario\Downloads\SD")
OUT = ROOT / "Output" / "test_momo_cosplay5"
OUT.mkdir(parents=True, exist_ok=True)

MASTER = ("masterpiece, best quality, highly detailed, sharp focus, very aesthetic, very awa, "
          "detailed background, score_9, score_8_up, <lora:IFL_v1.0_IL:0.7> <lora:add-detail-xl:0.5> "
          "<lora:blackwhiplash(bwl)-guy90-Illust-Lorav3:0.6> blaash, <lora:scara2b_ill_v1.00:0.7> scara2b-style, "
          "<lora:Add_color_ILXLv1:3>, 1girl, solo")
CHAR = "<lora:ayase_momo-koto-Illustrious v01:0.8> ayasemomo, hair between eyes, crossed bangs, green earrings, brown hair, red eyes, short hair, half naked"
COSPLAY = "cosplay, bat_print, pantyhose, jewelry, earrings, black_choker, leotard, animal_print, print_pantyhose, choker, purple_pantyhose, bare_shoulders, covered_navel, sky, black_leotard, clothing_cutout"
BASE_POSE = COSPLAY  # placeholder, will be overridden

variants = [
    ("base", "standing, hand on hip, weight on one leg, arched back, chest forward, confident expression, outdoors, night, moon, sky"),
    ("doggystyle", "doggystyle, all_fours, arched spine, hips raised, from behind, penetration, open mouth, blush, looking back, outdoors, night, moon, sky, saliva, pre-cum"),
    ("mating_press", "mating press, knees to chest, legs up, deep penetration, arched back, open mouth, blush, outdoors, night, moon, sky, saliva"),
    ("suspended_congress", "suspended congress, airborne, held in arms, suspension during sex, weightless, open mouth, blush, outdoors, night, moon, sky, saliva"),
    ("cowgirl", "cowgirl position, straddling, riding, bouncing, hands on partner's shoulders, open mouth, blush, outdoors, night, moon, sky, saliva, pre-cum"),
]

NEG = ("lowres, bad anatomy, bad hands, error, missing fingers, extra digit, fewer digits, cropped, worst quality, "
       "low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry, artist name, bad feet, "
       "multiple views, splits, 2girls, extra people, duplicate_character, cloned_character, similar_character, "
       "ugly, deformed, disfigured, mutation, mutated, extra_limbs, extra_arms, extra_legs, fused_fingers, "
       "long_neck, cross-eyed, censored, mosaic censoring, bar censor, mirror, reflection, mirrored, glass_reflection, "
       "reflective_surface")

API = "http://127.0.0.1:7860/sdapi/v1/txt2img"
manifest = []
for idx, (name, extra) in enumerate(variants, 1):
    # structure: MASTER BREAK char, half naked BREAK cosplay (reduced) BREAK pose tags
    prompt = f"{MASTER} BREAK {CHAR} BREAK {COSPLAY} BREAK {extra}"
    payload = {
        "prompt": prompt,
        "negative_prompt": NEG,
        "width": 832,
        "height": 1216,
        "steps": 28,
        "sampler_name": "DPM++ 2M Karras",
        "cfg_scale": 7,
        "seed": -1,
        "batch_size": 1,
        "n_iter": 1,
        "override_settings": {"CLIP_stop_at_last_layers": 2},
    }
    print(f"[{idx}/{len(variants)}] {name} -> generating (seed=-1, cosplay BREAK pose)...")
    try:
        r = requests.post(API, json=payload, timeout=300)
        r.raise_for_status()
        data = r.json()
        b64 = data["images"][0]
        if "," in b64:
            b64 = b64.split(",", 1)[1]
        info = data.get("info", "")
        real_seed = None
        try:
            info_json = json.loads(info)
            real_seed = info_json.get("seed")
        except Exception:
            import re
            m = re.search(r'"seed":\s*(\d+)', info)
            if m:
                real_seed = int(m.group(1))
        if real_seed is None:
            real_seed = "unknown"
        out_path = OUT / f"momo_cosplay5_{idx:02d}_{name}_s{real_seed}.png"
        out_path.write_bytes(base64.b64decode(b64))
        print(f"  OK -> {out_path.name} (seed={real_seed})")
        manifest.append({"file": out_path.name, "name": name, "seed": real_seed, "prompt": prompt})
    except Exception as e:
        print(f"  ERROR: {e}")
    time.sleep(1)

(OUT / "manifest.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False), encoding="utf-8")
print("DONE")