#include "camera_interface.h"
#include <mosis/sandbox/permission_gate.h>
#include <lua.hpp>

namespace mosis {

// CameraSession implementation

CameraSession::CameraSession(int id, const CameraConfig& config)
    : m_id(id)
    , m_config(config)
    , m_active(true)
{
    // Set default frame dimensions based on resolution
    switch (config.resolution) {
        case CameraResolution::VGA:
            m_last_frame.width = 640;
            m_last_frame.height = 480;
            break;
        case CameraResolution::HD:
            m_last_frame.width = 1280;
            m_last_frame.height = 720;
            break;
        case CameraResolution::FullHD:
            m_last_frame.width = 1920;
            m_last_frame.height = 1080;
            break;
    }
}

CameraSession::~CameraSession() {
    Stop();
}

CameraFrame CameraSession::Capture() {
    std::lock_guard<std::mutex> lock(m_mutex);

    if (!m_active) {
        return CameraFrame{};
    }

    // Return copy of last frame
    CameraFrame frame = m_last_frame;
    frame.timestamp_ms = static_cast<uint64_t>(
        std::chrono::duration_cast<std::chrono::milliseconds>(
            std::chrono::steady_clock::now().time_since_epoch()
        ).count()
    );

    return frame;
}

void CameraSession::Stop() {
    m_active = false;
}

void CameraSession::SimulateFrame(const CameraFrame& frame) {
    std::lock_guard<std::mutex> lock(m_mutex);

    if (!m_active) {
        return;
    }

    m_last_frame = frame;

    if (m_on_frame) {
        m_on_frame(frame);
    }
}

// CameraInterface implementation

CameraInterface::CameraInterface(const std::string& app_id, PermissionGate* permissions)
    : m_app_id(app_id)
    , m_permissions(permissions)
    , m_mock_mode(true)
{
}

CameraInterface::~CameraInterface() {
    Shutdown();
}

void CameraInterface::SimulateUserGesture() {
    m_last_gesture_time = std::chrono::steady_clock::now();
    m_has_gesture = true;
}

bool CameraInterface::HasRecentUserGesture() const {
    if (!m_has_gesture) {
        return false;
    }

    auto now = std::chrono::steady_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
        now - m_last_gesture_time
    ).count();

    return elapsed < GESTURE_VALIDITY_MS;
}

void CameraInterface::ShowIndicator() {
    m_indicator_visible = true;
    // In real implementation: notify system UI to show recording indicator
}

void CameraInterface::HideIndicator() {
    m_indicator_visible = false;
    // In real implementation: notify system UI to hide recording indicator
}

std::shared_ptr<CameraSession> CameraInterface::StartSession(const CameraConfig& config, std::string& error) {
    std::lock_guard<std::mutex> lock(m_mutex);

    // Check permission
    if (m_permissions && !m_permissions->HasPermission("camera")) {
        error = "Camera permission not granted";
        return nullptr;
    }

    // Check user gesture
    if (!HasRecentUserGesture()) {
        error = "Camera requires recent user gesture";
        return nullptr;
    }

    // Check for existing session
    if (m_active_session && m_active_session->IsActive()) {
        error = "Camera session already active";
        return nullptr;
    }

    // Create new session
    int id = m_next_session_id++;
    m_active_session = std::make_shared<CameraSession>(id, config);

    // Show recording indicator
    ShowIndicator();

    // In mock mode, session is created but no real camera access
    // In real implementation: start camera hardware

    return m_active_session;
}

void CameraInterface::StopSession() {
    std::lock_guard<std::mutex> lock(m_mutex);

    if (m_active_session) {
        m_active_session->Stop();
        m_active_session.reset();
        HideIndicator();
    }
}

bool CameraInterface::HasActiveSession() const {
    std::lock_guard<std::mutex> lock(m_mutex);
    return m_active_session && m_active_session->IsActive();
}

bool CameraInterface::IsIndicatorVisible() const {
    return m_indicator_visible;
}

void CameraInterface::Shutdown() {
    StopSession();
}

// Lua API implementation

// Userdata for CameraSession
struct LuaCameraSession {
    std::weak_ptr<CameraSession> session;
    int id;
};

static const char* CAMERA_SESSION_MT = "mosis.CameraSession";

// Get CameraInterface from upvalue
static CameraInterface* GetCameraInterface(lua_State* L) {
    return static_cast<CameraInterface*>(lua_touserdata(L, lua_upvalueindex(1)));
}

// Get CameraSession from userdata
static LuaCameraSession* GetCameraSession(lua_State* L, int index) {
    return static_cast<LuaCameraSession*>(luaL_checkudata(L, index, CAMERA_SESSION_MT));
}

// session:capture() -> frame or nil
static int L_session_capture(lua_State* L) {
    LuaCameraSession* lcs = GetCameraSession(L, 1);

    auto session = lcs->session.lock();
    if (!session || !session->IsActive()) {
        lua_pushnil(L);
        return 1;
    }

    CameraFrame frame = session->Capture();

    // Return frame as table
    lua_newtable(L);

    // frame.width
    lua_pushinteger(L, frame.width);
    lua_setfield(L, -2, "width");

    // frame.height
    lua_pushinteger(L, frame.height);
    lua_setfield(L, -2, "height");

    // frame.timestamp
    lua_pushinteger(L, static_cast<lua_Integer>(frame.timestamp_ms));
    lua_setfield(L, -2, "timestamp");

    // frame.data (as string for binary data)
    if (!frame.data.empty()) {
        lua_pushlstring(L, reinterpret_cast<const char*>(frame.data.data()), frame.data.size());
    } else {
        lua_pushstring(L, "");
    }
    lua_setfield(L, -2, "data");

    // frame.is_jpeg
    lua_pushboolean(L, frame.is_jpeg ? 1 : 0);
    lua_setfield(L, -2, "is_jpeg");

    return 1;
}

// session:stop()
static int L_session_stop(lua_State* L) {
    LuaCameraSession* lcs = GetCameraSession(L, 1);

    auto session = lcs->session.lock();
    if (session) {
        session->Stop();
    }

    // Also stop via interface to hide indicator
    CameraInterface* camera = static_cast<CameraInterface*>(
        lua_touserdata(L, lua_upvalueindex(1))
    );
    if (camera) {
        camera->StopSession();
    }

    return 0;
}

// session:on(event, callback)
static int L_session_on(lua_State* L) {
    LuaCameraSession* lcs = GetCameraSession(L, 1);

    auto session = lcs->session.lock();
    if (!session) {
        return 0;
    }

    const char* event = luaL_checkstring(L, 2);
    luaL_checktype(L, 3, LUA_TFUNCTION);

    // For now, simplified implementation that doesn't store callbacks
    // A full implementation would need to store refs and call them on events

    lua_pushboolean(L, 1);
    return 1;
}

// session:isActive() -> bool
static int L_session_isActive(lua_State* L) {
    LuaCameraSession* lcs = GetCameraSession(L, 1);

    auto session = lcs->session.lock();
    lua_pushboolean(L, session && session->IsActive() ? 1 : 0);
    return 1;
}

// CameraSession garbage collection
static int L_session_gc(lua_State* L) {
    LuaCameraSession* lcs = GetCameraSession(L, 1);

    auto session = lcs->session.lock();
    if (session && session->IsActive()) {
        session->Stop();
    }

    return 0;
}

// camera.start(config) -> session, error
static int L_camera_start(lua_State* L) {
    CameraInterface* camera = GetCameraInterface(L);
    if (!camera) {
        lua_pushnil(L);
        lua_pushstring(L, "CameraInterface not available");
        return 2;
    }

    CameraConfig config;

    // Parse config table if provided
    if (lua_istable(L, 1)) {
        // facing
        lua_getfield(L, 1, "facing");
        if (lua_isstring(L, -1)) {
            std::string facing = lua_tostring(L, -1);
            if (facing == "front") {
                config.facing = CameraFacing::Front;
            } else {
                config.facing = CameraFacing::Back;
            }
        }
        lua_pop(L, 1);

        // resolution
        lua_getfield(L, 1, "resolution");
        if (lua_isstring(L, -1)) {
            std::string res = lua_tostring(L, -1);
            if (res == "480p" || res == "vga") {
                config.resolution = CameraResolution::VGA;
            } else if (res == "1080p" || res == "fullhd") {
                config.resolution = CameraResolution::FullHD;
            } else {
                config.resolution = CameraResolution::HD;
            }
        }
        lua_pop(L, 1);

        // fps
        lua_getfield(L, 1, "fps");
        if (lua_isnumber(L, -1)) {
            config.max_fps = static_cast<int>(lua_tointeger(L, -1));
            if (config.max_fps > 30) config.max_fps = 30;
            if (config.max_fps < 1) config.max_fps = 1;
        }
        lua_pop(L, 1);
    }

    std::string error;
    auto session = camera->StartSession(config, error);

    if (!session) {
        lua_pushnil(L);
        lua_pushstring(L, error.c_str());
        return 2;
    }

    // Create userdata
    LuaCameraSession* lcs = static_cast<LuaCameraSession*>(
        lua_newuserdata(L, sizeof(LuaCameraSession))
    );
    lcs->session = session;
    lcs->id = session->GetId();

    // Set metatable
    luaL_getmetatable(L, CAMERA_SESSION_MT);
    lua_setmetatable(L, -2);

    return 1;
}

// camera.isActive() -> bool
static int L_camera_isActive(lua_State* L) {
    CameraInterface* camera = GetCameraInterface(L);
    if (!camera) {
        lua_pushboolean(L, 0);
        return 1;
    }

    lua_pushboolean(L, camera->HasActiveSession() ? 1 : 0);
    return 1;
}

// camera.stop()
static int L_camera_stop(lua_State* L) {
    CameraInterface* camera = GetCameraInterface(L);
    if (camera) {
        camera->StopSession();
    }
    return 0;
}

// Helper to set a global in the real _G (bypassing any proxy)
static void SetGlobalInRealG(lua_State* L, const char* name) {
    lua_rawgeti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS);

    if (lua_getmetatable(L, -1)) {
        lua_getfield(L, -1, "__index");
        if (lua_istable(L, -1)) {
            lua_pushvalue(L, -4);
            lua_setfield(L, -2, name);
            lua_pop(L, 4);
            return;
        }
        lua_pop(L, 2);
    }

    lua_pushvalue(L, -2);
    lua_setfield(L, -2, name);
    lua_pop(L, 2);
}

void RegisterCameraAPI(lua_State* L, CameraInterface* camera) {
    // Create CameraSession metatable
    luaL_newmetatable(L, CAMERA_SESSION_MT);

    lua_pushstring(L, "__index");
    lua_newtable(L);

    // Methods with camera interface as upvalue for stop
    lua_pushlightuserdata(L, camera);
    lua_pushcclosure(L, L_session_capture, 1);
    lua_setfield(L, -2, "capture");

    lua_pushlightuserdata(L, camera);
    lua_pushcclosure(L, L_session_stop, 1);
    lua_setfield(L, -2, "stop");

    lua_pushcfunction(L, L_session_on);
    lua_setfield(L, -2, "on");

    lua_pushcfunction(L, L_session_isActive);
    lua_setfield(L, -2, "isActive");

    lua_settable(L, -3);  // Set __index

    // GC metamethod
    lua_pushstring(L, "__gc");
    lua_pushcfunction(L, L_session_gc);
    lua_settable(L, -3);

    lua_pop(L, 1);  // Pop metatable

    // Create camera table
    lua_newtable(L);

    // camera.start
    lua_pushlightuserdata(L, camera);
    lua_pushcclosure(L, L_camera_start, 1);
    lua_setfield(L, -2, "start");

    // camera.isActive
    lua_pushlightuserdata(L, camera);
    lua_pushcclosure(L, L_camera_isActive, 1);
    lua_setfield(L, -2, "isActive");

    // camera.stop
    lua_pushlightuserdata(L, camera);
    lua_pushcclosure(L, L_camera_stop, 1);
    lua_setfield(L, -2, "stop");

    // Set as global
    SetGlobalInRealG(L, "camera");
}

} // namespace mosis
