#pragma once
#include "common.hpp"
#include "crypto.hpp"
#include "bridge.hpp"
#include "payment.hpp"
#include "ollama.hpp"
#include "vault.hpp"
#include <string>
#include <vector>
#include <map>
#include <functional>
#include <utility>
#include <thread>
#include <atomic>
#include <mutex>
#include <json/json.h>
#include <netinet/in.h>

enum ArtifactType : uint8_t {
    PAYMENT_INIT = 1,
    PAYMENT_STATUS = 2,
    PAYMENT_CANCEL = 3,
    EMAIL_PURCHASE = 4,
    EMAIL_BULK = 5,
    FULFILLMENT_START = 6,
    SECURITY_EVENT = 7,
    HEALTH_CHECK = 8,
    AI_QUERY = 9,
    VAULT_DECRYPT = 10
};

struct ArtifactRequest {
    ArtifactType type;
    std::string payload;
    std::vector<uint8_t> hmac;
    uint64_t timestamp;
    std::string node_id;
};

class Engine;

class HttpServer {
public:
    HttpServer(uint16_t port, Engine* engine);
    ~HttpServer();
    void start();
    void stop();
    bool running() const;
private:
    uint16_t port_;
    Engine* engine_;
    int sock_fd_;
    std::atomic<bool> running_;
    std::thread thread_;
    void accept_loop();
    void handle_client(int fd);
    std::string parse_request(const std::string& buf, std::string& method, std::string& path,
                               std::map<std::string, std::string>& hdrs, std::string& body);
    std::pair<int, std::string> route_request(const std::string& method, const std::string& path,
                               const std::map<std::string, std::string>& hdrs,
                               const std::string& body);
    void send_response(int fd, int code, const std::string& body,
                        const std::map<std::string, std::string>& extra_hdrs = {});
    bool verify_hmac(const ArtifactRequest& req);
};
