"""
Quick test: Call Thesys C1 API with a search-like query and see what it returns.
Usage: THESYS_API_KEY=your_key python test_c1.py
"""

import os
import sys
import time

try:
    from openai import OpenAI
except ImportError:
    print("Installing openai...")
    os.system(f"{sys.executable} -m pip install openai -q")
    from openai import OpenAI


def test_c1(api_key: str):
    client = OpenAI(
        api_key=api_key,
        base_url="https://api.thesys.dev/v1/embed",
    )

    queries = [
        "Show current gold prices in India for 24K and 22K with today's change percentage. Display as a clean visual card.",
        "Show weather in Hyderabad, India right now with temperature, humidity, wind speed.",
        "Show Bitcoin and Ethereum current prices with 24h change percentage.",
    ]

    for i, query in enumerate(queries, 1):
        print(f"\n{'='*80}")
        print(f"TEST {i}: {query[:60]}...")
        print("=" * 80)

        start = time.time()
        try:
            response = client.chat.completions.create(
                model="c1/google/gemini-3-flash/v-20251230",
                messages=[
                    {
                        "role": "system",
                        "content": (
                            "You are a visual data card generator. Generate clean, "
                            "compact visual cards for mobile display. Use real-time "
                            "data styling with bold numbers, change indicators "
                            "(green for up, red for down), and clean layouts. "
                            "Keep cards compact — suitable for a mobile app card view. "
                            "Do NOT use placeholder data — use realistic current values."
                        ),
                    },
                    {"role": "user", "content": query},
                ],
                temperature=0.3,
            )

            elapsed = time.time() - start
            content = response.choices[0].message.content

            print(f"\nLatency: {elapsed:.2f}s")
            print(f"Tokens: input={response.usage.prompt_tokens}, output={response.usage.completion_tokens}")
            print(f"\nC1 Response ({len(content)} chars):")
            print("-" * 40)
            print(content[:2000])
            if len(content) > 2000:
                print(f"\n... ({len(content) - 2000} more chars)")
            print("-" * 40)

        except Exception as e:
            elapsed = time.time() - start
            print(f"\nERROR after {elapsed:.2f}s: {e}")


if __name__ == "__main__":
    api_key = os.getenv("THESYS_API_KEY", "")

    if not api_key:
        if len(sys.argv) > 1:
            api_key = sys.argv[1]
        else:
            print("Usage: THESYS_API_KEY=your_key python test_c1.py")
            print("   or: python test_c1.py YOUR_API_KEY")
            print("\nGet a free key at: https://console.thesys.dev/keys")
            sys.exit(1)

    print(f"Testing C1 API with key: {api_key[:8]}...")
    test_c1(api_key)
