"""
Test 3 senaryo:
  A) Placeholder (NO PRODUCT) → Llava NO_PRODUCT döner, Gemma sahnede üründen bahsetmez
  B) Gerçek ürün (parfün.png) → Llava tarif eder, Gemma sahneye entegre eder
  C) Türkçe sızıntı kontrolü
"""
import json, urllib.request, base64, time
from io import BytesIO
from PIL import Image

OLLAMA = "http://127.0.0.1:11434"
WF = json.load(open(r"D:\Comfy\App\ComfyUI_windows_portable\ComfyUI\user\default\workflows\FikoYT_MVD_Muhtesem_Video_Merkezi.json","r",encoding="utf-8"))

# Extract live prompts/directives from workflow nodes
llava = next(n for n in WF["nodes"] if n["type"]=="OllamaAPI" and "1/2" in n.get("title",""))
gemma = next(n for n in WF["nodes"] if n["type"]=="OllamaAPI" and "2/2" in n.get("title",""))
concat= next(n for n in WF["nodes"] if n["type"]=="StringConcatenate")

LLAVA_PROMPT = llava["widgets_values"][0]
LLAVA_DIRECTIVE = llava["widgets_values"][6]
GEMMA_DIRECTIVE = gemma["widgets_values"][6]
CONCAT_DELIM = concat["widgets_values"][2]

def call_ollama(model, prompt, image_path=None):
    payload = {"model": model, "prompt": prompt, "stream": False}
    if image_path:
        img = Image.open(image_path).convert("RGB")
        # Resize ürün like LoadAndResizeImage keep_proportion=True target 768
        img.thumbnail((768, 768))
        buf = BytesIO(); img.save(buf, format="PNG")
        payload["images"] = [base64.b64encode(buf.getvalue()).decode()]
    req = urllib.request.Request(f"{OLLAMA}/api/generate",
        data=json.dumps(payload).encode(), headers={"Content-Type":"application/json"})
    t0 = time.time()
    r = json.loads(urllib.request.urlopen(req, timeout=300).read())
    return r.get("response",""), time.time()-t0

def run_pipeline(label, urun_img_path, turkce):
    print(f"\n{'='*60}\nSENARYO: {label}\nÜRÜN: {urun_img_path}\nTÜRKÇE: {turkce[:80]}...\n{'='*60}")

    # Step 1: Llava
    full_llava_prompt = f"{LLAVA_PROMPT}\n\n{LLAVA_DIRECTIVE}"
    llava_out, t1 = call_ollama("llava:13b", full_llava_prompt, urun_img_path)
    print(f"\n[LLAVA {t1:.1f}s]  ({len(llava_out)} chars)")
    print(f"  >>> '{llava_out.strip()[:300]}'")

    # Step 2: Concat
    combined = turkce + CONCAT_DELIM + llava_out

    # Step 3: Gemma
    full_gemma_prompt = f"{combined}\n\n{GEMMA_DIRECTIVE}"
    gemma_out, t2 = call_ollama("gemma4:12b", full_gemma_prompt)
    print(f"\n[GEMMA {t2:.1f}s]  ({len(gemma_out)} chars)")
    print(f"  >>> {gemma_out.strip()}")

    # Analysis
    gemma_lower = gemma_out.lower()
    has_no_product_marker = "NO_PRODUCT" in llava_out
    mentions_product_words = any(w in gemma_lower for w in [
        "perfume","bottle","product","device","item","gadget","package","tablet","phone","watch","jar"
    ])
    turkish_leaks = [w for w in ["sahne","karakter","kafe","ürün","müzik","elinde","akşam"] if w in gemma_lower.split()]
    print(f"\n[ANALİZ]")
    print(f"  Llava NO_PRODUCT marker: {'EVET' if has_no_product_marker else 'HAYIR'}")
    print(f"  Gemma ürün kelimesi geçti: {mentions_product_words}")
    print(f"  Türkçe sızıntı: {turkish_leaks if turkish_leaks else 'YOK ✓'}")
    return {"label":label, "no_product":has_no_product_marker, "product_words":mentions_product_words, "tr_leaks":turkish_leaks}

# --- SENARYO A: Placeholder (no product) ---
results = []
r1 = run_pipeline(
    "A) Ürün VERİLMEMİŞ (placeholder)",
    r"D:\Comfy\App\ComfyUI_windows_portable\ComfyUI\input\fikoyt_mvd_placeholder.png",
    "Sahne: Zekiye kafede oturuyor, kameraya gülümsüyor. Akşam ışığı, lo-fi caz müzik 90 BPM."
)
results.append(r1)

# --- SENARYO B: Real product (parfün.png) ---
import os
real_product = r"D:\Comfy\App\ComfyUI_windows_portable\ComfyUI\input\parfün.png"
if os.path.exists(real_product):
    r2 = run_pipeline(
        "B) Gerçek ürün (parfün.png)",
        real_product,
        "Sahne: Zekiye elinde ürünü dikkatlice tutuyor, kameraya gülümsüyor. Akşam ışığı, lo-fi caz müzik 90 BPM."
    )
    results.append(r2)
else:
    print(f"\n[B atlandı: {real_product} yok]")

# --- ÖZET ---
print(f"\n{'='*60}\nÖZET\n{'='*60}")
for r in results:
    expected_no_product = r["label"].startswith("A")
    pipeline_ok = (r["no_product"] == expected_no_product)
    product_ok  = (r["product_words"] != expected_no_product)  # A: no products mentioned, B: yes
    print(f"{r['label']}")
    print(f"  Llava NO_PRODUCT branch: {'✓' if pipeline_ok else '✗ FAIL'}")
    print(f"  Gemma ürün entegrasyonu doğru: {'✓' if product_ok else '✗ FAIL'}")
    tr_status = "✓" if not r["tr_leaks"] else f"✗ {r['tr_leaks']}"
    print(f"  Türkçe sızıntı yok: {tr_status}")
