#!/bin/bash
# Normal CLI Script - Convenient wrapper for nectar commands
#
# Configuration and State Storage:
#   $NORMAL_HOME/config    - User configuration (API URLs, model settings, etc.); default ~/.normal/config
#   $NORMAL_ROOT/etc/config - Bundled defaults, lowest priority (overridden by user config and env vars)
#   $NORMAL_HOME/logs/     - Command execution logs (override with NORMAL_LOGDIR env var)
#   ./.nproject            - Project-specific state (project ID, project name, revision ID, trusted marker)
#
set -e

# Enable job control for better signal handling
set -m

get_normal_home() {
    if [[ -n "$NORMAL_HOME" ]]; then
        echo "$NORMAL_HOME"
    else
        echo "$HOME/.normal"
    fi
}

get_config_dir() {
    echo "$(get_normal_home)"
}

get_config_file() {
    # NORMAL_CONFIG env var overrides the default location
    if [[ -n "$NORMAL_CONFIG" ]]; then
        echo "$NORMAL_CONFIG"
    else
        echo "$(get_config_dir)/config"
    fi
}

get_logs_dir() {
    echo "${NORMAL_LOGDIR:-$(get_config_dir)/logs}"
}

get_bundled_config_file() {
    if [[ -n "$NORMAL_ROOT" ]]; then
        echo "$NORMAL_ROOT/etc/config"
    else
        echo "${SCRIPT_DIR}/../etc/config"
    fi
}

# Set consistent temp directory for ZMQ IPC sockets (cross-platform)
# This ensures TUI and MCP subprocess use the same IPC path;
# Only if not set already (allows user override)
if [[ -z "$NORMAL_TMP_DIR" ]]; then
  export NORMAL_TMP_DIR="$(get_config_dir)/tmp"
fi
mkdir -p "$NORMAL_TMP_DIR"

# Get the directory where this script is located
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

# Resolve the Python interpreter that has nectar2 installed.
# Order: bundled tarball python → project venv → system python3.
if [[ -n "${NORMAL_ROOT:-}" ]] && [[ -x "$NORMAL_ROOT/python/bin/python3.14" ]]; then
    _NORMAL_PYTHON="$NORMAL_ROOT/python/bin/python3.14"
elif [[ -x "$SCRIPT_DIR/../python/bin/python3.14" ]]; then
    _NORMAL_PYTHON="$SCRIPT_DIR/../python/bin/python3.14"
elif [[ -x "$SCRIPT_DIR/../.venv/bin/python3" ]]; then
    _NORMAL_PYTHON="$SCRIPT_DIR/../.venv/bin/python3"
else
    _NORMAL_PYTHON="python3"
fi

# Fast path for --help on specific commands to avoid loading config/Python
# This is a performance optimization following CLI best practices:
# - Help output should be deterministic and not depend on config state
# - Help should work even if config is broken (fail-fast principle)
# - Industry standard: most CLIs (git, docker, kubectl) show help instantly
#
# Note: This skips config/env loading for help-only invocations, which is
# intentional and safe since help text doesn't depend on runtime configuration.
if [[ $# -eq 2 && ( "$2" == "-h" || "$2" == "--help" ) ]]; then
    case "$1" in
        login)
            # These commands have inline bash help that doesn't require Python
            # Skip expensive config loading since help text is static
            SKIP_CONFIG_LOAD=true
            ;;
    esac
fi

# Define show_help function for use throughout the script
show_help_early() {
    VERSION=$($_NORMAL_PYTHON -c "import nectar2; print(nectar2.__version__)" 2>/dev/null || echo "unknown")
    # Calculate padding for version line (box width is 61 chars including borders)
    local version_text="Version: $VERSION"
    local box_width=57  # Internal width (61 - 2 for borders)
    local text_len=${#version_text}
    local padding=$(( (box_width - text_len) / 2 ))
    local right_padding=$(( box_width - text_len - padding ))

    cat << 'EOF'
╭─────────────────────────────────────────────────────────╮
│                     🚀 Normal CLI                        │
│            Accelerate Silicon Engineering               │
EOF
        printf "│%*s%s%*s│\n" $padding "" "$version_text" $right_padding ""
        cat << 'EOF'
╰─────────────────────────────────────────────────────────╯

USAGE
  normal <command> [options]

QUICK START
  1. normal login                          # Authenticate with web app
  2. normal cli                            # Launch the interactive CLI

AVAILABLE COMMANDS
  cli                                      Launch interactive Normal CLI
  login                                    Authenticate with web app API
        [--refresh-token <token>]          Use refresh token for authentication (session lasts 180 days)
        [--cli]                            Force CLI login mode
        [--status]                         Check login status
        [--logout]                         Log out and clear credentials

CONFIGURATION
  config edit                              Open config file in editor

MCP SERVERS
  mcp edit [--scope <scope>]               Open MCP config in \$EDITOR (default scope: user)
  mcp list                                 List effective MCP servers

KEYBINDINGS
  keys edit [--preset <name>]              Open keybindings config in \$EDITOR

FEEDBACK
  feedback "<message>"                   Send feedback to the Normal team

UPDATES
  upgrade                                Check for app/config updates and choose what to upgrade

NOTE
  Project sync, listing, and verification workflows are available via the Nectar CLI directly.

COMMON OPTIONS
  -v, --verbose         Increase verbosity (-v for info, -vv for debug)

EXAMPLES
  normal login
  normal cli

For detailed documentation, visit: https://docs.normalcomputing.ai
EOF
}

# Handle help and version early (before any config/logging)
if [[ "${1:-}" == "-h" ]] || [[ "${1:-}" == "--help" ]]; then
    show_help_early
    exit 0
fi

if [[ "${1:-}" == "-V" ]] || [[ "${1:-}" == "--version" ]]; then
    VERSION=$($_NORMAL_PYTHON -c "import nectar2; print(nectar2.__version__)" 2>/dev/null || echo "unknown")
    echo "$VERSION"
    exit 0
fi

ORIGINAL_ARGS=("$@")

# Parse global flags (--verbose/-v/-vv) before command dispatch
VERBOSITY=0
args=()
for arg in "$@"; do
    case "$arg" in
        -vv)         VERBOSITY=2 ;;
        --verbose|-v) (( VERBOSITY < 1 )) && VERBOSITY=1 ;;
        *) args+=("$arg") ;;
    esac
done
set -- "${args[@]}"

# Note: Configuration will be loaded in this order (highest to lowest priority):
# 1. Environment variables (already set)
# 2. User config (NORMAL_HOME/config, default ~/.normal/config)
# 3. Bundled config (NORMAL_ROOT/etc/config)
# 4. Script defaults (set after config loading)

# Colors for output (compatible with target platform)
# Set NO_COLOR environment variable to disable colors
if [[ -n "$NO_COLOR" ]] || [[ "$TERM" == "dumb" ]] || [[ ! -t 1 ]]; then
    GREEN=''
    YELLOW=''
    RED=''
    BLUE=''
    CYAN=''
    NC=''
else
    GREEN='\033[0;32m'
    YELLOW='\033[0;33m'
    RED='\033[0;31m'
    BLUE='\033[0;34m'
    CYAN='\033[0;36m'
    NC='\033[0m' # No Color
fi

setup_logging() {
    # Use NORMAL_LOGFILE if set, otherwise generate default path
    if [[ -n "$NORMAL_LOGFILE" ]]; then
        LOG_FILE="$NORMAL_LOGFILE"
        # Ensure parent directory exists
        mkdir -p "$(dirname "$LOG_FILE")" 2>/dev/null || true
    else
        ensure_logs_dir
        local logs_dir=$(get_logs_dir)
        local today=$(date '+%Y-%m-%d')
        LOG_FILE="$logs_dir/normal_${today}.log"
    fi

    cleanup_old_logs

    # Add session header to log file
    cat >> "$LOG_FILE" << EOF

# ==========================================
# New Session: $(date)
# PID: $$
# Working Directory: $(pwd)
# Command: $0 $*
# ==========================================
EOF
}

log_to_file() {
    local level="$1"
    local message="$2"
    if [[ -n "$LOG_FILE" ]]; then
        echo "[$(date '+%Y-%m-%d %H:%M:%S')] [$level] $message" >> "$LOG_FILE"
    fi
}

log_debug() {
    local message="$1"
    if [[ "$VERBOSITY" -ge 2 ]]; then
        echo -e "${CYAN}[normal]${NC} $message"
    fi
    log_to_file "DEBUG" "$message"
}

log_info() {
    local message="$1"
    if [[ "$VERBOSITY" -ge 1 ]]; then
        echo -e "${GREEN}[normal]${NC} $message"
    fi
    log_to_file "INFO" "$message"
}

log_warn() {
    local message="$1"
    echo -e "${YELLOW}[normal]${NC} $message"
    log_to_file "WARN" "$message"
}

log_error() {
    local message="$1"
    echo -e "${RED}[normal]${NC} $message"
    log_to_file "ERROR" "$message"
}

log_command() {
    local cmd_description="$1"
    shift
    local cmd=("$@")
    log_info "$cmd_description"
    log_to_file "CMD" "Executing: ${cmd[*]}"
}

cleanup_old_logs() {
    local logs_dir
    logs_dir=$(get_logs_dir)

    if [[ -d "$logs_dir" ]]; then
        find "$logs_dir" -name "normal_*.log" -mtime +30 -delete 2>/dev/null || true
        find "$logs_dir" -name "nectar_*.log" -mtime +30 -delete 2>/dev/null || true
    fi
}

ensure_logs_dir() {
    local logs_dir=$(get_logs_dir)
    if [[ ! -d "$logs_dir" ]]; then
        mkdir -p "$logs_dir"
    fi
}

load_config_file() {
    # Helper function to load a single config file
    # Within a file: last definition wins (standard behavior)
    # Across sources: ENV > user config (NORMAL_HOME/config) > bundled config (NORMAL_ROOT/etc/config)
    load_single_config() {
        local config_file="$1"
        local config_type="$2"  # e.g. "user"

        if [[ ! -f "$config_file" ]]; then
            return
        fi

        log_debug "Loading $config_type configuration from $config_file"

        # Track keys set from THIS file (allows last-wins within file)
        local set_from_this_file=" "

        while IFS= read -r line || [[ -n "$line" ]]; do
            # Skip empty lines and comments
            [[ -z "$line" || "$line" =~ ^[[:space:]]*# ]] && continue

            # Skip lines that don't contain '='
            [[ "$line" =~ = ]] || continue

            # Extract key and value
            local key="${line%%=*}"
            local value="${line#*=}"

            # Remove leading/trailing whitespace from key
            key=$(echo "$key" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')

            # Remove quotes from value if present
            value=$(echo "$value" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//' | sed 's/^["'\'']\(.*\)["'\'']$/\1/')

            # Export if: not already set OR was set from this same file (last-wins within file)
            if [[ -z "${!key}" ]] || [[ "$set_from_this_file" == *" $key "* ]]; then
                export "$key=$value"
                # Mark as set from this file (only add once)
                [[ "$set_from_this_file" != *" $key "* ]] && set_from_this_file+="$key "
            fi
        done < "$config_file" || true
    }

    # Load user config first so it takes precedence over bundled defaults.
    # load_single_config only exports keys that aren't already set, so the
    # order here encodes priority: ENV (pre-set) > user > bundled.
    local user_config=$(get_config_file)
    load_single_config "$user_config" "user"

    local bundled_config
    bundled_config=$(get_bundled_config_file)
    load_single_config "$bundled_config" "bundled"
}

# Load configuration.
# Priority: Environment variables > User config (NORMAL_HOME/config) > Bundled config (NORMAL_ROOT/etc/config)
# Skip config loading if we're just showing help
if [[ "${SKIP_CONFIG_LOAD:-false}" != "true" ]]; then
    load_config_file

    # Export REQUESTS_CA_BUNDLE if set (for SSL/TLS verification)
    [[ -n "${REQUESTS_CA_BUNDLE:-}" ]] && export REQUESTS_CA_BUNDLE || true

    # Set fallback defaults for script variables (only if not set by config)
    DEFAULT_MAX_TURNS="${DEFAULT_MAX_TURNS:-200}"

    # Setup logging (after config is loaded)
    setup_logging

    # Configure Python logging to use the same log file
    export NORMAL_LOGFILE="${NORMAL_LOGFILE:-$LOG_FILE}"
    if [[ "$VERBOSITY" -ge 2 ]]; then
        export LOGLEVEL="${LOGLEVEL:-DEBUG}"
    elif [[ "$VERBOSITY" -ge 1 ]]; then
        export LOGLEVEL="${LOGLEVEL:-INFO}"
    else
        export LOGLEVEL="${LOGLEVEL:-WARN}"
    fi
fi

# Default TUI frame rate unless explicitly overridden by env or config
export TEXTUAL_FPS="${TEXTUAL_FPS:-30}"

# Global variables to track processes
CHILD_PIDS=()
INTERRUPT_RECEIVED=false

# Function to handle interrupts
interrupt_handler() {
    INTERRUPT_RECEIVED=true
    log_warn "Interrupt received, stopping iterations and cleaning up..."
    cleanup_all
    # Exit with interrupt code
    exit 130
}

# Trap to cleanup on exit
cleanup_on_exit() {
    local exit_code=$?
    # Only cleanup if not already handled by interrupt
    if [[ $exit_code -ne 130 ]]; then
        cleanup_all
    fi
}

# Add comprehensive cleanup for all exit scenarios
cleanup_all() {
    # Kill all child processes
    for pid in "${CHILD_PIDS[@]}"; do
        if kill -0 "$pid" 2>/dev/null; then
            log_info "Cleaning up process $pid"
            kill -TERM "$pid" 2>/dev/null || true
        fi
    done

    # Give processes time to clean up
    sleep 1

    # Force kill any remaining processes
    for pid in "${CHILD_PIDS[@]}"; do
        if kill -0 "$pid" 2>/dev/null; then
            log_warn "Force killing process $pid"
            kill -KILL "$pid" 2>/dev/null || true
        fi
    done
}

trap interrupt_handler INT TERM HUP
trap cleanup_on_exit EXIT

# Help function (calls early version defined at top of script)
show_help() {
    show_help_early
}

# Find nectar executable
find_nectar() {
    if command -v nectar >/dev/null 2>&1; then
        echo "nectar"
    else
        log_error "nectar command not found in PATH!"
        log_error "Please ensure Normal CLI is installed"
        exit 1
    fi
}

# Parse first argument as command
COMMAND=""
if [[ $# -gt 0 ]]; then
    case $1 in
        config|login|cli|feedback|upgrade|daemon|mcp|keys|-h|--help|-V|--version)
            COMMAND="$1"
            shift
            ;;
        *)
            COMMAND="passthrough"
            ;;
    esac
else
    COMMAND="cli"
fi

# Handle help and version (fallback when combined with other global flags)
if [[ "$COMMAND" == "help" || "$COMMAND" == "-h" || "$COMMAND" == "--help" ]]; then
    show_help
    exit 0
fi
if [[ "$COMMAND" == "-V" || "$COMMAND" == "--version" ]]; then
    VERSION=$($_NORMAL_PYTHON -c "import nectar2; print(nectar2.__version__)" 2>/dev/null || echo "unknown")
    echo "$VERSION"
    exit 0
fi

# Find nectar command
NECTAR_CMD=$(find_nectar)

# Handle different commands
case "$COMMAND" in
    login)
        # Check for help flag first
        if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
            echo ""
            log_info "USAGE"
            log_info "  normal login [options]"
            echo ""
            log_info "DESCRIPTION"
            log_info "  Authenticate with Normal web app API"
            log_info "  Opens browser for authentication or uses refresh token"
            echo ""
            log_info "OPTIONS"
            log_info "  --refresh-token <token>    Use existing refresh token instead of browser login"
            log_info "  --cli                      Force CLI login mode"
            log_info "  --status                   Check login status"
            log_info "  --logout                   Log out and clear stored credentials"
            echo ""
            log_info "EXAMPLES"
            log_info "  normal login                              # Interactive browser login"
            log_info "  normal login --refresh-token <token>      # Login with refresh token"
            echo ""
            exit 0
        fi

        # Validate arguments before passing to nectar to maintain normal branding
        is_refresh_token_next=false
        token_value=""
        has_refresh_token=false
        
        for arg in "$@"; do
            # Skip token value if we're expecting it
            if [[ "$is_refresh_token_next" == true ]]; then
                token_value="$arg"
                is_refresh_token_next=false
                continue
            fi
            
            # Check for valid options
            if [[ "$arg" == --* ]]; then
                case "$arg" in
                    --refresh-token)
                        has_refresh_token=true
                        is_refresh_token_next=true
                        ;;
                    --cli|--status|--logout)
                        ;;
                    *)
                        log_error "Unrecognized option: $arg"
                        echo ""
                        log_info "USAGE"
                        log_info "  normal login [--refresh-token <token>] [--cli] [--status] [--logout]"
                        echo ""
                        log_info "For more information: normal login --help"
                        exit 1
                        ;;
                esac
            else
                # Positional arguments are not allowed for login command
                log_error "Unrecognized argument: $arg"
                echo ""
                log_info "USAGE"
                log_info "  normal login [--refresh-token <token>] [--cli] [--status] [--logout]"
                echo ""
                log_info "For more information: normal login --help"
                exit 1
            fi
        done

        # Validate refresh token if provided
        if [[ "$has_refresh_token" == true ]]; then
            # Validate token value: must exist, not be empty, and not be another flag
            if [[ -z "$token_value" ]]; then
                # --refresh-token was provided but no value followed
                log_error "The --refresh-token option requires a token value"
                log_error "Usage: normal login --refresh-token <token>"
                exit 1
            elif [[ "$token_value" == --* ]]; then
                # Token value is another flag
                log_error "The --refresh-token option requires a token value"
                log_error "Usage: normal login --refresh-token <token>"
                exit 1
            fi
        fi

        # Execute login directly (interactive command)
        log_command "Running login command" "$NECTAR_CMD" "login" "$@"
        exec "$NECTAR_CMD" "login" "$@"
        ;;
    config)
        if [[ $# -eq 0 ]]; then
            exec "$NECTAR_CMD" "config" "show"
        else
            exec "$NECTAR_CMD" "config" "$@"
        fi
        ;;

    feedback)
        exec "$NECTAR_CMD" "feedback" "$@"
        ;;

    upgrade)
        exec "$NECTAR_CMD" "upgrade" "$@"
        ;;

    cli)
        # Interactive CLI mode - launch nectar with no parameters
        # Cross-platform CLI environment variables for better terminal compatibility
        export TERM="${TERM:-xterm-256color}"
        export LANG="${LANG:-en_US.UTF-8}"
        export LC_ALL="${LC_ALL:-en_US.UTF-8}"

        log_debug "Running Normal CLI"
        log_to_file "CMD" "Executing: $NECTAR_CMD cli $*"
        exec "$NECTAR_CMD" "cli" "$@"
        ;;
    passthrough)
        # Pass through to nectar. If it exits with code 2 (argparse error for
        # unrecognized commands), show the normal help screen instead.
        # Capture stderr so we can suppress the argparse error on code 2
        # but still show it for legitimate errors.
        log_command "Passing through command" "$NECTAR_CMD" "${ORIGINAL_ARGS[@]}"
        stderr_file=$(mktemp)
        "$NECTAR_CMD" "${ORIGINAL_ARGS[@]}" 2>"$stderr_file" || exit_code=$?
        exit_code=${exit_code:-0}
        if [[ $exit_code -eq 2 ]]; then
            rm -f "$stderr_file"
            log_error "Unknown command: ${ORIGINAL_ARGS[0]}"
            show_help
            exit 1
        fi
        cat "$stderr_file" >&2
        rm -f "$stderr_file"
        exit $exit_code
        ;;

    daemon)
        if [[ $# -eq 0 ]]; then
            log_error "Daemon command requires a subcommand (start, stop, status)"
            echo ""
            log_info "USAGE"
            log_info "  normal daemon start [--foreground]   Start the Conductor provider daemon"
            log_info "  normal daemon stop                   Stop the daemon"
            log_info "  normal daemon status                 Show daemon status"
            exit 1
        fi
        exec "$NECTAR_CMD" "daemon" "$@"
        ;;

    mcp)
        exec "$NECTAR_CMD" "mcp" "$@"
        ;;

    keys)
        NORMAL_DIR="$(get_normal_home)"
        KB_FILE="$NORMAL_DIR/keybindings.yaml"

        if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
            echo ""
            echo "USAGE"
            echo "  normal keys edit [--preset <name>]   Open keybindings file in \$EDITOR"
            echo ""
            echo "OPTIONS"
            echo "  --preset <name>    Reset keybindings to a preset (default, emacs)"
            echo ""
            exit 0
        fi

        if [[ "${1:-}" != "edit" ]]; then
            log_error "Unknown keys subcommand: ${1:-}"
            echo ""
            echo "USAGE"
            echo "  normal keys edit [--preset <name>]   Open keybindings file in \$EDITOR"
            exit 1
        fi
        shift  # consume "edit"

        # Parse --preset flag
        PRESET_NAME=""
        while [[ $# -gt 0 ]]; do
            case "$1" in
                --preset)
                    if [[ -z "${2:-}" ]]; then
                        log_error "The --preset option requires a preset name (default, emacs)"
                        exit 1
                    fi
                    PRESET_NAME="$2"
                    shift 2
                    ;;
                *)
                    log_error "Unknown option: $1"
                    echo ""
                    echo "USAGE"
                    echo "  normal keys edit [--preset <name>]   Open keybindings file in \$EDITOR"
                    exit 1
                    ;;
            esac
        done

        if [[ -n "$PRESET_NAME" ]]; then
            # Write the requested preset to the keybindings file
            PRESET_KB=$($_NORMAL_PYTHON -c "from nectar2.cli.ui.keybindings import get_default_keybindings_yaml; print(get_default_keybindings_yaml('$PRESET_NAME'), end='')" 2>/dev/null)
            if [[ -z "$PRESET_KB" ]]; then
                log_error "Unknown preset: $PRESET_NAME (available: default, emacs)"
                exit 1
            fi
            if [[ -f "$KB_FILE" ]]; then
                printf "Overwrite %s with %s preset? [y/N] " "$KB_FILE" "$PRESET_NAME"
                read -r CONFIRM
                if [[ "$CONFIRM" != "y" && "$CONFIRM" != "Y" ]]; then
                    echo "Aborted."
                    exit 0
                fi
            fi
            mkdir -p "$NORMAL_DIR"
            printf '%s\n' "$PRESET_KB" > "$KB_FILE"
            log_info "Wrote $PRESET_NAME preset to $KB_FILE"
        elif [[ ! -f "$KB_FILE" ]]; then
            # No --preset and no existing file: create default
            mkdir -p "$NORMAL_DIR"
            DEFAULT_KB=$($_NORMAL_PYTHON -c "from nectar2.cli.ui.keybindings import get_default_keybindings_yaml; print(get_default_keybindings_yaml(), end='')" 2>/dev/null)
            if [[ -n "$DEFAULT_KB" ]]; then
                printf '%s\n' "$DEFAULT_KB" > "$KB_FILE"
                log_info "Created default keybindings at $KB_FILE"
            else
                log_error "Could not load default keybindings template"
                exit 1
            fi
        fi

        # Open in editor
        EDITOR_CMD="${EDITOR:-}"
        if [[ -z "$EDITOR_CMD" ]] || ! command -v "$EDITOR_CMD" >/dev/null 2>&1; then
            for fallback in vim nano vi; do
                if command -v "$fallback" >/dev/null 2>&1; then
                    EDITOR_CMD="$fallback"
                    break
                fi
            done
        fi
        if [[ -z "$EDITOR_CMD" ]]; then
            log_error "No suitable editor found. Install vim/nano or set EDITOR."
            exit 1
        fi

        log_info "Opening keybindings file with $EDITOR_CMD..."
        exec "$EDITOR_CMD" "$KB_FILE"
        ;;

    *)
        log_error "Unknown command: $COMMAND"
        show_help
        exit 1
        ;;
esac
