local ngx = ngx
local cjson = require "cjson"
local cache_manager = require "sm.service.cache_manager"
local cache_api = require "sm.service.cache_api"
local config_fetcher = require "sm.utils.config_fetcher"
local redis = require "sm.utils.redis"
local cache_utils = require "sm.utils.cache_utils"

local _M = {}

-- 处理缓存
function _M.handle(hostname)
    local zone_id = hostname["key"]
    local json_cache_config, hit_level, err = config_fetcher.getDomainConf(redis, zone_id .. ":cache_config")
    if err then
        return false, nil
    end
    -- 缓存规则为空
    if not json_cache_config then
        return false, nil
    end

    ngx.log(ngx.INFO, "cache config: " .. json_cache_config)

    local cache_configs = cjson.decode(json_cache_config)
    -- 构建缓存键
    if hostname["ignore_args"] == true then
        ngx.var.cache_key = ngx.var.host .. ngx.var.uri
    else
        ngx.var.cache_key = ngx.var.host .. ngx.var.request_uri
    end

    for _, cache_config in ipairs(cache_configs) do
        -- config的结构 {rule = "xxx", expiration_time = 3600}
        if cache_config.rule and ngx.re.find(ngx.var.uri, cache_config.rule) then
            ngx.log(ngx.INFO, "cache rule matched: " .. cache_config.rule .. " for uri: " .. ngx.var.uri)
            return true, cache_config
        end
    end
    return false, nil
end

-- 保存响应到缓存
-- function _M.save_response()
--     if not variables.get("need_cache") then
--         ngx.log(ngx.INFO, "no need to cache")
--         return
--     end

--     -- 只缓存成功的响应
--     if ngx.status ~= 200 and ngx.status ~= 302 then
--         ngx.log(ngx.INFO, "response status: " .. ngx.status)
--         return
--     end

--     -- 获取当前响应体数据块和是否是最后一个数据块的标志
--     local chunk, eof = ngx.arg[1], ngx.arg[2]

--     -- 初始化缓存文件
--     if not ngx.ctx.cache_file then
--         local cache_key = variables.get("cache_key")
--         local cache_ttl = variables.get("cache_ttl")
--         local file_path = cache_utils.get_cache_file_path(cache_key)

--         -- 确保目录存在
--         local dir = file_path:match("(.*/)")
--         os.execute("mkdir -p " .. dir)
--         -- 创建缓存文件
--         local file = io.open(file_path, "w+")
--         if not file then
--             ngx.log(ngx.ERR, "failed to open cache file: " .. file_path)
--             return
--         end

--         ngx.ctx.cache_file = file
--         variables.set("cache_size", 0)
--     end

--     -- 如果有数据块，写入缓存文件
--     if chunk and chunk ~= "" then
--         local file = ngx.ctx.cache_file
--         local ok, err = file:write(chunk)
--         if not ok then
--             ngx.log(ngx.ERR, "failed to write to cache file: " .. err)
--             file:close()
--             ngx.ctx.cache_file = nil
--             return
--         end
--         variables.set("cache_size", variables.get("cache_size") + #chunk)
--     end

--     -- 如果是最后一个数据块，完成缓存
--     if eof then
--         local file = ngx.ctx.cache_file
--         if file then
--             file:close()
--             cache_manager.save_response(variables.get("cache_key"), variables.get("cache_ttl"), variables.get("cache_size"))
--             ngx.log(ngx.INFO, "cache saved: " .. variables.get("cache_key"))
--         end
--     end
-- end

-- 处理API请求
function _M.handle_api()
    cache_api.handle_request()
end

return _M
