#pragma once

#include "MCPTransport.hpp"
#include <spdlog/spdlog.h>

#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <atomic>
#include <unordered_map>

#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>
#endif

namespace celuna::mcp {

/**
 * @brief Stdio transport for MCP servers
 *
 * Spawns a child process and communicates via stdin/stdout using JSON-RPC.
 */
class StdioTransport : public IMCPTransport {
public:
    StdioTransport(const MCPServerConfig& config);
    ~StdioTransport() override;

    bool start() override;
    void stop() override;
    bool isRunning() const override;

    JsonRpcResponse sendRequest(const JsonRpcRequest& request, int timeoutMs = 30000) override;
    void sendNotification(const std::string& method, const json& params) override;

private:
    MCPServerConfig m_config;
    std::shared_ptr<spdlog::logger> m_logger;

    std::atomic<bool> m_running{false};
    std::atomic<int> m_nextRequestId{1};

    // Process handles
#ifdef _WIN32
    HANDLE m_processHandle = nullptr;
    HANDLE m_stdinWrite = nullptr;
    HANDLE m_stdoutRead = nullptr;
#else
    pid_t m_pid = -1;
    int m_stdinFd = -1;
    int m_stdoutFd = -1;
#endif

    // Reader thread
    std::thread m_readerThread;
    std::mutex m_mutex;
    std::condition_variable m_responseCV;

    // Pending requests
    struct PendingRequest {
        std::mutex mutex;
        std::condition_variable cv;
        JsonRpcResponse response;
        bool hasResponse = false;
    };
    std::unordered_map<int, std::shared_ptr<PendingRequest>> m_pendingRequests;

    // Methods
    bool spawnProcess();
    void readerLoop();
    void writeLine(const std::string& line);
    std::string readLine();
    void handleMessage(const json& message);
};

} // namespace celuna::mcp
