
import(Module_System)

-- Debug: confirm script file loaded at all
log("[record] script loading...")

-- Import with error checking
local ok, err = pcall(function() import(Module_ExternalInterface) end)
if not ok then
    log("[record] ERROR: failed to import Module_ExternalInterface: " .. tostring(err))
    log("[record] Is Module_ExternalInterface registered in Script4.h enum and Script4.cpp switch?")
    return
end
log("[record] Module_ExternalInterface imported OK")

import(Module_Defines)
import(Module_Game)
import(Module_Globals)
import(Module_Level)

-- Verify the ext_interface table exists
if type(ext_interface) ~= "table" then
    log("[record] ERROR: ext_interface is not a table, got: " .. type(ext_interface))
    return
end
log("[record] ext_interface table exists OK")

local server_started = false

function OnTurn()
    if not server_started then
        log("[record] calling ext_interface.start(27035, 'shared-token')...")
        local ok2, err2 = pcall(function()
            ext_interface.start(27035, "shared-token")
        end)
        if not ok2 then
            log("[record] ERROR: ext_interface.start failed: " .. tostring(err2))
            return
        end
        server_started = true
        log("[record] start() returned OK, is_running=" .. tostring(ext_interface.is_running()))
    end
    local ok3, err3 = pcall(function()
        ext_interface.process()
        local pending = ext_interface.pending_level()
        if pending >= 0 then
            ext_interface.clear_pending_level()
            change_level(pending)
        end
    end)
    if not ok3 then
        log("[record] ERROR in OnTurn: " .. tostring(err3))
    end
end

function OnPlayerDeath(player)
    ext_interface.notify_event("player_death", player)
end

log("[record] script loaded, waiting for OnLevelInit...")
