local skynet = require "skynet"
local debug = require "skynet.debug"
local inject = require "skynet.inject"
----------------------------------------------------------------

local function debug_run(source, filename, ...)
    local args = table.pack(...)
    local ok, output = inject(skynet, source, filename, args, skynet.dispatch_message, skynet.register_protocol)
    skynet.ret(skynet.pack(ok, table.concat(output, "\n")))
end
debug.reg_debugcmd("SWT_RUN", debug_run)

local function debug_snapshot(len, ti)
    collectgarbage("collect")

    local lss = require "swt.lsnapshot"
    local json = require "json"
    lss.start_snapshot()

    if ti then
        ti = tonumber(ti)
    end
    ti = ti or 10
    skynet.sleep(ti * 100)

    if len then
        len = tonumber(len)
    end
    local rlen, diff = lss.dstop_snapshot(len)
    local ret = {
        ti = ti,
        rlen = rlen,
        len = len,
        diff = diff,
    }

    local filename = "zlogs/snapshot-" .. string.format("%08x", skynet.self()) .. "-" .. os.time() .. ".json"
    local file = assert(io.open(filename, "a"))
    local jsonstr = json.encode(ret)
    file:write(jsonstr)
    io.close(file)

    ret.diff = nil
    ret.filename = filename
    skynet.ret(skynet.pack(ret))
end

debug.reg_debugcmd("SWT_SNAPSHOT", debug_snapshot)

local hotfix_helper = require("hotfix.helper.hotfix_helper")
-- 热更新模块初始化
hotfix_helper.init()

-- hotfix_module_names = { "attribute.test_fight_attr" }
-- dbgcmd 00000025 SWT_HOTFIX attribute.test_fight_attr
local function debug_hotfix(module_name)
    hotfix_helper.add(module_name)
    skynet.ret(skynet.pack({}))
end

debug.reg_debugcmd("SWT_HOTFIX", debug_hotfix)

skynet.fork(function()
    while true do
        hotfix_helper.check()
        skynet.sleep(500)
    end
end)
