"""Example: Using the Routes service to create mock APIs."""

from sed_sh import SedSH
import json

# Initialize client
client = SedSH()

# Example 1: Create a mock API endpoint
print("=== Example 1: Mock API endpoint ===")
endpoint = client.routes.create_endpoint(
    name="User API",
    method="GET",
    path="/api/users",
    response_status=200,
    response_body=json.dumps({
        "users": [
            {"id": 1, "name": "Alice"},
            {"id": 2, "name": "Bob"}
        ]
    }),
    response_headers={"Content-Type": "application/json"}
)
print(f"Endpoint URL: {endpoint['url']}")
print(f"Endpoint ID: {endpoint['endpointId']}")
print("Try: curl", endpoint['url'])
print()

# Example 2: Create endpoint with delay
print("=== Example 2: Endpoint with delay ===")
slow_endpoint = client.routes.create_endpoint(
    name="Slow API",
    method="POST",
    path="/api/slow",
    response_status=200,
    response_delay=2000,  # 2 second delay
    response_body=json.dumps({"message": "This took 2 seconds"})
)
print(f"Slow endpoint: {slow_endpoint['url']}")
print("This endpoint will wait 2 seconds before responding")
print()

# Example 3: Create error response endpoint
print("=== Example 3: Error response ===")
error_endpoint = client.routes.create_endpoint(
    name="Error API",
    method="GET",
    path="/api/error",
    response_status=500,
    response_body=json.dumps({"error": "Internal server error"})
)
print(f"Error endpoint: {error_endpoint['url']}")
print("This endpoint returns HTTP 500")
print()

# Example 4: Create forward mode endpoint (proxy)
print("=== Example 4: Forward mode (proxy) ===")
proxy_endpoint = client.routes.create_endpoint(
    name="GitHub Proxy",
    method="GET",
    path="/api/github",
    forward_mode=True,
    forward_url="https://api.github.com/users/github"
)
print(f"Proxy endpoint: {proxy_endpoint['url']}")
print("This endpoint forwards requests to GitHub API")
print()

# Example 5: List all endpoints
print("=== Example 5: List all endpoints ===")
endpoints = client.routes.list_endpoints()
print(f"Total endpoints: {len(endpoints['endpoints'])}")
for ep in endpoints['endpoints']:
    print(f"  - {ep['method']} {ep['path']}: {ep['url']}")
print()

# Example 6: Update an endpoint
print("=== Example 6: Update endpoint ===")
updated = client.routes.update_endpoint(
    endpoint_id=endpoint['endpointId'],
    response_status=201,
    response_body=json.dumps({"message": "Updated response"})
)
print(f"Updated endpoint: {updated['endpointId']}")
print()

# Example 7: Toggle endpoint on/off
print("=== Example 7: Toggle endpoint ===")
client.routes.toggle_endpoint(endpoint['endpointId'], enabled=False)
print(f"Disabled endpoint: {endpoint['endpointId']}")
client.routes.toggle_endpoint(endpoint['endpointId'], enabled=True)
print(f"Re-enabled endpoint: {endpoint['endpointId']}")
print()

# Example 8: View incoming requests
print("=== Example 8: View request logs ===")
print("Make a request to one of your endpoints, then run this...")
requests_log = client.routes.get_requests()
print(f"Total requests logged: {len(requests_log['requests'])}")
if requests_log['requests']:
    req = requests_log['requests'][0]
    print(f"Latest request:")
    print(f"  Method: {req['method']}")
    print(f"  Path: {req['path']}")
    print(f"  Source IP: {req['sourceIp']}")
    print(f"  Timestamp: {req['timestamp']}")

    # Get detailed request info
    detailed = client.routes.get_request(req['requestId'])
    print(f"  Headers: {json.dumps(detailed.get('headers', {}), indent=4)}")
print()

# Example 9: Practical use case - webhook testing
print("=== Example 9: Webhook testing ===")
webhook = client.routes.create_endpoint(
    name="Stripe Webhook",
    method="POST",
    path="/webhooks/stripe",
    response_status=200,
    response_body=json.dumps({"received": True})
)
print(f"Webhook URL: {webhook['url']}")
print("Use this URL as your webhook endpoint in Stripe/GitHub/etc.")
print("Then check request logs to see the webhook payloads:")
print(f"  client.routes.get_requests()")
print()

# Clean up - delete the endpoints we created
print("=== Cleanup ===")
for ep_id in [endpoint['endpointId'], slow_endpoint['endpointId'],
              error_endpoint['endpointId'], proxy_endpoint['endpointId'],
              webhook['endpointId']]:
    client.routes.delete_endpoint(ep_id)
    print(f"Deleted endpoint: {ep_id}")
