#!/usr/bin/env python3
"""
Example API client for the Infinite Replayability Generator API

This script demonstrates how to interact with the Infinite Replayability API
to generate adventure hooks, NPCs, and dungeon maps programmatically.
"""

import requests
import json
import sys
import random

# Base URL for the API (Replace with the actual URL when using)
BASE_URL = "https://your-application-url.replit.app/api/v1"

def generate_hook(setting="baldurs_gate", seed=None, params=None):
    """
    Generate an adventure hook using the API
    
    Args:
        setting (str): The campaign setting (e.g., baldurs_gate, menzoberranzan, spelljammer)
        seed (int, optional): A seed for reproducible generation
        params (dict, optional): Parameters to customize the hook
        
    Returns:
        dict: Generated hook data
    """
    endpoint = f"{BASE_URL}/hooks"
    
    # Default parameters if none provided
    if params is None:
        params = {
            "campaign_title": "Lost Treasures of the Sword Coast",
            "alignment": "neutral",
            "level_range": "1-4"
        }
    
    payload = {
        "setting": setting,
        "params": params
    }
    
    # Add seed if provided
    if seed is not None:
        payload["seed"] = seed
    
    # Make API request
    try:
        response = requests.post(endpoint, json=payload)
        response.raise_for_status()  # Raise exception for 4XX/5XX responses
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"Error generating hook: {e}")
        if hasattr(e, 'response') and e.response is not None:
            print(f"Response: {e.response.text}")
        return None

def generate_npc(species=None, gender=None, seed=None):
    """
    Generate an NPC using the API
    
    Args:
        species (str, optional): The species of the NPC (e.g., Human, Elf, Dwarf)
        gender (str, optional): The gender of the NPC (male, female, indeterminate)
        seed (int, optional): A seed for reproducible generation
        
    Returns:
        dict: Generated NPC data
    """
    endpoint = f"{BASE_URL}/npcs"
    
    payload = {}
    
    # Add optional parameters if provided
    if species is not None:
        payload["species"] = species
    if gender is not None:
        payload["gender"] = gender
    if seed is not None:
        payload["seed"] = seed
    
    # Make API request
    try:
        response = requests.post(endpoint, json=payload)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"Error generating NPC: {e}")
        if hasattr(e, 'response') and e.response is not None:
            print(f"Response: {e.response.text}")
        return None

def generate_map(width=20, height=20, theme="dungeon", seed=None, params=None):
    """
    Generate a dungeon map using the API
    
    Args:
        width (int): Width of the map
        height (int): Height of the map
        theme (str): Map theme (dungeon, cave, temple, etc.)
        seed (int, optional): A seed for reproducible generation
        params (dict, optional): Advanced parameters
        
    Returns:
        dict: Generated map data
    """
    endpoint = f"{BASE_URL}/maps"
    
    # Default parameters if none provided
    if params is None:
        params = {
            "min_rooms": 5,
            "max_rooms": 10,
            "min_room_size": 3,
            "max_room_size": 6,
            "corridor_density": 0.7,
            "feature_density": 1.0
        }
    
    payload = {
        "width": width,
        "height": height,
        "theme": theme,
        "params": params
    }
    
    # Add seed if provided
    if seed is not None:
        payload["seed"] = seed
    
    # Make API request
    try:
        response = requests.post(endpoint, json=payload)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"Error generating map: {e}")
        if hasattr(e, 'response') and e.response is not None:
            print(f"Response: {e.response.text}")
        return None

def generate_ascii_map(width=20, height=20, theme="dungeon", seed=None, params=None):
    """
    Generate an ASCII representation of a dungeon map using the API
    
    Args:
        width (int): Width of the map
        height (int): Height of the map
        theme (str): Map theme (dungeon, cave, temple, etc.)
        seed (int, optional): A seed for reproducible generation
        params (dict, optional): Advanced parameters
        
    Returns:
        dict: Generated ASCII map data
    """
    endpoint = f"{BASE_URL}/maps/ascii"
    
    # Default parameters if none provided
    if params is None:
        params = {
            "min_rooms": 5,
            "max_rooms": 10,
            "min_room_size": 3,
            "max_room_size": 6,
            "corridor_density": 0.7,
            "feature_density": 1.0
        }
    
    payload = {
        "width": width,
        "height": height,
        "theme": theme,
        "params": params
    }
    
    # Add seed if provided
    if seed is not None:
        payload["seed"] = seed
    
    # Make API request
    try:
        response = requests.post(endpoint, json=payload)
        response.raise_for_status()
        result = response.json()
        
        # Print ASCII map if available
        if "ascii_map" in result:
            print("\nASCII Map:")
            print(result["ascii_map"])
        
        return result
    except requests.exceptions.RequestException as e:
        print(f"Error generating ASCII map: {e}")
        if hasattr(e, 'response') and e.response is not None:
            print(f"Response: {e.response.text}")
        return None

def print_json(data):
    """Print JSON data in a readable format"""
    print(json.dumps(data, indent=2))

if __name__ == "__main__":
    # Simple CLI interface
    if len(sys.argv) < 2:
        print("Usage: python api_client.py [hook|npc|map|ascii-map]")
        sys.exit(1)
    
    command = sys.argv[1].lower()
    
    # Use a random seed for examples
    example_seed = random.randint(1, 1000000)
    
    if command == "hook":
        print(f"Generating adventure hook with seed {example_seed}...")
        hook = generate_hook(seed=example_seed)
        if hook:
            print("\nAdventure Hook:")
            print(f"Title: {hook.get('campaign_title')}")
            print(f"Setting: {hook.get('setting_name')}")
            print(f"Hook: {hook.get('hook_text')}")
    
    elif command == "npc":
        print(f"Generating NPC with seed {example_seed}...")
        npc = generate_npc(seed=example_seed)
        if npc:
            print("\nNPC:")
            print(f"Name: {npc.get('name')}")
            print(f"Species: {npc.get('species')}")
            print(f"Profession: {npc.get('profession')}")
            print(f"Backstory: {npc.get('backstory')}")
    
    elif command == "map":
        print(f"Generating dungeon map with seed {example_seed}...")
        map_data = generate_map(seed=example_seed)
        if map_data:
            print("\nMap Generated:")
            print(f"Theme: {map_data.get('theme')}")
            print(f"Dimensions: {map_data.get('width')}x{map_data.get('height')}")
            print(f"Rooms: {len(map_data.get('rooms', []))}")
            print(f"Special Rooms: {len(map_data.get('special_rooms', {}))}")
    
    elif command == "ascii-map":
        print(f"Generating ASCII dungeon map with seed {example_seed}...")
        map_data = generate_ascii_map(seed=example_seed)
        if map_data:
            print("\nMap Generated:")
            print(f"Theme: {map_data.get('theme')}")
            print(f"Dimensions: {map_data.get('width')}x{map_data.get('height')}")
    
    else:
        print(f"Unknown command: {command}")
        print("Available commands: hook, npc, map, ascii-map")