import requests
import sys
from .models import models
from .keys import keys

class EasyRouter:
    def __init__(self, account_type):
        self._keys = keys
        self.models = models
        self.api_key = self._keys.get(account_type)
        self.url = "https://openrouter.ai/api/v1/chat/completions"

    def _make_request(self, model_id, messages):
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }
        data = {"model": model_id, "messages": messages}
        response = requests.post(self.url, headers=headers, json=data)
        response.raise_for_status()
        return response.json()['choices'][0]['message']['content']

    def start_chat(self, model):
        model_id = self.models.get(model)
        history = [{"role": "system", "content": "You are a helpful assistant."}]
        
        while True:
            user_input = input("ysm: ")
            if user_input.lower() == 'q':
                break
            
            history.append({"role": "user", "content": user_input})
            
            print("obla: ", end="", flush=True)
            try:
                answer = self._make_request(model_id, history)
                print(answer + "\n")
                history.append({"role": "assistant", "content": answer})
            except Exception as e:
                print(f"\nError: {e}")

def run_cli():
    args = sys.argv[1:]

    if len(args) == 1 and args[0] == "list":
        for key, value in models.items():
            print(f"{key:>2} {value}")
        sys.exit(0)

    if len(args) < 2:
        sys.exit(1)

    api_input = args[0]
    model_input = args[1]

    app = EasyRouter(account_type=api_input)
    app.start_chat(model=model_input)