#!/bin/bash
set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
CARGO_TOML="$PROJECT_ROOT/Cargo.toml"
OUTPUT="$PROJECT_ROOT/SKILL.md"
BINARY="l-tool"

RED='\033[0;31m'
GREEN='\033[0;32m'
CYAN='\033[0;36m'
NC='\033[0m'

info()    { echo -e "${CYAN}ℹ ${NC}$1"; }
success() { echo -e "${GREEN}✓ ${NC}$1"; }
error()   { echo -e "${RED}✗ ${NC}$1"; }

if [ "$1" = "--help" ] || [ "$1" = "-h" ]; then
  echo "Usage: $0 [OUTPUT_PATH]"
  echo ""
  echo "Generates SKILL.md from l-tool CLI --help output and Cargo.toml metadata."
  echo "Default output: PROJECT_ROOT/SKILL.md"
  exit 0
fi

[ -n "$1" ] && OUTPUT="$1"

info "Building project..."
cd "$PROJECT_ROOT"
cargo build --quiet 2>/dev/null
BIN="$PROJECT_ROOT/target/debug/$BINARY"

if [ ! -f "$BIN" ]; then
  error "Binary not found at $BIN"
  exit 1
fi

VERSION=$(grep '^version' "$CARGO_TOML" | head -1 | sed 's/.*"\(.*\)".*/\1/')
NAME=$(grep '^name' "$CARGO_TOML" | head -1 | sed 's/.*"\(.*\)".*/\1/')

get_help() {
  "$BIN" "$@" --help 2>/dev/null | grep -v '^warning:'
}

collect_subcommands() {
  local prefix="$1"
  shift
  local args=("$@")
  
  local help_output
  help_output=$(get_help "${args[@]}")
  
  local in_commands=false
  while IFS= read -r line; do
    if echo "$line" | grep -q '^Commands:'; then
      in_commands=true
      continue
    fi
    if echo "$line" | grep -q '^Options:'; then
      break
    fi
    if [ "$in_commands" = true ]; then
      local cmd=$(echo "$line" | awk '{print $1}' | tr -d ' ')
      if [ -n "$cmd" ] && [ "$cmd" != "help" ]; then
        echo "$prefix$cmd"
        collect_subcommands "${prefix}${cmd} " "${args[@]}" "$cmd"
      fi
    fi
  done <<< "$help_output"
}

info "Collecting CLI structure..."

TOP_COMMANDS=()
while IFS= read -r line; do
  [ -n "$line" ] && TOP_COMMANDS+=("$line")
done < <(get_help | awk '/^Commands:/{found=1;next} /^Options:/{found=0} found{print $1}' | grep -v '^$' | grep -v 'help')

{
cat << 'HEADER'
# l-tool CLI Reference

A versatile command-line tool for JavaScript project management, image processing, PDF operations, Git utilities, and FFmpeg video processing.

HEADER

echo "## Installation"
echo ""
echo '```bash'
echo "cargo install $NAME"
echo '```'
echo ""
echo "## Quick Reference"
echo ""
echo "| Module | Command | Description |"
echo "|--------|---------|-------------|"

for cmd in "${TOP_COMMANDS[@]}"; do
  SUB_HELP=$(get_help "$cmd")
  CMD_DESC=$(echo "$SUB_HELP" | head -1)
  
  SUBCMDS=()
  while IFS= read -r line; do
    [ -n "$line" ] && SUBCMDS+=("$line")
  done < <(echo "$SUB_HELP" | awk '/^Commands:/{found=1;next} /^Options:/{found=0} found{print $1}' | grep -v '^$' | grep -v 'help')
  
  if [ ${#SUBCMDS[@]} -gt 0 ]; then
    for sub in "${SUBCMDS[@]}"; do
      SUB_DESC=$(get_help "$cmd" "$sub" | head -1)
      echo "| \`$cmd\` | \`$BINARY $cmd $sub\` | $SUB_DESC |"
    done
  else
    echo "| \`$cmd\` | \`$BINARY $cmd\` | $CMD_DESC |"
  fi
done

echo ""

for cmd in "${TOP_COMMANDS[@]}"; do
  CMD_HELP=$(get_help "$cmd")
  CMD_DESC=$(echo "$CMD_HELP" | head -1)
  
  echo "## \`$cmd\` — $CMD_DESC"
  echo ""
  
  SUBCMDS=()
  while IFS= read -r line; do
    [ -n "$line" ] && SUBCMDS+=("$line")
  done < <(echo "$CMD_HELP" | awk '/^Commands:/{found=1;next} /^Options:/{found=0} found{print $1}' | grep -v '^$' | grep -v 'help')
  
  if [ ${#SUBCMDS[@]} -gt 0 ]; then
    for sub in "${SUBCMDS[@]}"; do
      SUB_FULL=$(get_help "$cmd" "$sub")
      SUB_DESC=$(echo "$SUB_FULL" | head -1)
      
      echo "### \`$cmd $sub\` — $SUB_DESC"
      echo ""
      echo '```'
      echo "$SUB_FULL"
      echo '```'
      echo ""
    done
  else
    echo '```'
    echo "$CMD_HELP"
    echo '```'
    echo ""
  fi
done

echo "---"
echo ""
echo "*Generated from \`$BINARY v$VERSION\` on $(date +%Y-%m-%d)*"

} > "$OUTPUT"

success "SKILL.md generated at: $OUTPUT"
info "Lines: $(wc -l < "$OUTPUT" | tr -d ' ')"
