"""
MCP Server for Vultr Cloud Services
"""
import logging
import os
import sys
from typing import Dict, List, Any, Optional
from mcp.server.fastmcp import FastMCP, Context

from .client import VultrClient
from .config import load_config

# Configure logging
logging.basicConfig(level=logging.INFO, stream=sys.stderr)
logger = logging.getLogger(__name__)

# Load configuration from config.json
try:
    config = load_config()
except (FileNotFoundError, ValueError) as e:
    logger.error(f"Configuration error: {e}")
    sys.exit(1)

# Initialize FastMCP
mcp = FastMCP("Vultr MCP Server")

# Initialize Vultr client
vultr_client = None
try:
    vultr_client = VultrClient(api_key=config['vultr']['api_key'])
except ValueError as e:
    logger.warning(f"Vultr client initialization failed: {e}")
    logger.warning("Server will start but Vultr operations will fail")

# Helper to check client
def get_client() -> VultrClient:
    if not vultr_client:
        raise ValueError("Vultr client not initialized. Please check config.json.")
    return vultr_client


@mcp.tool()
def get_account_info() -> Dict[str, Any]:
    """Get Vultr account information"""
    return get_client().get_account_info()

@mcp.tool()
def list_instances(per_page: int = 100) -> Dict[str, Any]:
    """
    List all Vultr instances
    
    Args:
        per_page: Number of instances per page (default: 100)
    """
    return {'instances': get_client().list_instances(per_page=per_page)}

@mcp.tool()
def get_instance(instance_id: str) -> Dict[str, Any]:
    """
    Get details of a specific instance
    
    Args:
        instance_id: ID of the instance
    """
    return get_client().get_instance(instance_id)

@mcp.tool()
def create_instance(
    region: str,
    plan: str,
    os_id: int,
    label: str = "",
    hostname: str = "",
    tags: List[str] = []
) -> Dict[str, Any]:
    """
    Create a new Vultr instance
    
    Args:
        region: Region code (e.g., 'ams')
        plan: Plan ID (e.g., 'vc2-1c-1gb')
        os_id: Operating System ID
        label: Instance label
        hostname: Instance hostname
        tags: Tags for the instance
    """
    return get_client().create_instance(
        region=region,
        plan=plan,
        os_id=os_id,
        label=label,
        hostname=hostname,
        tags=tags
    )

@mcp.tool()
def delete_instance(instance_id: str) -> Dict[str, Any]:
    """
    Delete a Vultr instance
    
    Args:
        instance_id: ID of the instance to delete
    """
    return get_client().delete_instance(instance_id)

@mcp.tool()
def start_instance(instance_id: str) -> Dict[str, Any]:
    """
    Start a Vultr instance
    
    Args:
        instance_id: ID of the instance to start
    """
    return get_client().start_instance(instance_id)

@mcp.tool()
def stop_instance(instance_id: str) -> Dict[str, Any]:
    """
    Stop a Vultr instance
    
    Args:
        instance_id: ID of the instance to stop
    """
    return get_client().stop_instance(instance_id)

@mcp.tool()
def reboot_instance(instance_id: str) -> Dict[str, Any]:
    """
    Reboot a Vultr instance
    
    Args:
        instance_id: ID of the instance to reboot
    """
    return get_client().reboot_instance(instance_id)

@mcp.tool()
def list_regions() -> Dict[str, Any]:
    """List available Vultr regions"""
    return {'regions': get_client().list_regions()}

@mcp.tool()
def list_plans() -> Dict[str, Any]:
    """List available Vultr plans"""
    return {'plans': get_client().list_plans()}

@mcp.tool()
def list_os() -> Dict[str, Any]:
    """List available Vultr operating systems"""
    return {'os': get_client().list_os()}

# DNS Management Tools
@mcp.tool()
def list_dns_domains() -> Dict[str, Any]:
    """List all DNS domains"""
    return {'domains': get_client().list_dns_domains()}

@mcp.tool()
def create_dns_domain(domain: str, ip: str) -> Dict[str, Any]:
    """
    Create a new DNS domain
    
    Args:
        domain: Domain name (e.g., 'example.com')
        ip: IP address for the domain
    """
    return get_client().create_dns_domain(domain, ip)

@mcp.tool()
def delete_dns_domain(domain: str) -> Dict[str, Any]:
    """
    Delete a DNS domain
    
    Args:
        domain: Domain name
    """
    return get_client().delete_dns_domain(domain)

@mcp.tool()
def get_dns_domain(domain: str) -> Dict[str, Any]:
    """
    Get DNS domain details
    
    Args:
        domain: Domain name
    """
    return get_client().get_dns_domain(domain)

@mcp.tool()
def list_dns_records(domain: str) -> Dict[str, Any]:
    """
    List DNS records for a domain
    
    Args:
        domain: Domain name
    """
    return {'records': get_client().list_dns_records(domain)}

@mcp.tool()
def create_dns_record(
    domain: str,
    type: str,
    name: str,
    data: str,
    ttl: int = 300,
    priority: int = 0
) -> Dict[str, Any]:
    """
    Create a new DNS record
    
    Args:
        domain: Domain name
        type: Record type (A, AAAA, CNAME, MX, TXT, etc.)
        name: Record name (e.g., 'www', '@', 'mail')
        data: Record data (IP address, hostname, etc.)
        ttl: Time to live in seconds (default: 300)
        priority: Priority for MX records (default: 0)
    """
    return get_client().create_dns_record(domain, type, name, data, ttl, priority)

@mcp.tool()
def update_dns_record(
    domain: str,
    record_id: str,
    type: Optional[str] = None,
    name: Optional[str] = None,
    data: Optional[str] = None,
    ttl: Optional[int] = None,
    priority: Optional[int] = None
) -> Dict[str, Any]:
    """
    Update a DNS record
    
    Args:
        domain: Domain name
        record_id: Record ID
        type: Record type (optional)
        name: Record name (optional)
        data: Record data (optional)
        ttl: Time to live in seconds (optional)
        priority: Priority for MX records (optional)
    """
    # Filter out None values
    update_args = {}
    if type is not None: update_args['type'] = type
    if name is not None: update_args['name'] = name
    if data is not None: update_args['data'] = data
    if ttl is not None: update_args['ttl'] = ttl
    if priority is not None: update_args['priority'] = priority

    return get_client().update_dns_record(domain, record_id, **update_args)

@mcp.tool()
def delete_dns_record(domain: str, record_id: str) -> Dict[str, Any]:
    """
    Delete a DNS record
    
    Args:
        domain: Domain name
        record_id: Record ID
    """
    return get_client().delete_dns_record(domain, record_id)

@mcp.resource("vultr://account/info")
def resource_account_info() -> str:
    """Vultr account information"""
    return str(get_client().get_account_info())

@mcp.resource("vultr://instances/list")
def resource_instances_list() -> str:
    """List of Vultr instances"""
    return str(get_client().list_instances())

@mcp.resource("vultr://regions/list")
def resource_regions_list() -> str:
    """List of available Vultr regions"""
    return str(get_client().list_regions())

@mcp.resource("vultr://plans/list")
def resource_plans_list() -> str:
    """List of available Vultr plans"""
    return str(get_client().list_plans())

@mcp.resource("vultr://os/list")
def resource_os_list() -> str:
    """List of available Vultr operating systems"""
    return str(get_client().list_os())

@mcp.resource("vultr://dns/domains")
def resource_dns_domains() -> str:
    """List of DNS domains"""
    return str(get_client().list_dns_domains())
