local msg = require('mp.msg')
local utils = require("mp.utils")

local repo = "Tony15246/uosc_danmaku"

local local_version = VERSION or "0.0.0"

local function version_greater(v1, v2)
    local function parse(ver)
        local a, b, c = ver:match("v?(%d+)%.(%d+)%.(%d+)")
        return tonumber(a), tonumber(b), tonumber(c)
    end
    local a1, a2, a3 = parse(v1)
    local b1, b2, b3 = parse(v2)
    if a1 ~= b1 then return a1 > b1 end
    if a2 ~= b2 then return a2 > b2 end
    return a3 > b3
end

local function get_latest_release(repo)
    local url = "https://api.github.com/repos/" .. repo .. "/releases/latest"
    local cmd = { "curl", "-sL", url }
    local res = mp.command_native({
        name = "subprocess",
        args = cmd,
        capture_stdout = true,
        capture_stderr = true,
        playback_only = false,
    })
    if not res or res.status ~= 0 then return nil end
    local tag = res.stdout:match([["tag_name"%s*:%s*"([^"]+)"]])
    return tag
end

-- 仅检查并提示新版本，不自动下载/覆盖（避免 rm -rf 破坏配置）
function check_for_update()
    local latest_version = get_latest_release(repo)
    if not latest_version then
        show_message("无法获取最新版本信息")
        msg.warn("无法获取最新版本信息")
        return
    end

    if not version_greater(latest_version, local_version) then
        show_message("uosc_danmaku 已是最新版本 (" .. local_version .. ")")
        msg.info("uosc_danmaku 已是最新版本 (" .. local_version .. ")")
        return
    end

    local update_url = "https://github.com/" .. repo .. "/releases/tag/" .. latest_version
    show_message("uosc_danmaku 有新版本: " .. latest_version .. " (当前: " .. local_version .. ")\n请手动更新: " .. update_url)
    msg.info("uosc_danmaku 新版本: " .. latest_version .. " 下载地址: " .. update_url)
end
