#!/usr/bin/env python3
"""Debug: cek akses model + search image models."""
import json, re, urllib.request

tools = open('TOOLS.md', encoding='utf-8').read()
m = re.search(r'Replicate API Key[\s\S]*?Token:\*\*\s*`([^`]+)`', tools)
KEY = m.group(1).strip()
H = {"Authorization": f"Bearer {KEY}"}

# 1. Verifikasi model video yang diketahui OK
for model in ["bytedance/seedance-2.5", "stability-ai/stable-video-diffusion"]:
    try:
        req = urllib.request.Request(f"https://api.replicate.com/v1/models/{model}", headers=H)
        with urllib.request.urlopen(req, timeout=30) as r:
            d = json.loads(r.read())
        print(f"OK: {model} | {d.get('name')} | latest {d['latest_version']['id'][:16]}")
    except urllib.error.HTTPError as e:
        print(f"FAIL: {model} | {e.code}")

# 2. Search flux / image gen
for q in ["flux", "image", "text-to-image"]:
    try:
        req = urllib.request.Request(f"https://api.replicate.com/v1/models?query={q}&limit=5", headers=H)
        with urllib.request.urlopen(req, timeout=30) as r:
            d = json.loads(r.read())
        print(f"\nSEARCH '{q}':", [x.get("owner") + "/" + x.get("name") for x in d.get("results", [])])
    except urllib.error.HTTPError as e:
        print(f"\nSEARCH '{q}' FAIL: {e.code} {e.read().decode()[:150]}")
