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"

# Get actual messages from the new session
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()

messages = [{"role": r["role"], "content": r["content"]} for r in rows if (r["content"] or "").strip()]
print(f"Total messages: {len(messages)}")
for i, m in enumerate(messages):
    print(f"  [{i}] {m['role']} len={len(m['content'])} preview={repr(m['content'][:80])}")

async def test():
    payload = {"model": "google/gemini-2.5-flash", "messages": messages, "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:
            print("status:", r.status_code)
            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("ERROR:", json.dumps(parsed["error"], indent=2))
                    return
                content = parsed.get("choices", [{}])[0].get("delta", {}).get("content", "")
                if content:
                    print("OK, got chunk:", repr(content[:50]))
                    return

asyncio.run(test())
