#!/usr/bin/env python3
"""
Genesis Terminal Chat - Talk to AIVA or Claude via LiteLLM
Usage: python chat.py [aiva|claude|gemini-flash|gemini-pro]
"""
import sys
import requests
import json

LITELLM_URL = "http://localhost:4000/v1/chat/completions"
API_KEY = "sk-genesis-litellm-2024"

def chat(model: str, message: str, history: list) -> str:
    history.append({"role": "user", "content": message})

    response = requests.post(
        LITELLM_URL,
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json"
        },
        json={
            "model": model,
            "messages": history,
            "max_tokens": 2000,
            "stream": False
        },
        timeout=120
    )

    if response.status_code != 200:
        return f"Error: {response.text}"

    content = response.json()["choices"][0]["message"]["content"]
    history.append({"role": "assistant", "content": content})
    return content

def main():
    model = sys.argv[1] if len(sys.argv) > 1 else "aiva"

    print(f"""
╔══════════════════════════════════════════════╗
║     Genesis Terminal Chat                    ║
║     Model: {model:<33} ║
║     Type 'exit' to quit, 'switch' to change  ║
╚══════════════════════════════════════════════╝
""")

    history = []

    while True:
        try:
            user_input = input(f"\n🧑 You: ").strip()

            if not user_input:
                continue

            if user_input.lower() == "exit":
                print("Goodbye!")
                break

            if user_input.lower().startswith("switch "):
                model = user_input.split()[1]
                print(f"Switched to model: {model}")
                history = []
                continue

            print(f"\n🤖 {model}: ", end="", flush=True)
            response = chat(model, user_input, history)
            print(response)

        except KeyboardInterrupt:
            print("\nGoodbye!")
            break
        except Exception as e:
            print(f"\nError: {e}")

if __name__ == "__main__":
    main()
