"""
Example usage of the Kindred AI SDK.

This example demonstrates how to use the Kindred AI interceptor to reroute
HTTP requests from any API provider to custom destinations.
The SDK works with ANY domain - not limited to specific providers.
"""

import os
from kindred_ai import Interceptor

# Example 1: Basic usage with requests
def example_requests():
    """Example using the requests library."""
    print("=== Example 1: Using with requests ===")
    
    # Works with ANY domain - here we reroute Stripe API calls
    rules = {
        "api.stripe.com": "http://localhost:8080/stripe-mock"
    }
    
    Interceptor.init(routing_rules=rules, verbose=True)
    
    try:
        import requests
        # This request will be intercepted and rerouted
        response = requests.get("https://api.stripe.com/v1/charges")
        print(f"Response status: {response.status_code}")
    except Exception as e:
        print(f"Request failed (expected if gateway is not running): {e}")
    finally:
        Interceptor.stop()


# Example 2: Using context manager
def example_context_manager():
    """Example using the context manager for temporary interception."""
    print("\n=== Example 2: Using context manager ===")
    
    # Reroute multiple providers at once
    rules = {
        "api.stripe.com": "http://localhost:8080/stripe-mock",
        "api.github.com": "http://localhost:8080/github-proxy"
    }
    
    with Interceptor.scope(routing_rules=rules, verbose=True):
        try:
            import requests
            response = requests.get("https://api.stripe.com/v1/charges")
            print(f"Response status: {response.status_code}")
        except Exception as e:
            print(f"Request failed (expected if gateway is not running): {e}")
    
    print("Kindred AI interceptor is now stopped (outside context)")


# Example 3: Using with httpx (async)
async def example_httpx_async():
    """Example using httpx async client."""
    print("\n=== Example 3: Using with httpx (async) ===")
    
    # Example: Reroute OpenAI API calls to a caching gateway
    rules = {
        "api.openai.com": "http://localhost:8080/openai-cache"
    }
    
    Interceptor.init(routing_rules=rules, verbose=True)
    
    try:
        import httpx
        async with httpx.AsyncClient() as client:
            # This request will be intercepted and rerouted
            response = await client.get("https://api.openai.com/v1/models")
            print(f"Response status: {response.status_code}")
    except Exception as e:
        print(f"Request failed (expected if gateway is not running): {e}")
    finally:
        Interceptor.stop()


# Example 4: Using environment variables to fetch restricted URLs from server
def example_env_variable():
    """Example using environment variables to fetch restricted URLs from server."""
    print("\n=== Example 4: Using environment variables (fetch from server) ===")
    
    # Set environment variables (in real usage, set these before running)
    # KINDRED_AGENT_TOKEN serves as both the agent token and agent ID
    os.environ["KINDRED_AGENT_TOKEN"] = "test-token-123"
    # KINDRED_URL is used for both fetching restricted URLs and as the sidecar endpoint
    os.environ["KINDRED_URL"] = "http://localhost:8080"
    
    # Initialize without rules - will fetch restricted URLs from server
    Interceptor.init(verbose=True)
    
    try:
        import requests
        # Only requests matching restricted URLs will be intercepted
        response1 = requests.get("https://api.stripe.com/v1/charges")
        print(f"Stripe request -> {response1.url}")
        
        response2 = requests.get("https://api.github.com/users")
        print(f"GitHub request -> {response2.url}")
    except Exception as e:
        print(f"Request failed (expected if gateway is not running): {e}")
    finally:
        Interceptor.stop()
        # Clean up
        if "KINDRED_AGENT_TOKEN" in os.environ:
            del os.environ["KINDRED_AGENT_TOKEN"]
        if "KINDRED_URL" in os.environ:
            del os.environ["KINDRED_URL"]


if __name__ == "__main__":
    # Run examples
    example_requests()
    example_context_manager()
    example_env_variable()
    
    # Uncomment to run async example
    # import asyncio
    # asyncio.run(example_httpx_async())

