import asyncio, httpx, os, json, sqlite3
from dotenv import load_dotenv
load_dotenv()

KEY = os.getenv("ROUTER_KEY")
URL = "https://openrouter.ai/api/v1/chat/completions"

db = sqlite3.connect("data/chat.db")
db.row_factory = sqlite3.Row
rows = db.execute(
    "SELECT role, content FROM messages WHERE session_id = (SELECT session_id FROM sessions ORDER BY updated_at DESC LIMIT 1) ORDER BY id"
).fetchall()
db.close()

all_msgs = [{"role": r["role"], "content": r["content"]} for r in rows if (r["content"] or "").strip()]

async def try_msgs(msgs, label):
    payload = {"model": "google/gemini-2.5-flash", "messages": msgs, "stream": True}
    headers = {"Authorization": f"Bearer {KEY}", "Content-Type": "application/json"}
    async with httpx.AsyncClient(timeout=30) as c:
        async with c.stream("POST", URL, headers=headers, json=payload) as r:
            async for line in r.aiter_lines():
                if not line.startswith("data: "): continue
                d = line[6:]
                if d == "[DONE]": break
                parsed = json.loads(d)
                if parsed.get("error"):
                    print(f"[{label}] ERROR: {parsed['error']['message']}")
                    return
                if parsed.get("choices", [{}])[0].get("delta", {}).get("content"):
                    print(f"[{label}] OK")
                    return

async def main():
    # Test subsets to find which message causes the error
    await try_msgs(all_msgs[1:], "no system")
    await try_msgs([all_msgs[0], all_msgs[2]], "system+user only")
    await try_msgs([{"role": "user", "content": all_msgs[2]["content"]}], "user only")
    # Print full system prompt
    print("\n--- system prompt last 500 chars ---")
    print(repr(all_msgs[0]["content"][-500:]))
    print("\n--- user content ---")
    print(repr(all_msgs[2]["content"]))

asyncio.run(main())
