/**
 * @file server_example.cpp
 * @brief Server example based on MCP protocol
 * 
 * This example demonstrates how to create an MCP server, register tools and resources,
 * and handle client requests. Follows the 2024-11-05 basic protocol specification.
 */

#include "mcp_server.h"
#include "mcp_tool.h"
#include "mcp_resource.h"

#include <iostream>
#include <chrono>
#include <ctime>
#include <thread>
#include <filesystem>
#include <algorithm>

// Tool handler for getting current time
mcp::json get_time_handler(const mcp::json& params) {
    auto now = std::chrono::system_clock::now();
    auto time_t_now = std::chrono::system_clock::to_time_t(now);
    
    std::string time_str = std::ctime(&time_t_now);
    // Remove trailing newline
    if (!time_str.empty() && time_str[time_str.length() - 1] == '\n') {
        time_str.erase(time_str.length() - 1);
    }
    
    return {
        {"current_time", time_str},
        {"timestamp", static_cast<long long>(std::chrono::duration_cast<std::chrono::seconds>(
            now.time_since_epoch()).count())}
    };
}

// Echo tool handler
mcp::json echo_handler(const mcp::json& params) {
    mcp::json result = params;
    
    if (params.contains("text")) {
        std::string text = params["text"];
        
        if (params.contains("uppercase") && params["uppercase"].get<bool>()) {
            std::transform(text.begin(), text.end(), text.begin(), ::toupper);
            result["text"] = text;
        }
        
        if (params.contains("reverse") && params["reverse"].get<bool>()) {
            std::reverse(text.begin(), text.end());
            result["text"] = text;
        }
    }
    
    return result;
}

// Calculator tool handler
mcp::json calculator_handler(const mcp::json& params) {
    if (!params.contains("operation")) {
        throw mcp::mcp_exception(mcp::error_code::invalid_params, "Missing 'operation' parameter");
    }
    
    std::string operation = params["operation"];
    double result = 0.0;
    
    if (operation == "add") {
        if (!params.contains("a") || !params.contains("b")) {
            throw mcp::mcp_exception(mcp::error_code::invalid_params, "Missing 'a' or 'b' parameter");
        }
        result = params["a"].get<double>() + params["b"].get<double>();
    } else if (operation == "subtract") {
        if (!params.contains("a") || !params.contains("b")) {
            throw mcp::mcp_exception(mcp::error_code::invalid_params, "Missing 'a' or 'b' parameter");
        }
        result = params["a"].get<double>() - params["b"].get<double>();
    } else if (operation == "multiply") {
        if (!params.contains("a") || !params.contains("b")) {
            throw mcp::mcp_exception(mcp::error_code::invalid_params, "Missing 'a' or 'b' parameter");
        }
        result = params["a"].get<double>() * params["b"].get<double>();
    } else if (operation == "divide") {
        if (!params.contains("a") || !params.contains("b")) {
            throw mcp::mcp_exception(mcp::error_code::invalid_params, "Missing 'a' or 'b' parameter");
        }
        if (params["b"].get<double>() == 0.0) {
            throw mcp::mcp_exception(mcp::error_code::invalid_params, "Division by zero not allowed");
        }
        result = params["a"].get<double>() / params["b"].get<double>();
    } else {
        throw mcp::mcp_exception(mcp::error_code::invalid_params, "Unknown operation: " + operation);
    }
    
    return {{"result", result}};
}

// Custom API endpoint handler
mcp::json hello_handler(const mcp::json& params) {
    std::string name = params.contains("name") ? params["name"].get<std::string>() : "World";
    return {{"message", "Hello, " + name + "!"}};
}

int main() {
    // Ensure file directory exists
    std::filesystem::create_directories("./files");
    
    // Create and configure server
    mcp::server server("localhost", 8080);
    server.set_server_info("ExampleServer", "2024-11-05");
    
    // Set server capabilities
    mcp::json capabilities = {
        {"tools", {{"listChanged", true}}},
        {"resources", {{"listChanged", true}}}
    };
    server.set_capabilities(capabilities);
    
    // Register method handlers
    server.register_method("ping", [](const mcp::json& params) {
        return mcp::json{{"pong", true}};
    });
    
    // Register tools
    mcp::tool time_tool = mcp::tool_builder("get_time")
        .with_description("Get current time")
        .build();
    
    mcp::tool echo_tool = mcp::tool_builder("echo")
        .with_description("Echo input with optional transformations")
        .with_string_param("text", "Text to echo")
        .with_boolean_param("uppercase", "Convert to uppercase", false)
        .with_boolean_param("reverse", "Reverse the text", false)
        .build();
    
    mcp::tool calc_tool = mcp::tool_builder("calculator")
        .with_description("Perform basic calculations")
        .with_string_param("operation", "Operation to perform (add, subtract, multiply, divide)")
        .with_number_param("a", "First operand")
        .with_number_param("b", "Second operand")
        .build();
    
    server.register_tool(time_tool, get_time_handler);
    server.register_tool(echo_tool, echo_handler);
    server.register_tool(calc_tool, calculator_handler);
    
    // Register resources
    auto file_resource = std::make_shared<mcp::file_resource>("./files");
    server.register_resource("/files", file_resource);
    
    auto api_resource = std::make_shared<mcp::api_resource>("API", "Custom API endpoints");
    api_resource->register_handler("hello", hello_handler, "Say hello");
    
    server.register_resource("/api", api_resource);
    
    // Start server
    std::cout << "Starting MCP server at localhost:8080..." << std::endl;
    std::cout << "Press Ctrl+C to stop the server" << std::endl;
    server.start(true);  // Blocking mode
    
    return 0;
} 