#!/usr/bin/env python3
"""
Basic usage example for Vultr MCP Server
"""
import requests
import json
import time

# Server configuration
SERVER_URL = "http://localhost:8000"

print("Vultr MCP Server - Basic Usage Example\n")
print(f"Connecting to server at {SERVER_URL}\n")

def make_request(method, endpoint, data=None):
    """Make HTTP request and handle errors"""
    url = f"{SERVER_URL}{endpoint}"
    try:
        if method == "GET":
            response = requests.get(url)
        elif method == "POST":
            response = requests.post(url, json=data)
        else:
            raise ValueError(f"Unsupported method: {method}")
        
        response.raise_for_status()
        return response.json()
    except requests.exceptions.ConnectionError:
        print(f"Error: Cannot connect to server at {url}")
        print("Make sure the server is running with: python main.py")
        return None
    except requests.exceptions.RequestException as e:
        print(f"Error: {e}")
        if hasattr(e.response, 'text'):
            print(f"Response: {e.response.text}")
        return None

# 1. Get server info
print("1. Getting server information...")
info = make_request("GET", "/")
if info:
    print(f"   Server: {info.get('name')}")
    print(f"   Version: {info.get('version')}")
    print(f"   Description: {info.get('description')}\n")

# 2. List available tools
print("2. Listing available tools...")
tools = make_request("GET", "/tools")
if tools:
    print(f"   Found {len(tools)} tools:")
    for tool in tools[:5]:  # Show first 5 tools
        print(f"   - {tool['name']}: {tool['description']}")
    if len(tools) > 5:
        print(f"   ... and {len(tools) - 5} more tools\n")
    else:
        print()

# 3. List available resources
print("3. Listing available resources...")
resources = make_request("GET", "/resources")
if resources:
    print(f"   Found {len(resources)} resources:")
    for resource in resources:
        print(f"   - {resource['name']}: {resource['uri']}")
    print()

# 4. List available prompts
print("4. Listing available prompts...")
prompts = make_request("GET", "/prompts")
if prompts:
    print(f"   Found {len(prompts)} prompts:")
    for prompt in prompts:
        print(f"   - {prompt['name']}: {prompt['description']}")
    print()

# 5. Try to get account info (requires API key)
print("5. Trying to get account info...")
account_info = make_request("POST", "/tools/call", {
    "name": "get_account_info",
    "arguments": {}
})
if account_info:
    if account_info.get("isError"):
        print("   Error: Vultr API key not configured or invalid")
        print("   To fix this, add your VULTR_API_KEY to .env file\n")
    else:
        print("   Account info retrieved successfully!")
        # Pretty print the result
        content = account_info.get("content", [])
        if content and len(content) > 0:
            try:
                data = json.loads(content[0].get("text", "{}"))
                print(f"   Account: {data.get('name', 'N/A')}")
                print(f"   Email: {data.get('email', 'N/A')}")
                print(f"   Balance: ${data.get('balance', 'N/A')}")
            except:
                print(f"   Response: {content[0].get('text', 'No data')}")
        print()

# 6. List regions (doesn't require API key for some endpoints)
print("6. Trying to list available regions...")
regions = make_request("POST", "/tools/call", {
    "name": "list_regions",
    "arguments": {}
})
if regions:
    if regions.get("isError"):
        print("   Error: Could not list regions")
        error_text = regions.get("content", [{}])[0].get("text", "Unknown error")
        print(f"   Details: {error_text}")
    else:
        content = regions.get("content", [])
        if content and len(content) > 0:
            try:
                regions_data = json.loads(content[0].get("text", "[]"))
                if isinstance(regions_data, list):
                    print(f"   Found {len(regions_data)} regions:")
                    for region in regions_data[:3]:  # Show first 3
                        if isinstance(region, dict):
                            print(f"   - {region.get('city', 'N/A')}, {region.get('country', 'N/A')} ({region.get('id', 'N/A')})")
                    if len(regions_data) > 3:
                        print(f"   ... and {len(regions_data) - 3} more regions")
            except:
                print(f"   Response: {content[0].get('text', 'No data')}")
    print()

print("\nExample completed!")
print("\nNext steps:")
print("1. Add your VULTR_API_KEY to .env file")
print("2. Start the server: python main.py")
print("3. Run this example again to see full functionality")
print("\nFor more examples, check the examples/ directory")

