// sandbox_manager.h - Multi-app sandbox orchestrator
// Milestone 20: Kernel Integration
#pragma once

// Core library headers (shared across platforms)
#include <mosis/sandbox/lua_sandbox.h>
#include <mosis/sandbox/permission_gate.h>
#include <mosis/sandbox/audit_log.h>
#include <mosis/sandbox/rate_limiter.h>
#include <mosis/sandbox/timer_manager.h>
#include <mosis/sandbox/virtual_fs.h>
#include <mosis/sandbox/database_manager.h>
#include <mosis/sandbox/network_manager.h>
#include <mosis/sandbox/json_api.h>
#include <mosis/sandbox/crypto_api.h>

// Android-specific hardware interfaces
#include "websocket_manager.h"
#include "camera_interface.h"
#include "microphone_interface.h"
#include "audio_output.h"
#include "location_interface.h"
#include "sensor_interface.h"
#include "bluetooth_interface.h"
#include "contacts_interface.h"
#include "message_bus.h"

#include <memory>
#include <unordered_map>
#include <string>
#include <mutex>
#include <functional>

namespace mosis {

// Per-app sandbox instance with all components
struct AppSandbox {
    std::unique_ptr<LuaSandbox> lua;
    std::unique_ptr<PermissionGate> permissions;
    std::unique_ptr<VirtualFS> filesystem;
    std::unique_ptr<DatabaseManager> database;
    std::unique_ptr<NetworkManager> network;
    std::unique_ptr<WebSocketManager> websocket;
    std::unique_ptr<CameraInterface> camera;
    std::unique_ptr<MicrophoneInterface> microphone;
    std::unique_ptr<AudioOutputInterface> audio;
    std::unique_ptr<LocationInterface> location;
    std::unique_ptr<SensorInterface> sensors;
    std::unique_ptr<BluetoothInterface> bluetooth;
    std::unique_ptr<ContactsInterface> contacts;
    SandboxContext context;
    bool is_running = false;
};

// Callback for recording user gestures (from UI events)
using UserGestureCallback = std::function<void(const std::string& app_id)>;

class LuaSandboxManager {
public:
    explicit LuaSandboxManager(const std::string& data_root = ".");
    ~LuaSandboxManager();

    // Prevent copying
    LuaSandboxManager(const LuaSandboxManager&) = delete;
    LuaSandboxManager& operator=(const LuaSandboxManager&) = delete;

    // App lifecycle
    bool StartApp(const std::string& app_id, const std::string& app_path,
                  const std::vector<std::string>& permissions,
                  bool is_system_app = false);
    bool StopApp(const std::string& app_id);
    bool IsAppRunning(const std::string& app_id) const;

    // Get app sandbox for direct access
    AppSandbox* GetApp(const std::string& app_id);
    const AppSandbox* GetApp(const std::string& app_id) const;

    // Execute Lua code in app context
    bool ExecuteCode(const std::string& app_id, const std::string& code,
                     const std::string& source_name = "script");
    bool LoadFile(const std::string& app_id, const std::string& path);

    // User gesture tracking (for permission-sensitive operations)
    void RecordUserGesture(const std::string& app_id);

    // Timer management - called from main loop
    void UpdateTimers();

    // Get all running app IDs
    std::vector<std::string> GetRunningApps() const;

    // Shared components
    AuditLog& GetAuditLog() { return m_audit_log; }
    RateLimiter& GetRateLimiter() { return m_rate_limiter; }
    MessageBus& GetMessageBus() { return m_message_bus; }
    TimerManager& GetTimerManager() { return m_timer_manager; }

    // Configuration
    void SetDefaultLimits(const SandboxLimits& limits) { m_default_limits = limits; }
    const SandboxLimits& GetDefaultLimits() const { return m_default_limits; }

    // Stats
    size_t GetRunningAppCount() const;

private:
    // Create and configure a new app sandbox
    std::unique_ptr<AppSandbox> CreateAppSandbox(const SandboxContext& ctx);

    // Register all Lua APIs with sandbox
    void RegisterAPIs(AppSandbox& app);

    // Clean up app resources
    void CleanupApp(AppSandbox& app);

    // Data storage
    std::string m_data_root;
    mutable std::mutex m_mutex;
    std::unordered_map<std::string, std::unique_ptr<AppSandbox>> m_apps;

    // Shared components across all apps
    AuditLog m_audit_log;
    RateLimiter m_rate_limiter;
    MessageBus m_message_bus;
    TimerManager m_timer_manager;

    // Default limits for new sandboxes
    SandboxLimits m_default_limits;
};

} // namespace mosis
