#!/usr/bin/env python3
import requests
import json
import os
import argparse
from typing import List, Dict, Any

def call_openrouter_api(api_key: str, prompt: str, function_def: Dict[str, Any]) -> Dict[str, Any]:
    """
    Call the OpenRouter API with the Claude 3.7 Sonnet Thinking model
    
    Args:
        api_key: OpenRouter API key
        prompt: The game prompt to send to the model
        function_def: The function definition
    
    Returns:
        The response from the API
    """
    url = "https://openrouter.ai/api/v1/chat/completions"
    
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}",
        "HTTP-Referer": "https://tictactoe-game.example"  # Replace with your actual site
    }
    
    data = {
        "model": "openai/o1-pro",
        "max_tokens": 20000,
    #     "reasoning": {
    #     "effort": "high",
    #     "exclude": False
    # },
    
    # "reasoning": {
    #     "exclude": False,
    #     "effort": "high",
    #     #"max_tokens": 1024
    # },

        "messages": [
            {"role": "user", "content": prompt}
        ],
        "tools": [
            {
                "type": "function",
                "function": function_def
            }
        ]
    }
    
    response = requests.post(url, headers=headers, json=data)
    
    if response.status_code != 200:
        print(f"Error: {response.status_code}")
        print(response.text)
        return {}
    
    return response.json()

def get_tictactoe_function_def() -> Dict[str, Any]:
    """Returns the TicTacToe function definition"""
    return {
      "name": "make_move",
      "description": "Make a move in the Tic-Tac-Toe game",
      "parameters": {
        "type": "object",
        "properties": {
          "logic": {
            "type": "string",
            "description": "Your detailed logic for making this move"
          },
          "move": {
            "type": "string",
            "enum": ["0,1", "0,2","1,2","2,1"],
            "description": "The position to place your symbol, formatted as 'row,column' (e.g., '1,1' for center)"
          }
        },
        "required": ["logic", "move"]
      }
    }

def get_tictactoe_prompt() -> str:
    """Returns the TicTacToe game prompt"""
    return """You are playing Tic-Tac-Toe as player "claude 3.7 sonnet" with symbol "O".

Current board state:

 O | . | .
 -----------
 X | X | .
 -----------
 O | . | X

Valid moves are specified as 'row,column' with 0-indexed positions.
For example, the center position is '1,1' and the top-left is '0,0'.

Valid moves: 0,1, 0,2, 1,2, 2,1

Your goal is to get three of your symbols in a row (horizontally, vertically, or diagonally) and win as fast as possible.
Close
"""

def main():
    parser = argparse.ArgumentParser(description='Call OpenRouter API for TicTacToe move')
    parser.add_argument('--api-key', type=str, help='OpenRouter API key')
    args = parser.parse_args()
    
    # Get API key from args or environment variable
    api_key = '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'
    
    if not api_key:
        print("Error: No API key provided. Please provide it as an argument or set the OPENROUTER_API_KEY environment variable.")
        return
    
    function_def = get_tictactoe_function_def()
    prompt = get_tictactoe_prompt()
    
    print("Calling OpenRouter API...")
    response = call_openrouter_api(api_key, prompt, function_def)
    
    if response:
        print("\nAPI Response:")
        print(json.dumps(response, indent=2))
        
        # Extract the function call
        if "choices" in response:
            choice = response["choices"][0]
            if "message" in choice and "tool_calls" in choice["message"]:
                tool_call = choice["message"]["tool_calls"][0]
                function_args = json.loads(tool_call["function"]["arguments"])
                
                print("\nTicTacToe Move:")
                print(f"Position: {function_args.get('move')}")
                print(f"Reasoning: {function_args.get('reasoning')}")
                
                # If there's thinking available, display it
                if "thinking" in choice:
                    print("\nThinking Process:")
                    print(choice["thinking"])

if __name__ == "__main__":
    main() 