#!/bin/bash
# cmd — natural language to shell command, powered by Apple Intelligence
# Install globally as `apfel-cmd`: see demo/README.md "Install demos globally (optional)"
#
# Usage:  cmd "find files larger than 100MB"
#         cmd -x "list all open ports"       # execute (asks confirm)
#         cmd -c "show disk usage sorted by size"   # copy to clipboard
#
# Shell function version (add to .zshrc):
#   cmd(){ local x c r a; while [[ $1 == -* ]]; do case $1 in -x)x=1;shift;; -c)c=1;shift;; *)break;; esac; done; r=$(apfel -q -s 'Output only a shell command.' "$*" | sed '/^```/d;/^#/d;s/\x1b\[[0-9;]*[a-zA-Z]//g;s/^[[:space:]]*//;/^$/d' | head -1); [[ $r ]] || { echo "no command generated"; return 1; }; printf '\e[32m$\e[0m %s\n' "$r"; [[ $c ]] && printf %s "$r" | pbcopy && echo "(copied)"; [[ $x ]] && { printf 'Run? [y/N] '; read -r a; [[ $a == y ]] && eval "$r"; }; return 0; }
#
# Examples:
#   cmd find all swift files larger than 1MB
#   cmd -c show disk usage sorted by size
#   cmd -x what process is using port 3000
#   cmd list all git branches merged into main
#
# Note: Apple's on-device model has safety guardrails that may block prompts
# containing words like "kill", "terminate", "destroy", etc. — even in
# legitimate contexts (e.g. "kill all node processes"). Rephrase to avoid:
#   BAD:  cmd "kill all node processes"
#   GOOD: cmd "stop all running node processes"
#
# Requires: apfel installed (https://github.com/Arthur-Ficial/apfel)

EXECUTE=false
COPY=false

while [[ $# -gt 0 ]]; do
    case "$1" in
        -x|--execute)  EXECUTE=true; shift ;;
        -c|--copy)     COPY=true; shift ;;
        -h|--help)
            echo "cmd — natural language to shell command"
            echo ""
            echo "Usage: cmd [OPTIONS] \"description\""
            echo ""
            echo "  -x, --execute  Run the command (asks confirmation first)"
            echo "  -c, --copy     Copy command to clipboard"
            echo "  -h, --help     Show this help"
            echo ""
            echo "Examples:"
            echo "  cmd \"find all .log files modified today\""
            echo "  cmd -x \"show disk usage sorted by size\""
            echo "  cmd -c \"awk to sum column 3 of a CSV\""
            echo ""
            echo "Requires: apfel (Apple Intelligence CLI)"
            exit 0
            ;;
        -*) echo "Unknown option: $1. Use --help."; exit 1 ;;
        *)  break ;;
    esac
done

if [[ -z "$1" ]]; then
    echo "Usage: cmd \"what you want to do\""
    echo "       cmd --help for more options"
    exit 1
fi

# Check apfel is installed
if ! command -v apfel &>/dev/null; then
    echo "Error: apfel not found. Install from https://github.com/Arthur-Ficial/apfel"
    exit 1
fi

SYSTEM="You are a shell command generator for macOS (zsh/bash). Output ONLY the command — no explanation, no markdown, no code fences, no comments. If multiple commands are needed, join them with && or |. Never output anything except the command itself."

result=$(apfel -q -s "$SYSTEM" "$1")
status=$?

if [[ $status -ne 0 ]]; then
    echo "Error: apfel failed (exit $status)" >&2
    exit $status
fi

# Strip markdown fences, ANSI escape sequences, and whitespace
result=$(echo "$result" | sed '/^```/d' | sed 's/\x1b\[[0-9;]*[a-zA-Z]//g' | sed 's/^[[:space:]]*//' | sed '/^$/d')

if $COPY; then
    echo "$result" | pbcopy
    echo -e "\033[90m(copied to clipboard)\033[0m"
fi

echo -e "\033[32m\$\033[0m $result"

if $EXECUTE; then
    echo ""
    read -r -p "Run this? [y/N] " confirm
    if [[ "$confirm" =~ ^[yY]$ ]]; then
        eval "$result"
    fi
fi
