#!/usr/bin/env python3
"""
Simple CLI app to chat with Grok AI
"""

import requests
import json
import sys

# Your Grok API key (found in your system)
API_KEY = "xai-Xw5PCCW3A7WwCged9UhB9RsDyOk5AyJXv3dAPi3P4Qj158p8Wm8Pk9mmMVOdpdbbhMdZxhIpmJndP4MB"
BASE_URL = "https://api.x.ai/v1/chat/completions"
DEFAULT_MODEL = "grok-4-1-fast-reasoning"

def chat_with_grok(message, model=DEFAULT_MODEL, history=None):
    """Send a message to Grok and get response"""
    if history is None:
        history = []
    
    messages = history + [{"role": "user", "content": message}]
    
    payload = {
        "model": model,
        "messages": messages,
        "max_tokens": 150
    }
    
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {API_KEY}"
    }
    
    try:
        response = requests.post(BASE_URL, headers=headers, json=payload, timeout=30)
        response.raise_for_status()
        result = response.json()
        
        if "choices" in result and len(result["choices"]) > 0:
            return result["choices"][0]["message"]["content"]
        else:
            return "Error: No response from API"
    except requests.exceptions.RequestException as e:
        return f"Error: {str(e)}"
    except json.JSONDecodeError:
        return "Error: Invalid response from API"

def main():
    print("Grok CLI Chat")
    print("Type 'quit', 'exit', or press Ctrl+C to exit")
    print("-" * 40)
    
    history = []
    
    while True:
        try:
            user_input = input("\nYou: ").strip()
            
            if user_input.lower() in ['quit', 'exit', 'q']:
                print("\nGoodbye!")
                break
            
            if not user_input:
                continue
                
            print("\nGrok: ", end="", flush=True)
            response = chat_with_grok(user_input, history=history)
            print(response)
            
            # Update conversation history
            history.append({"role": "user", "content": user_input})
            history.append({"role": "assistant", "content": response})
            
            # Keep history reasonable (last 10 exchanges)
            if len(history) > 20:
                history = history[-20:]
                
        except KeyboardInterrupt:
            print("\n\nGoodbye!")
            break
        except Exception as e:
            print(f"\nUnexpected error: {e}")

if __name__ == "__main__":
    # Check if requests is available
    try:
        import requests
    except ImportError:
        print("Error: 'requests' library not found.")
        print("Please install it with: pip install requests")
        sys.exit(1)
    
    main()