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

ROOT = Path(r"C:\Users\Usuario\Downloads\SD")
BASE = ROOT / "_sandbox_cl_tagger" / "Momo Ayase 102"
HARVEST = BASE / "harvest" / "por_imagen.txt"
OUT = ROOT / "Output" / "test_momo_outfit"
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"
OUTFIT = "playboy_bunny, leotard, black_leotard, wrist_cuffs, bow, bowtie, areola_slip, blush, detached_collar, black_bowtie, strapless_leotard, bare_shoulders, covered_navel, strapless, highleg"
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")

# Scenes by group
scenes_outdoor_night = ["outdoors, night, night_sky, moon, sky"] * 6
scenes_indoor = ["indoors, bed, pillow"] * 6
scenes_varied = ["beach, ocean, day", "outdoors, day, sky", "indoors, desk, flower", "snow, outdoors",
                 "indoors, bathtub, water, tile_wall", "outdoors, night, moon", "indoors, window, desk", "beach, ocean, sunset"]
scenes = scenes_outdoor_night + scenes_indoor + scenes_varied

cams = ["pov", "ass_focus", "from_behind", "cowboy_shot", "full_moon", "from_below"]

# Parse harvest
entries = []
lines = HARVEST.read_text(encoding="utf-8").splitlines()
i = 0
while i < len(lines):
    if ".txt" in lines[i] and not lines[i].startswith("#"):
        img = lines[i].split()[0]
        tags = lines[i+1].strip() if i+1 < len(lines) else ""
        entries.append((img, tags))
        i += 2
    else:
        i += 1

sel = entries[:20]
print(f"Selected {len(sel)} entries")

API = "http://127.0.0.1:7860/sdapi/v1/txt2img"
for idx, (img, tags) in enumerate(sel, 1):
    scene = scenes[idx-1]
    cam = cams[(idx-1) % len(cams)]
    prompt = f"{MASTER} BREAK {CHAR}, half naked, {OUTFIT} BREAK {tags}, {scene}, {cam}"
    payload = {
        "prompt": prompt,
        "negative_prompt": NEG,
        "width": 832,
        "height": 1216,
        "steps": 28,
        "sampler_name": "DPM++ 2M Karras",
        "cfg_scale": 7,
        "seed": 7000 + idx,
        "batch_size": 1,
        "n_iter": 1,
        "override_settings": {"CLIP_stop_at_last_layers": 2},
    }
    print(f"[{idx}/{len(sel)}] {img} scene={scene} cam={cam} -> generating...")
    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]
        out_path = OUT / f"momo_outfit_{idx:02d}.png"
        out_path.write_bytes(base64.b64decode(b64))
        print(f"  OK -> {out_path.name}")
    except Exception as e:
        print(f"  ERROR: {e}")
    time.sleep(1)

print("DONE")