#pragma once

#include "engine_config.h"
#include "engine_crypto.h"
#include "engine_vault.h"
#include "engine_security.h"
#include "engine_artifact.h"
#include "engine_payment.h"
#include "engine_email.h"
#include "engine_fulfillment.h"

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <thread>
#include <atomic>
#include <vector>
#include <queue>
#include <condition_variable>
#include <functional>
#include <memory>

namespace node669427 {

struct HttpRequest {
    std::string method;
    std::string path;
    std::string body;
    std::unordered_map<std::string, std::string> headers;
    std::string client_ip;
};

class ThreadPool {
public:
    explicit ThreadPool(size_t threads);
    ~ThreadPool();
    void enqueue(std::function<void()> task);
    void stop();
private:
    std::vector<std::thread> workers_;
    std::queue<std::function<void()>> tasks_;
    std::mutex queue_mutex_;
    std::condition_variable condition_;
    std::atomic<bool> running_{true};
};

class HttpServer {
public:
    HttpServer(NodeConfig& config, CryptoEngine& crypto, VaultPtr vault,
               SecurityEngine& security, ArtifactProcessor& artifacts,
               PaymentProcessor& payments, EmailDispatcher& email,
               FulfillmentEngine& fulfillment);
    ~HttpServer();

    bool start();
    void stop();
    void run();
    bool is_running() const { return running_.load(); }

private:
    NodeConfig& config_;
    CryptoEngine& crypto_;
    VaultPtr vault_;
    SecurityEngine& security_;
    ArtifactProcessor& artifacts_;
    PaymentProcessor& payments_;
    EmailDispatcher& email_;
    FulfillmentEngine& fulfillment_;

    int server_fd_ = -1;
    std::atomic<bool> running_{false};
    std::unique_ptr<ThreadPool> thread_pool_;

    std::string parse_method(const std::string& request);
    std::string parse_path(const std::string& request);
    std::string parse_body(const std::string& request);
    std::unordered_map<std::string, std::string> parse_headers(const std::string& request);
    std::string extract_path_param(const std::string& path, size_t segment);

    void send_response(int client_fd, int status, const std::string& body);
    void handle_client(int client_fd, const std::string& client_ip);
    std::string route_request(const HttpRequest& req);

    std::string handle_artifact(const HttpRequest& req);
    std::string handle_health(const HttpRequest& req);
    std::string handle_status(const HttpRequest& req);
    std::string handle_payment_init(const HttpRequest& req);
    std::string handle_payment_status(const HttpRequest& req);
    std::string handle_email_send(const HttpRequest& req);
    std::string handle_fulfillment_start(const HttpRequest& req);
    std::string handle_security_events(const HttpRequest& req);
    std::string handle_ai_infer(const HttpRequest& req);

    bool validate_hmac(const HttpRequest& req) const;
};

} // namespace node669427
