#pragma once
// engine_orchestrator.h — Main Engine class declaration
// Ported from v1-monolithic/include/engine.hpp (Engine class) + engine.cpp (lines 428-684)
// Wires together all subsystems in the Iter2 modular architecture

#include "engine_subsystems.h"
#include "engine_bridge.h"
#include "engine_ollama.h"
#include "engine_config.h"
#include "engine_crypto.h"

#include <memory>
#include <atomic>
#include <cstdint>
#include <string>

// Forward declarations for payment/vault engines referenced by public pointers
class XmrEngine;
class TronEngine;
class StripeEngine;
class EtransferEngine;

namespace node669427 {
    class CryptoEngine;
}

namespace node669427 {
namespace subsys {

// ──────────────────────────────────────────────────────────────
// Engine — top-level orchestrator owning all subsystems
// ──────────────────────────────────────────────────────────────
class Engine {
public:
    explicit Engine(EngineConfig& cfg);
    ~Engine();

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

    void run();
    void shutdown();
    bool is_running() const { return running_.load(); }
    ServiceState state() const { return static_cast<ServiceState>(state_.load()); }
    NodeRole role() const { return cfg_.node_role; }
    void disguise();
    void handle_command(const OriginCommand& cmd);
    bool drop_privileges();

    // Public accessors for HttpServer / external modules
    XmrEngine* xmr = nullptr;
    TronEngine* tron = nullptr;
    StripeEngine* stripe = nullptr;
    EtransferEngine* etransfer = nullptr;
    OllamaClient* ollama = nullptr;

private:
    void init_crypto();
    void init_bridge();
    void start_subsystems();
    void stop_subsystems();
    void load_config();
    void event_loop();
    void process_command_queue();
    void collect_metrics();
    void check_health();
    uint8_t get_cpu_usage();
    uint8_t get_mem_usage();
    uint8_t get_disk_usage();
    uint32_t get_wg_peers();

    EngineConfig& cfg_;
    std::unique_ptr<node669427::CryptoEngine> crypto_;
    std::unique_ptr<OriginBridge> bridge_;
    std::unique_ptr<SubsysThreadPool> pool_;
    std::unique_ptr<HbMgr> hb_;
    std::unique_ptr<WdMgr> wd_;
    std::unique_ptr<DdMon> dd_;
    std::unique_ptr<FoMgr> fo_;
    std::unique_ptr<ScMgr> sc_;
    std::unique_ptr<FwMgr> fw_;
    std::unique_ptr<LdMgr> ld_;
    std::atomic<bool> running_{false};
    std::atomic<bool> shutdown_requested_{false};
    std::atomic<uint8_t> state_{static_cast<uint8_t>(ServiceState::STOPPED)};
    TSQueue<OriginCommand> command_queue_;
    std::atomic<uint8_t> cpu_pct_{0};
    std::atomic<uint8_t> mem_pct_{0};
    std::atomic<uint8_t> disk_pct_{0};
    std::atomic<uint32_t> wg_peer_count_{0};
    std::atomic<uint32_t> last_heartbeat_ack_{0};
    std::atomic<uint32_t> consecutive_timeouts_{0};
};

} // namespace subsys
} // namespace node669427
