-- lua_sen/cli.lua: CLI definition DSL
-- Returns a table that senl-rs reads to build clap::Command

local M = {}

-- Command builder
local CmdBuilder = {}
CmdBuilder.__index = CmdBuilder

function CmdBuilder:arg(name, help, opts)
    opts = opts or {}
    self._args[#self._args + 1] = {
        name = name,
        help = help or "",
        required = opts.required ~= false,
    }
    return self
end

function CmdBuilder:flag(short, long, help)
    self._flags[#self._flags + 1] = {
        short = short,
        long = long,
        help = help or "",
    }
    return self
end

function CmdBuilder:option(short, long, help, opts)
    opts = opts or {}
    self._options[#self._options + 1] = {
        short = short,
        long = long,
        help = help or "",
        default = opts.default,
        required = opts.required or false,
    }
    return self
end

function CmdBuilder:done()
    return self._parent
end

-- App builder
local AppBuilder = {}
AppBuilder.__index = AppBuilder

function M.app(name, about)
    local self = setmetatable({}, AppBuilder)
    self._name = name
    self._about = about or ""
    self._version = ""
    self._commands = {}
    self._routes = {}
    return self
end

function AppBuilder:version(v)
    self._version = v
    return self
end

function AppBuilder:command(name, about)
    local cmd = setmetatable({
        _name = name,
        _about = about or "",
        _args = {},
        _flags = {},
        _options = {},
        _parent = self,
    }, CmdBuilder)
    self._commands[name] = cmd
    return cmd
end

function AppBuilder:route(name, handler)
    self._routes[name] = handler
    return self
end

function AppBuilder:build()
    local commands = {}
    for name, cmd in pairs(self._commands) do
        commands[name] = {
            about = cmd._about,
            args = cmd._args,
            flags = cmd._flags,
            options = cmd._options,
        }
    end
    return {
        name = self._name,
        about = self._about,
        version = self._version,
        commands = commands,
        routes = self._routes,
    }
end

return M
