#pragma once
// engine_bridge.h — OriginBridge class declaration
// Ported from v1-monolithic/include/bridge.hpp → Iter2 modular architecture
// Uses nlohmann/json instead of jsoncpp

#include "engine_subsystems.h"
#include "json.hpp"

#include <curl/curl.h>
#include <atomic>
#include <string>
#include <vector>
#include <cstdint>
#include <fstream>
#include <sstream>
#include <stdexcept>

// Forward declaration
namespace node669427 {
    class CryptoEngine;
}

namespace node669427 {
namespace subsys {

// ──────────────────────────────────────────────────────────────
// CmdType enum + OriginCommand (from v1 bridge.hpp)
// ──────────────────────────────────────────────────────────────

enum CmdType : uint8_t {
    UNKNOWN = 0,
    UPDATE_RULES = 1,
    EXEC_SCRIPT = 2,
    REBOOT = 3,
    STATUS_REQ = 4,
    LOCKDOWN = 5,
    RECOVER = 6,
    CONFIG_PUSH = 7,
    PING = 8
};
typedef CmdType OriginCommandType;

struct OriginCommand {
    CmdType type = UNKNOWN;
    uint32_t seq = 0;
    uint32_t timestamp = 0;
    uint32_t node_id = 0;
    std::string payload;
    std::vector<uint8_t> hmac;

    bool valid() const { return type != UNKNOWN; }
};

// ──────────────────────────────────────────────────────────────
// OriginBridge — curl-based HTTP communication with HMAC signing
// ──────────────────────────────────────────────────────────────

class OriginBridge {
public:
    struct SignedRequest {
        std::string method;
        std::string path;
        std::string body;
        std::string x_node_id;
        std::string x_timestamp;
        std::string x_counter;
        std::string x_signature;
    };

    OriginBridge(const std::string& origin_url, const std::string& node_id, CryptoEngine& crypto);
    ~OriginBridge();

    OriginBridge(const OriginBridge&) = delete;
    OriginBridge& operator=(const OriginBridge&) = delete;

    // CRY-02: HMAC signing — format: ts.nonce.METHOD.path.body
    SignedRequest sign_request(const std::string& method, const std::string& path, const std::string& body);

    bool verify_response(const std::vector<uint8_t>& data, const uint8_t* hmac) const;
    bool verify_response_hex(const std::vector<uint8_t>& data, const std::string& hmac_hex) const;

    bool send_event(const SecurityEventPacket& event, const std::string& payload = "");
    bool send_firewall_rules(const std::vector<FirewallRule>& rules);
    bool send_heartbeat(uint8_t cpu, uint8_t mem, uint8_t disk, uint32_t peers,
                        ServiceState state, NodeRole role);
    OriginCommand receive_command();
    bool report_result(uint32_t seq, bool success, const std::string& output, const std::string& error = "");
    bool send_status_report(NodeRole role, ServiceState state, const std::string& details);

private:
    std::string origin_url_;
    std::string node_id_;
    CryptoEngine& crypto_ref_;
    CURL* curl_;
    SecureBuffer<32> hmac_key_;
    std::atomic<uint64_t> counter_{1};
    std::atomic<uint32_t> last_seq_{0};
    std::atomic<uint32_t> last_ts_{0};
    static constexpr uint32_t TS_WINDOW_S = 300;

    void load_hmac_key();
    bool check_replay(uint32_t seq, uint32_t timestamp);

    static size_t curl_write_cb(void* contents, size_t size, size_t nmemb, void* userp);
    struct curl_slist* build_headers(const SignedRequest& req, const std::string& content_type) const;

    bool http_post(const std::string& url, const std::vector<uint8_t>& data, const SignedRequest& req);
    bool http_post(const std::string& url, const std::string& body, const SignedRequest& req);
    bool http_get(const std::string& url, std::string& response, const SignedRequest& req, long* out_http_code = nullptr);
};

} // namespace subsys
} // namespace node669427
