import base64, json, sys, urllib.request, urllib.error
from PIL import Image
import io

img_path = sys.argv[1]

# Resize image to reduce vision tokens
im = Image.open(img_path).convert("RGB")
im.thumbnail((768, 768))
buf = io.BytesIO()
im.save(buf, "JPEG", quality=80)
b64 = base64.b64encode(buf.getvalue()).decode()
print(f"[info] resized to {im.size}", file=sys.stderr)

key = open("/home/mantapman/.openrouter_key").read().strip()

prompt = "Deskripsikan gambar ini secara detail dalam Bahasa Indonesia: apa isinya, semua teks yang terlihat, konteks, gaya visual, dan elemen penting. Jawab dalam Bahasa Indonesia."

models = [
    "google/gemini-2.0-flash-exp:free",
    "qwen/qwen-2.5-vl-7b-instruct:free",
    "meta-llama/llama-3.2-11b-vision-instruct:free",
    "mistralai/pixtral-12b:free",
    "google/gemini-2.5-flash-lite:free",
]

for model in models:
    payload = {
        "model": model,
        "messages": [{
            "role": "user",
            "content": [
                {"type": "text", "text": prompt},
                {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64}"}}
            ]
        }],
        "max_tokens": 700
    }
    req = urllib.request.Request(
        "https://openrouter.ai/api/v1/chat/completions",
        data=json.dumps(payload).encode(),
        headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"}
    )
    try:
        with urllib.request.urlopen(req, timeout=120) as resp:
            data = json.loads(resp.read().decode())
            print(f"=== SUCCESS with {model} ===")
            print(data["choices"][0]["message"]["content"])
            sys.exit(0)
    except urllib.error.HTTPError as e:
        body = e.read().decode()[:300]
        print(f"[fail] {model}: HTTP {e.code} {body}", file=sys.stderr)
    except Exception as e:
        print(f"[fail] {model}: {e}", file=sys.stderr)

print("ALL MODELS FAILED")
