#!/bin/bash

# CLI handler for `libreportal app tool list [<app>]`.
#
# Reads the generated apps-tools.json (single source of truth for the
# Tools tab + this CLI) and pretty-prints the available tools.
#
# Shapes:
#   libreportal app tool list             — every app + all its tools
#   libreportal app tool list <app>       — just <app>'s tools

cliAppToolList()
{
    local filter_app="$1"
    local manifest="$containers_dir/libreportal/frontend/data/apps/generated/apps-tools.json"

    if [[ ! -f "$manifest" ]]; then
        isError "apps-tools.json not found at $manifest. Run the WebUI updater to generate it."
        return 1
    fi

    if ! command -v jq >/dev/null 2>&1; then
        isError "jq is required to parse the tools manifest."
        return 1
    fi

    # Build a list of apps to print: either the filter or every key.
    local apps=()
    if [[ -n "$filter_app" ]]; then
        if ! jq -e --arg a "$filter_app" '.apps | has($a)' "$manifest" >/dev/null 2>&1; then
            isError "No tools found for app '$filter_app'."
            isNotice "Run 'libreportal app tool list' for the full set."
            return 1
        fi
        apps=("$filter_app")
    else
        mapfile -t apps < <(jq -r '.apps | keys[]' "$manifest")
    fi

    if [[ ${#apps[@]} -eq 0 ]]; then
        isNotice "No tools defined."
        return 0
    fi

    echo ""
    for app in "${apps[@]}"; do
        # App heading.
        echo "  $(tput bold 2>/dev/null)${app}$(tput sgr0 2>/dev/null)"
        echo ""

        # One row per tool: id, label, description, then field hints if any.
        jq -r --arg a "$app" '
            .apps[$a].tools[]
            | "    \(.id)  —  \(.label)\n      \(.description // "")\n"
              + (if (.fields // []) | length > 0 then
                  "      args: " + ([.fields[]
                    | "\(.name)" + (if .required then "*" else "" end)
                  ] | join("|"))
                else "      args: (none)" end)
        ' "$manifest"
        echo ""
    done

    echo "  Run a tool:"
    echo "    libreportal app tool <app> <tool_id> '<key>=<value>|<key>=<value>'"
    echo ""
    echo "  Field marked with * is required."
    echo ""
}
