#!/usr/bin/env python3
"""
RADKit MCP Server - Test Mode for iFlow

This version runs in test mode without requiring RADKit authentication
for local testing purposes.
"""

import sys
import logging
from pathlib import Path
from contextlib import asynccontextmanager

# Setup logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# Try to import fastmcp
try:
    from fastmcp import FastMCP
except ImportError:
    logger.error("fastmcp not found. Please install it with: pip install fastmcp")
    sys.exit(1)


@asynccontextmanager
async def lifespan(app):
    """
    Lifespan handler - test mode without RADKit connection
    """
    logger.info("=" * 60)
    logger.info("RADKit MCP Server - Starting up (TEST MODE)")
    logger.info("=" * 60)
    logger.info("Note: Running in test mode without RADKit connection")
    yield
    logger.info("\nShutting down RADKit MCP Server...")


# Create FastMCP server
mcp = FastMCP(
    name="RADKit MCP Server",
    version="2.0.0",
    lifespan=lifespan
)


@mcp.tool()
async def get_device_inventory_names() -> str:
    """
    Returns a string with the names of the devices onboarded in the Cisco RADKit service's inventory.
    Use this first when the user asks about "devices", "network", or "all devices".

    Returns:
        str: List of devices onboarded in the Cisco RADKit service's inventory
    """
    return '{"test-device-1", "test-device-2"}'


@mcp.tool()
async def get_device_attributes(target_device: str) -> str:
    """
    Returns a JSON string with the attributes of the specified target device.
    Always try this first when the user asks about a specific device.

    Args:
        target_device: (str) Target device to get the attributes from.

    Returns:
        str: JSON string with device attributes
    """
    import json
    return json.dumps({
        "name": target_device,
        "host": "test.example.com",
        "type": "router",
        "status": "active"
    })


@mcp.tool()
async def exec_cli_commands_in_device(
    target_device: str,
    cli_commands: str,
    timeout: int = 30,
    max_lines: int = 800
) -> str:
    """
    Executes a CLI command or commands on a target device.

    Args:
        target_device: Device name
        cli_commands: Commands to execute
        timeout: Timeout in seconds (optional)
        max_lines: Output line limit (optional)

    Returns:
        str: Raw output of executed command(s)
    """
    return f"Test output for command '{cli_commands}' on device '{target_device}'"


@mcp.tool()
async def snmp_get(
    device_name: str,
    oid: str,
    timeout: float = 10.0
) -> str:
    """
    Performs SNMP GET operations on network devices.

    Args:
        device_name: Device name
        oid: Single OID or list of OIDs
        timeout: SNMP timeout

    Returns:
        str: SNMP results
    """
    import json
    return json.dumps([{
        "device_name": device_name,
        "oid": oid,
        "value": "test-value",
        "type": "OctetString"
    }])


@mcp.tool()
async def exec_command(
    device_name: str,
    command: str,
    timeout: int = 0,
    max_lines: int = 800
) -> str:
    """
    Command execution with structured output format.

    Args:
        device_name: Device name
        command: Commands
        timeout: Timeout
        max_lines: Line limit

    Returns:
        str: Structured response
    """
    import json
    return json.dumps({
        "status": "success",
        "output": f"Test output for command '{command}'",
        "truncated": False
    })


def main():
    """Run the FastMCP server."""
    logger.info("✅ RADKit MCP Server starting with transport: STDIO")
    mcp.run(transport="stdio")


if __name__ == "__main__":
    main()
