--:Minify:--
-- HyperionOS NeetComputers initdisks.
-- Adapts the NeetComputers files API (disks x partitions) to the Hyperion
-- disk interface documented in docs/kernel/bootloaders/diskAPI.
--
-- Addresses look like "0:hyperion" (disk slot + partition name); the boot
-- partition is additionally aliased as "$".
--
-- NeetComputers file headers are snapshots: reads see the file as it was at
-- open time and writes only persist on flush/close (and always append). This
-- adapter keeps a Lua-side buffer per open handle so that read/seek/write
-- behave like regular POSIX files. Flush rewrites the whole file.

local args = {...}
local apis = args[1]
local bootDisk = args[2]
local bootPart = args[3]

local files = apis.files

local function fp(part, path)
    if not path or path == "" then path = "/" end
    if path:sub(1, 1) ~= "/" then path = "/" .. path end
    return part .. ":" .. path
end

local function normParts(raw)
    if type(raw) ~= "table" then return {} end
    -- tolerate a doubly-wrapped list
    if type(raw[1]) == "table" and raw[1].name == nil and #raw == 1 then
        raw = raw[1]
    end
    local out = {}
    for _, p in ipairs(raw) do
        local name = type(p) == "table" and p.name or p
        if type(name) == "string" and name ~= "" then
            out[#out + 1] = name
        end
    end
    return out
end

local function diskSlots()
    local out = {}
    local ok, raw = pcall(files.getDisks)
    if ok and type(raw) == "table" then
        for _, d in ipairs(raw) do
            local slot = type(d) == "table" and (d.slot or d[1]) or d
            if type(slot) == "number" then
                out[#out + 1] = slot
            end
        end
    end
    if #out == 0 then out = {0} end
    table.sort(out)
    return out
end

local function partReadOnly(slot, part)
    local ok, info = pcall(files.getPartition, part, slot)
    if ok and type(info) == "table" then
        return info.readonly == true
    end
    return false
end

local function createDisk(id, slot, part)
    local readonly = partReadOnly(slot, part)
    local disk = {
        address = id,
        isReadOnly = function() return readonly end
    }

    function disk:spaceUsed() return 0 end
    function disk:spaceTotal() return 2 ^ 40 end

    function disk:list(path)
        local ok, r = pcall(files.getChildren, fp(part, path), slot)
        if not ok or type(r) ~= "table" then return nil, "not directory" end
        local out = {}
        for _, n in ipairs(r) do
            if type(n) == "string" then out[#out + 1] = n end
        end
        return out
    end

    function disk:fileExists(path)
        local ok, r = pcall(files.exists, fp(part, path), slot)
        if not (ok and r) then return false end
        local ok2, d = pcall(files.isDir, fp(part, path), slot)
        if ok2 and d then return false end
        return true
    end

    function disk:directoryExists(path)
        if not path or path == "" or path == "/" then return true end
        local ok, r = pcall(files.isDir, fp(part, path), slot)
        return ok and r == true
    end

    function disk:type(path)
        local ok, r = pcall(files.exists, fp(part, path), slot)
        if not (ok and r) then return nil end
        local ok2, d = pcall(files.isDir, fp(part, path), slot)
        if ok2 and d then return "directory" end
        return "file"
    end

    function disk:makeDirectory(path)
        local ok, r = pcall(files.makeDir, fp(part, path), slot)
        if not ok then return nil, "cannot create directory" end
        if r == false then return nil, "cannot create directory" end
        return true
    end

    function disk:remove(path)
        local ok, r = pcall(files.delete, fp(part, path), slot)
        if not ok then return nil, "cannot delete" end
        if r == false then return nil, "cannot delete" end
        return true
    end

    function disk:setLabel(label) return true end
    function disk:getLabel() return part end

    function disk:attributes(path)
        local isDir = self:directoryExists(path)
        local size = 0
        if not isDir then
            local ok, h = pcall(files.open, fp(part, path), "r", slot)
            if ok and h then
                local ok2, data = pcall(h.read, "a")
                pcall(h.close)
                if ok2 and type(data) == "string" then size = #data end
            end
        end
        return {
            size = size,
            isDir = isDir,
            isReadOnly = readonly,
            modified = 0,
            created = 0
        }
    end

    function disk:open(path, mode)
        mode = mode or "r"
        local wantWrite = mode ~= "r" and mode ~= "rb"

        -- Snapshot the current content with a dedicated read handle.
        -- ("a"/"ab" headers are not readable themselves, and every header
        -- only appends, so all POSIX read/write/seek behavior below runs
        -- on this Lua-side buffer; persist() rewrites the file on flush.)
        local buf = ""
        if mode ~= "w" and mode ~= "wb" then
            local okR, hr = pcall(files.open, fp(part, path), "r", slot)
            if okR and hr then
                local okD, data = pcall(hr.read, "a")
                pcall(hr.close)
                if okD and type(data) == "string" then buf = data end
            end
        end

        local ok, h = pcall(files.open, fp(part, path), mode, slot)
        if not ok or not h then
            return nil, "file not found or access denied"
        end
        -- The live header is only needed to prove the open mode is valid
        -- (existence/creation); persist() reopens the file itself.
        pcall(h.close)

        local pos = 1
        if mode == "w" or mode == "wb" then
            buf = ""
        else
            pos = #buf + 1
            if mode == "r" or mode == "rb" or mode == "r+" or mode == "rb+"
                or mode == "r+b" or mode == "w+" or mode == "wb+"
                or mode == "w+b" then
                pos = 1
            end
        end

        local closed = false
        local handle = {}

        function handle.read(n)
            if closed then error("EBADF") end
            if type(n) == "number" then
                if n <= 0 then return nil end
                if pos > #buf then return nil end
                local chunk = buf:sub(pos, pos + n - 1)
                pos = pos + #chunk
                if chunk == "" then return nil end
                return chunk
            end
            local fmt = n or "l"
            if pos > #buf then return nil end
            if fmt == "a" then
                local chunk = buf:sub(pos)
                pos = #buf + 1
                return chunk
            elseif fmt == "l" or fmt == "L" then
                local s, e = buf:find("\n", pos, true)
                if not s then
                    local chunk = buf:sub(pos)
                    pos = #buf + 1
                    return chunk
                end
                local chunk
                if fmt == "l" then chunk = buf:sub(pos, s - 1)
                else chunk = buf:sub(pos, s) end
                pos = s + 1
                return chunk
            else
                error("EINVAL")
            end
        end

        function handle.readAll()
            if closed then error("EBADF") end
            local chunk = buf:sub(pos)
            pos = #buf + 1
            return chunk
        end

        function handle.write(data)
            if closed then error("EBADF") end
            if not wantWrite then error("EACCES") end
            data = tostring(data)
            local before = buf:sub(1, pos - 1)
            local after = buf:sub(pos + #data)
            buf = before .. data .. after
            pos = pos + #data
            return true
        end

        function handle.seek(whence, offset)
            if closed then error("EBADF") end
            whence = whence or "cur"
            offset = offset or 0
            local base
            if whence == "set" then base = 1
            elseif whence == "cur" then base = pos
            elseif whence == "end" then base = #buf + 1
            else error("EINVAL") end
            local np = base + offset
            if whence == "end" and offset > 0 then error("EINVAL") end
            if np < 1 then error("EINVAL") end
            if np > #buf + 1 then error("EINVAL") end
            pos = np
            return pos - 1
        end

        local function persist()
            if not wantWrite then return true end
            local ok2, h2 = pcall(files.open, fp(part, path), "w", slot)
            if not ok2 or not h2 then return nil, "flush failed" end
            if #buf > 0 then
                local ok3, err = pcall(h2.write, buf)
                if not ok3 then pcall(h2.close) return nil, err end
            end
            local ok4, err = pcall(h2.flush)
            pcall(h2.close)
            if not ok4 then return nil, err end
            return true
        end

        function handle.flush()
            if closed then error("EBADF") end
            local ok2, err = persist()
            if not ok2 then error(err or "EIO") end
            return true
        end

        function handle.close()
            if closed then return true end
            closed = true
            if wantWrite then pcall(persist) end
            buf = ""
            return true
        end

        return handle
    end

    return disk
end

local internal = {}
local disks = {}

internal["$"] = createDisk("$", bootDisk, bootPart)

local function refresh()
    disks = {}
    for _, slot in ipairs(diskSlots()) do
        local ok, raw = pcall(files.getPartitions, slot)
        if ok and type(raw) == "table" then
            for _, part in ipairs(normParts(raw)) do
                if not (slot == bootDisk and part == bootPart) then
                    local addr = tostring(slot) .. ":" .. part
                    disks[addr] = createDisk(addr, slot, part)
                end
            end
        end
    end
end

local function iter()
    refresh()
    local combined = {}
    for id, obj in pairs(internal) do combined[id] = obj end
    for id, obj in pairs(disks) do combined[id] = obj end
    return pairs(combined)
end

return {refresh = refresh, list = iter}
