local _M = {}

function _M.md5(str)
    return ngx.md5(str)
end

function _M.sha256(str)
    local resty_sha256 = require "resty.sha256"
    local restystr= require "resty.string"
    local sha256 = resty_sha256:new()
    sha256:update(str)
    local digest = sha256:final()
    return restystr.to_hex(digest)
end

local function get_auth_key(uri,timestamp, rand, uid, key,sign_func)
    local sign_string = string.format("%s-%s-%s-%s-%s", uri, timestamp, rand, uid, key)
    local hash_str = ""
    if sign_func=="md5" then
        hash_str =  md5(sign_string)
    elseif sign_func == "sha256" then
        hash_str = sha256(sign_string)
    end
    return string.format("%s-%s-%s-%s", timestamp, rand, uid, hash_str)
end

function _M.process_m3u8_file(whole, timestamp, rand, uid, key,sign_func)
    local new_lines = {}
    -- 遍历lines表中的每一行
    for line in string.gmatch(whole, "[^\n]+") do
        if line:match("^#EXT-X-MAP::URI=") then
            -- 处理 #EXT-X-MAP 标签
            local uri = line:match('URI="([^"]+)"')
            if uri then
                -- 使用 string.match 函数提取 URI 部分
                local path = uri:match("^[^:]+://[^/]+(/[^?]+)")
                local auth_key = get_auth_key(path, timestamp, rand,uid, key,sign_func)
                line = line:gsub('URI="([^"]+)"', 'URI="' .. uri .. "?auth_key=" .. auth_key .. '"')
            end
        elseif not line:match("^#") then
            -- 处理非 # 开头的行
            -- 使用 string.match 函数提取 URI 部分
            local path = line:match("^[^:]+://[^/]+(/[^?]+)")
            local auth_key = get_auth_key(path, timestamp,rand, uid, key,sign_func)
            line =  line .. "?auth_key=" .. auth_key
        end
        table.insert(new_lines, line)
    end
    return table.concat(new_lines, "\n")
end

return _M