#!/usr/bin/env python3
"""Test Kimi K2.5 with reasoning object parameter via OpenRouter."""
import urllib.request
import json
import ssl

OPENROUTER_KEY = "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"

# Test 1: with reasoning as object
payload = json.dumps({
    "model": "moonshotai/kimi-k2.5",
    "messages": [{"role": "user", "content": "What is 2+2? Think step by step."}],
    "temperature": 1.0,
    "max_tokens": 200,
    "reasoning": {"effort": "high"}
}).encode("utf-8")

req = urllib.request.Request(
    "https://openrouter.ai/api/v1/chat/completions",
    data=payload,
    headers={
        "Authorization": f"Bearer {OPENROUTER_KEY}",
        "Content-Type": "application/json",
        "HTTP-Referer": "https://sunaivadigital.com",
        "X-Title": "Genesis Swarm Test"
    },
    method="POST"
)

ctx = ssl.create_default_context()
try:
    with urllib.request.urlopen(req, context=ctx, timeout=60) as resp:
        data = json.loads(resp.read())
        print("STATUS: SUCCESS with reasoning object")
        msg = data["choices"][0]["message"]
        print("CONTENT:", msg["content"][:200])
        usage = data.get("usage", {})
        print("REASONING TOKENS:", usage.get("completion_tokens_details", {}).get("reasoning_tokens", "N/A"))
        print("TOTAL TOKENS:", usage.get("total_tokens", "?"))
except urllib.error.HTTPError as e:
    body = e.read().decode("utf-8", errors="replace")
    print(f"HTTP ERROR {e.code}: {body[:400]}")
    # Fallback: try without reasoning parameter
    print("\nTrying without reasoning parameter...")
    payload2 = json.dumps({
        "model": "moonshotai/kimi-k2.5",
        "messages": [{"role": "user", "content": "What is 2+2? Think step by step."}],
        "temperature": 1.0,
        "max_tokens": 200
    }).encode("utf-8")
    req2 = urllib.request.Request(
        "https://openrouter.ai/api/v1/chat/completions",
        data=payload2,
        headers={
            "Authorization": f"Bearer {OPENROUTER_KEY}",
            "Content-Type": "application/json",
            "HTTP-Referer": "https://sunaivadigital.com"
        },
        method="POST"
    )
    try:
        with urllib.request.urlopen(req2, context=ctx, timeout=60) as resp2:
            data2 = json.loads(resp2.read())
            print("NO-REASONING SUCCESS:")
            print("CONTENT:", data2["choices"][0]["message"]["content"][:200])
            print("TOKENS:", data2.get("usage", {}))
    except Exception as e2:
        print(f"ALSO FAILED: {e2}")
except Exception as e:
    print(f"ERROR: {type(e).__name__}: {e}")
