#!/usr/bin/env python3
import argparse
import sys
import requests
import os

API_URL = "https://ai.hackclub.com/proxy/v1/chat/completions"
MODEL = "openai/gpt-5.1"


def chat(token, message, conversation_history=None):
    if conversation_history is None:
        conversation_history = []
    
    conversation_history.append({"role": "user", "content": message})
    
    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json"
    }
    
    data = {
        "model": MODEL,
        "messages": conversation_history
    }
    
    try:
        response = requests.post(API_URL, headers=headers, json=data)
        response.raise_for_status()
        result = response.json()
        
        assistant_message = result["choices"][0]["message"]["content"]
        conversation_history.append({"role": "assistant", "content": assistant_message})
        
        return assistant_message, conversation_history
    except requests.exceptions.HTTPError as e:
        if e.response.status_code == 401:
            return "Error: Unauthorized. Please check your token.", conversation_history
        return f"Error: {e.response.status_code} {e.response.reason}", conversation_history
    except requests.exceptions.RequestException as e:
        return f"Error: {str(e)}", conversation_history


def main():
    parser = argparse.ArgumentParser(description="Hack Club AI Chatbot CLI")
    parser.add_argument(
        "--token",
        type=str,
        help="API token for Hack Club endpoint",
        default=os.environ.get("HACK_CLUB_TOKEN")
    )
    parser.add_argument(
        "message",
        nargs="?",
        type=str,
        help="Message to send (optional, will start interactive mode if not provided)"
    )
    
    args = parser.parse_args()
    
    if not args.token:
        print("Error: Token required. Provide --token or set HACK_CLUB_TOKEN environment variable.")
        sys.exit(1)
    
    conversation_history = []
    
    if args.message:
        response, _ = chat(args.token, args.message, conversation_history)
        print(response)
    else:
        print("type 'exit' or 'quit' to end")
        print("-" * 50)
        
        while True:
            try:
                user_input = input("\nName: ").strip()
                
                if not user_input:
                    continue
                
                if user_input.lower() in ["exit", "quit"]:
                    print("Goodbye!")
                    break
                
                print("Age: ", end="", flush=True)
                response, conversation_history = chat(args.token, user_input, conversation_history)
                print(response)
                
            except KeyboardInterrupt:
                print("\n\nGoodbye!")
                break
            except EOFError:
                print("\n\nGoodbye!")
                break


if __name__ == "__main__":
    main()
