#!/usr/bin/env bash
# wt — CLI per la libreria di prompt work-toolkit
# Vedi: docs/cli.md

set -eu

VERSION="2.0.0"

# --- Risolve TOOLKIT_HOME (gestisce symlink, e.g. ~/bin/wt → repo/bin/wt)
resolve_wt_home() {
    local target dir
    target="${BASH_SOURCE[0]}"
    while [ -L "$target" ]; do
        dir="$(cd "$(dirname "$target")" && pwd)"
        target="$(readlink "$target")"
        case "$target" in
            /*) ;;
            *) target="$dir/$target" ;;
        esac
    done
    cd "$(dirname "$target")/.." && pwd
}

if [ -z "${TOOLKIT_HOME:-}" ]; then
    TOOLKIT_HOME="$(resolve_wt_home)"
fi
export TOOLKIT_HOME

# shellcheck source=../lib/helpers.sh
. "$TOOLKIT_HOME/lib/helpers.sh"
# shellcheck source=../lib/registry.sh
. "$TOOLKIT_HOME/lib/registry.sh"

# --- Helpers ---

# Risolve query → path assoluto del file. Exit 1 se non trovato, 3 se file mancante.
resolve_to_file() {
    local query="$1" canonical row file full
    if ! canonical="$(resolve_name "$query")"; then
        err "prompt non trovato: $query"
        return 1
    fi
    row="$(get_row "$canonical")"
    file="$(printf '%s\n' "$row" | awk -F'\t' '{print $5}')"
    full="$TOOLKIT_HOME/$file"
    if [ ! -f "$full" ]; then
        err "file referenziato in registry non esiste: $file"
        return 3
    fi
    printf '%s\n' "$full"
}

# --- Comandi ---

cmd_list() {
    local category="" tier=""
    while [ $# -gt 0 ]; do
        case "$1" in
            --category) category="${2:?categoria mancante}"; shift 2 ;;
            --category=*) category="${1#--category=}"; shift ;;
            --tier) tier="${2:?tier mancante}"; shift 2 ;;
            --tier=*) tier="${1#--tier=}"; shift ;;
            -h|--help)
                printf 'Uso: wt list [--category C] [--tier v1|v2]\n'
                return 0 ;;
            *)
                err "opzione sconosciuta: $1"
                return 2 ;;
        esac
    done

    local rows
    rows="$(filter_rows "$category" "$tier")"
    if [ -z "$rows" ]; then
        warn "nessun prompt corrisponde ai filtri"
        return 0
    fi

    {
        printf 'CANONICAL\tALIAS\tCATEGORY\tTIER\n'
        printf '%s\n' "$rows" | awk -F'\t' '{printf "%s\t%s\t%s\t%s\n", $1, $2, $3, $4}'
    } | column -t -s $'\t'
}

cmd_show() {
    local query="${1:-}"
    if [ -z "$query" ]; then
        err "uso: wt show <name|alias>"
        return 2
    fi
    local file
    file="$(resolve_to_file "$query")" || return $?
    cat "$file"
}

cmd_path() {
    local query="${1:-}"
    if [ -z "$query" ]; then
        err "uso: wt path <name|alias>"
        return 2
    fi
    resolve_to_file "$query"
}

cmd_info() {
    local query="${1:-}"
    if [ -z "$query" ]; then
        err "uso: wt info <name|alias>"
        return 2
    fi
    local canonical row file full first_line
    if ! canonical="$(resolve_name "$query")"; then
        err "prompt non trovato: $query"
        return 1
    fi
    row="$(get_row "$canonical")"
    local aliases category tier
    aliases="$(printf '%s\n' "$row" | awk -F'\t' '{print $2}')"
    category="$(printf '%s\n' "$row" | awk -F'\t' '{print $3}')"
    tier="$(printf '%s\n' "$row" | awk -F'\t' '{print $4}')"
    file="$(printf '%s\n' "$row" | awk -F'\t' '{print $5}')"
    full="$TOOLKIT_HOME/$file"
    first_line=""
    [ -f "$full" ] && first_line="$(head -n1 "$full")"

    printf '%scanonical%s   %s\n' "$C_BOLD" "$C_RESET" "$canonical"
    printf '%saliases%s     %s\n' "$C_BOLD" "$C_RESET" "${aliases:-—}"
    printf '%scategory%s    %s\n' "$C_BOLD" "$C_RESET" "$category"
    printf '%stier%s        %s\n' "$C_BOLD" "$C_RESET" "$tier"
    printf '%sfile%s        %s\n' "$C_BOLD" "$C_RESET" "$file"
    printf '%sopening%s     %s\n' "$C_BOLD" "$C_RESET" "$first_line"
}

cmd_copy() {
    local query="${1:-}"
    if [ -z "$query" ]; then
        err "uso: wt copy <name|alias>"
        return 2
    fi
    local file clip
    file="$(resolve_to_file "$query")" || return $?
    if ! clip="$(detect_clipboard)"; then
        err "nessun comando clipboard rilevato (prova \$TOOLKIT_CLIPBOARD)"
        return 2
    fi
    # shellcheck disable=SC2086
    $clip < "$file"
    printf '%scopiato%s: %s\n' "$C_GREEN" "$C_RESET" "$(basename "$file")"
}

cmd_search() {
    local kw="${1:-}"
    if [ -z "$kw" ]; then
        err "uso: wt search <keyword>"
        return 2
    fi
    local found=0
    while IFS=$'\t' read -r canonical aliases category tier file; do
        local full="$TOOLKIT_HOME/$file"
        local match_in=""
        # match nel nome canonical o negli alias
        if printf '%s' "$canonical" | grep -qiF "$kw"; then
            match_in="name"
        elif printf '%s' "$aliases" | grep -qiF "$kw"; then
            match_in="alias"
        elif [ -f "$full" ] && grep -qiF "$kw" "$full"; then
            match_in="content"
        fi
        if [ -n "$match_in" ]; then
            found=$((found+1))
            printf '%s%s%s [%s] (%s)\n' "$C_BOLD" "$canonical" "$C_RESET" "$category" "$match_in"
            if [ "$match_in" = "content" ] && [ -f "$full" ]; then
                grep -inF "$kw" "$full" | head -n2 | sed 's/^/    /'
            fi
        fi
    done < <(registry_rows)
    if [ "$found" -eq 0 ]; then
        warn "nessun match per: $kw"
        return 1
    fi
}

cmd_help() {
    local sub="${1:-}"
    case "$sub" in
        list)    printf 'Uso: wt list [--category C] [--tier v1|v2]\n' ;;
        show)    printf 'Uso: wt show <name|alias>\n  Stampa il contenuto del prompt su stdout.\n' ;;
        path)    printf 'Uso: wt path <name|alias>\n  Stampa il path assoluto del file.\n' ;;
        info)    printf 'Uso: wt info <name|alias>\n  Mostra metadata del prompt.\n' ;;
        copy)    printf 'Uso: wt copy <name|alias>\n  Copia il prompt in clipboard.\n' ;;
        search)  printf 'Uso: wt search <keyword>\n  Cerca in nomi, alias e contenuti.\n' ;;
        version) printf 'Uso: wt version\n' ;;
        ""|help)
            cat <<EOF
wt — CLI per la libreria di prompt work-toolkit (v$VERSION)

Comandi:
  list [--category C] [--tier v1|v2]   Elenca i prompt
  show <name|alias>                    Stampa il prompt su stdout
  path <name|alias>                    Stampa il path del file
  info <name|alias>                    Metadata del prompt
  copy <name|alias>                    Copia in clipboard
  search <keyword>                     Cerca in nomi, alias, contenuti
  help [command]                       Aiuto
  version                              Versione

Variabili ambiente:
  TOOLKIT_HOME           Override path repo
  TOOLKIT_CLIPBOARD      Override comando clipboard
  NO_COLOR             Disabilita ANSI

Esempi:
  wt list
  wt show debug
  wt show arch | pbcopy
  wt copy disaster-recovery
EOF
            ;;
        *)
            err "comando help sconosciuto: $sub"
            return 2 ;;
    esac
}

cmd_version() {
    printf 'wt %s\n' "$VERSION"
}

# --- Entry point ---

main() {
    if [ $# -eq 0 ]; then
        cmd_help
        return 0
    fi
    local cmd="$1"; shift
    case "$cmd" in
        list)              cmd_list "$@" ;;
        show)              cmd_show "$@" ;;
        path)              cmd_path "$@" ;;
        info)              cmd_info "$@" ;;
        copy)              cmd_copy "$@" ;;
        search)            cmd_search "$@" ;;
        help|-h|--help)    cmd_help "$@" ;;
        version|-v|--version) cmd_version ;;
        *)
            err "comando sconosciuto: $cmd"
            cmd_help >&2
            return 2 ;;
    esac
}

main "$@"
