"""
Example usage of burt-logger with Anthropic Claude API.

This example shows how to integrate burt-logger with Anthropic's API
to automatically log all LLM requests and responses for training data collection.
"""

from burt_logger import LLMLogger

# Note: This example assumes you have anthropic installed
# pip install anthropic

try:
    from anthropic import Anthropic
except ImportError:
    print("This example requires the anthropic package. Install with: pip install anthropic")
    exit(1)


def main():
    # Initialize the logger with context manager for automatic cleanup
    with LLMLogger(
        endpoint="https://api.example.com/logs",  # Replace with your backend endpoint
        api_key="sk-your-backend-api-key",  # Replace with your API key
        batch_size=5,
        flush_interval=3.0,
        debug=True,
    ) as logger:
        
        # Initialize Anthropic client
        client = Anthropic(api_key="your-anthropic-api-key")  # Replace with your key
        
        print("Sending Anthropic requests and logging them...\n")
        
        # Example 1: Simple message
        prompt = "What are the three laws of robotics?"
        
        try:
            response = client.messages.create(
                model="claude-3-sonnet-20240229",
                max_tokens=1024,
                messages=[
                    {"role": "user", "content": prompt}
                ],
            )
            
            # Log the request and response
            logger.log(
                request={
                    "provider": "anthropic",
                    "model": "claude-3-sonnet-20240229",
                    "max_tokens": 1024,
                    "messages": [{"role": "user", "content": prompt}],
                },
                response={
                    "id": response.id,
                    "model": response.model,
                    "content": [
                        {"type": block.type, "text": block.text}
                        for block in response.content
                    ],
                    "usage": {
                        "input_tokens": response.usage.input_tokens,
                        "output_tokens": response.usage.output_tokens,
                    },
                    "stop_reason": response.stop_reason,
                },
                metadata={
                    "user_id": "user_789",
                    "application": "demo_app",
                },
            )
            
            print(f"Prompt: {prompt}")
            print(f"Response: {response.content[0].text}")
            print(f"Tokens - Input: {response.usage.input_tokens}, Output: {response.usage.output_tokens}\n")
            
        except Exception as e:
            print(f"Error calling Anthropic API: {e}\n")
        
        # Example 2: Conversation with system prompt
        try:
            response = client.messages.create(
                model="claude-3-sonnet-20240229",
                max_tokens=1024,
                system="You are a helpful AI assistant specialized in Python programming.",
                messages=[
                    {"role": "user", "content": "How do I create a list comprehension in Python?"}
                ],
            )
            
            logger.log(
                request={
                    "provider": "anthropic",
                    "model": "claude-3-sonnet-20240229",
                    "max_tokens": 1024,
                    "system": "You are a helpful AI assistant specialized in Python programming.",
                    "messages": [
                        {"role": "user", "content": "How do I create a list comprehension in Python?"}
                    ],
                },
                response={
                    "id": response.id,
                    "content": [{"text": response.content[0].text}],
                    "usage": {
                        "input_tokens": response.usage.input_tokens,
                        "output_tokens": response.usage.output_tokens,
                    },
                },
            )
            
            print(f"Response: {response.content[0].text[:200]}...")
            print(f"Tokens used: {response.usage.input_tokens + response.usage.output_tokens}\n")
            
        except Exception as e:
            print(f"Error: {e}\n")
        
        # Statistics will be printed before context manager cleanup
        print("Logger Statistics:")
        stats = logger.get_stats()
        for key, value in stats.items():
            print(f"  {key}: {value}")
        
        print("\nContext manager will handle cleanup automatically...")
    
    print("Done!")


if __name__ == "__main__":
    main()

