"""
Batch v4: 1girl solo + negative optimizado
"""
import requests, base64, random, time
from pathlib import Path

FORGE_URL = "http://127.0.0.1:7860"
BASE_DIR = Path(r"C:\Users\Usuario\Downloads\NEW")
OUTPUT = BASE_DIR / "Output" / "batch_ai_v4"

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, age up, mature female,"

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, airship_gondola, mirror, reflection, hothouse"

chars = [l.strip() for l in (BASE_DIR / "Archivos" / "personajes.txt").read_text(encoding="utf-8").splitlines() if l.strip()]
poses = [l.strip() for l in (BASE_DIR / "Archivos" / "wildcards_ai" / "pose_ai.txt").read_text(encoding="utf-8").splitlines() if l.strip()]
scenes = [l.strip() for l in (BASE_DIR / "Archivos" / "wildcards_ai" / "scene_ai_clean.txt").read_text(encoding="utf-8").splitlines() if l.strip()]
outfits = [l.strip() for l in (BASE_DIR / "Archivos" / "wildcards_ai" / "outfit_ai.txt").read_text(encoding="utf-8").splitlines() if l.strip()]

OUTPUT.mkdir(parents=True, exist_ok=True)

def get_char_trigger(char_line):
    if char_line.startswith('<lora:'):
        parts = char_line.split('>', 1)
        if len(parts) > 1:
            return parts[1].strip().split(',')[0].strip()
    return char_line[:30]

print("=" * 55)
print("  BATCH V4: 1girl solo + negative optimizado")
print("=" * 55)

used_chars = set()

for i in range(10):
    available = [c for c in chars if get_char_trigger(c) not in used_chars]
    if not available:
        available = chars
        used_chars.clear()
    
    char = random.choice(available)
    trigger = get_char_trigger(char)
    used_chars.add(trigger)
    
    pose = random.choice(poses)
    scene = random.choice(scenes)
    outfit = random.choice(outfits)

    prompt = f"{MASTER} {char} {outfit} BREAK {pose} BREAK {scene}"
    filename = f"batch_{i+1:02d}.png"
    outpath = OUTPUT / filename

    print(f"\n[{i+1}/10] {filename}")
    print(f"  Trigger: {trigger}")
    print(f"  Outfit: {outfit[:50]}...")
    print(f"  Pose: {pose[:50]}...")

    payload = {
        "prompt": prompt, "negative_prompt": NEG,
        "width": 832, "height": 1216, "steps": 28, "cfg_scale": 6,
        "sampler_name": "DPM++ 2M Karras", "batch_size": 1, "n_iter": 1, "seed": -1, "clip_skip": 2,
    }

    try:
        resp = requests.post(f"{FORGE_URL}/sdapi/v1/txt2img", json=payload, timeout=300)
        if resp.status_code == 200:
            img = base64.b64decode(resp.json()["images"][0])
            with open(outpath, "wb") as f:
                f.write(img)
            print(f"  [OK] {len(img)//1024}KB")
        else:
            print(f"  [FAIL] {resp.status_code}")
    except Exception as e:
        print(f"  [ERROR] {e}")

    time.sleep(2)

print(f"\n{'=' * 55}")
print(f"  COMPLETADO - {OUTPUT}")
print(f"{'=' * 55}")
