#!/usr/bin/env bash
set -euo pipefail

# Resolve package directory (follows symlinks from global bin).
if readlink -f "${BASH_SOURCE[0]}" >/dev/null 2>&1; then
    SELF="$(readlink -f "${BASH_SOURCE[0]}")"
else
    SELF="$(python3 -c 'import os,sys; print(os.path.realpath(sys.argv[1]))' "${BASH_SOURCE[0]}")"
fi
SCRIPT_DIR="$(dirname "$SELF")"
source "$SCRIPT_DIR/../lib/bash-helpers.sh"

CONFIG_DIR="$HOME/.config/ai-gauge"
CONFIG_FILE="$CONFIG_DIR/config.json"

mkdir -p "$CONFIG_DIR"

read_config() {
    if [[ -f "$CONFIG_FILE" ]]; then
        cat "$CONFIG_FILE"
    else
        echo '{"tokenSource":"claude-code","plan":"unknown"}'
    fi
}

get_field() {
    read_config | jq -r ".$1 // empty"
}

send_ws() {
    if [[ "${DRY_RUN:-0}" == "1" ]]; then
        echo "WOULD_SEND: $1"
        return 0
    fi
    echo "$1" | bun "$SCRIPT_DIR/../lib/send-ws.js" 2>/dev/null
}

# Encode value as JSON: numbers/booleans bare, strings quoted.
# Usage: json_encode_value <key> <value>
json_encode_value() {
    local key="$1" value="$2"
    case "$key" in
        autoCheckUpdates) printf '%s' "$value" ;;
        *) printf '"%s"' "$value" ;;
    esac
}

write_config_direct() {
    local key="$1"
    local value="$2"
    local json_value
    json_value=$(json_encode_value "$key" "$value")
    local current
    current=$(read_config)
    echo "$current" | jq ".${key} = ${json_value}" > "$CONFIG_FILE.tmp" && mv "$CONFIG_FILE.tmp" "$CONFIG_FILE"
}

try_reload_server() {
    if command -v systemctl >/dev/null 2>&1; then
        systemctl --user restart ai-gauge-server 2>/dev/null || true
    elif is_macos; then
        launchctl kickstart -k "gui/$UID/com.ai-gauge.server" 2>/dev/null || true
    fi
}

apply_config() {
    local key="$1"
    local value="$2"
    local msg="$3"
    local json_value
    json_value=$(json_encode_value "$key" "$value")

    if [[ "${DRY_RUN:-0}" == "1" ]]; then
        echo "WOULD_SEND: {\"type\":\"setConfig\",\"key\":\"$key\",\"value\":${json_value}}"
        return 0
    fi

    if echo "{\"type\":\"setConfig\",\"key\":\"$key\",\"value\":${json_value}}" | bun "$SCRIPT_DIR/../lib/send-ws.js" 2>/dev/null; then
        [[ -n "$msg" ]] && notify-send -t 2000 -a "AI Gauge" "$msg" 2>/dev/null || true
        return 0
    fi

    echo "ai-gauge-server not reachable; writing config file directly" >&2
    write_config_direct "$key" "$value"
    try_reload_server
    [[ -n "$msg" ]] && notify-send -t 2000 -a "AI Gauge" "$msg" 2>/dev/null || true
    return 0
}

# CLI mode
if [[ "${1:-}" == "get" ]]; then
    if [[ -n "${2:-}" ]]; then
        get_field "$2"
    else
        read_config | jq .
    fi
    exit 0
fi

if [[ "${1:-}" == "set" ]]; then
    if [[ -z "${2:-}" || -z "${3:-}" ]]; then
        echo "Usage: ai-gauge-config set <key> <value>" >&2
        exit 1
    fi

    key="$2"
    value="$3"

    case "$key" in
        autoCheckUpdates)
            if [[ "$value" != "true" && "$value" != "false" ]]; then
                echo "Error: autoCheckUpdates must be true or false" >&2
                exit 1
            fi
            ;;
        plan)
            case "$value" in
                max|pro|team|enterprise|unknown|plus|business|edu) ;;
                *)
                    echo "Error: plan must be one of: max, pro, team, enterprise, unknown, plus, business, edu" >&2
                    exit 1
                    ;;
            esac
            ;;
        tokenSource)
            if [[ "$value" =~ ^(claude-code|opencode|codex|github|pi|ollama-cloud|claude-settings:[a-zA-Z0-9_][a-zA-Z0-9_.-]*)$ ]]; then
                :
            else
                echo "Error: tokenSource must match pattern ^(claude-code|opencode|codex|github|pi|ollama-cloud|claude-settings:[a-zA-Z0-9_][a-zA-Z0-9_.-]*)$" >&2
                exit 1
            fi
            ;;
        displayMode)
            case "$value" in
                full|percent-only|bar-dots|number-bar|time-to-reset) ;;
                *)
                    echo "Error: displayMode must be one of: full, percent-only, bar-dots, number-bar, time-to-reset" >&2
                    exit 1
                    ;;
            esac
            ;;
        *)
            echo "Error: unknown key '$key' (valid: plan, tokenSource, autoCheckUpdates, displayMode)" >&2
            exit 1
            ;;
    esac

    apply_config "$key" "$value" ""
    echo "Set $key = $value"
    exit 0
fi

# Interactive mode (walker UI)
# Skip walker UI on macOS
if is_macos && [[ "${DRY_RUN:-0}" != "1" && -z "${SELECTED_ITEM:-}" ]]; then
    echo "Config UI available via menubar right-click submenu."
    echo "For CLI use: ai-gauge-config set <key> <value>"
    echo "  Keys: plan (max|pro|team|enterprise|unknown|plus|business|edu), tokenSource (claude-code|opencode|codex|github|claude-settings:<name>), autoCheckUpdates (true|false), displayMode (full|percent-only|bar-dots|number-bar|time-to-reset)"
    exit 0
fi

current_source=$(get_field tokenSource)
current_plan=$(get_field plan)
current_auto_check_updates=$(get_field autoCheckUpdates)
current_display_mode=$(read_config_field displayMode full "$CONFIG_FILE")

items=(
    "🔑  Token Source: ${current_source:-claude-code}"
    "📋  Plan: ${current_plan:-unknown}"
    "🔄  Auto-check updates: $(if [[ "${current_auto_check_updates:-true}" == "true" ]]; then echo ON; else echo OFF; fi)"
    "🎨  Display mode: ${current_display_mode}"
)

if [[ "${DRY_RUN:-0}" == "1" ]]; then
    printf '%s\n' "${items[@]}"
    choice="${SELECTED_ITEM:-}"
elif [[ -n "${SELECTED_ITEM:-}" ]]; then
    choice="$SELECTED_ITEM"
else
    choice=$(printf '%s\n' "${items[@]}" | omarchy-launch-walker --dmenu --width 260 --minheight 1 --maxheight 200 -p "Settings" 2>/dev/null) || exit 0
fi

case "$choice" in
    *"Token Source"*)
        # Build list: fixed OAuth sources + discovered claude-settings:* files (with provider suffix).
        settings_list=""
        if [[ -f "$SCRIPT_DIR/../lib/cli-list-settings.js" ]]; then
            settings_list=$(bun "$SCRIPT_DIR/../lib/cli-list-settings.js" --format=walker 2>/dev/null)
        fi
         all_options=("claude-code" "opencode" "codex" "github" "pi" "ollama-cloud")
        if [[ -n "$settings_list" ]]; then
            while IFS= read -r line; do
                [[ -z "$line" ]] && continue
                all_options+=("$line")
            done <<< "$settings_list"
        fi
        marked_text=$(mark_current "${current_source:-claude-code}" "${all_options[@]}")

        if [[ "${DRY_RUN:-0}" == "1" ]]; then
            if [[ "${SUBMENU_DRY_RUN:-0}" == "1" ]]; then
                printf '%s\n' "$marked_text"
                exit 0
            fi
            echo "WOULD_SET: tokenSource"
            exit 0
        fi

        new_source=$(printf '%s\n' "$marked_text" \
            | omarchy-launch-walker --dmenu --width 240 --minheight 1 --maxheight 250 -p "Token Source" 2>/dev/null
        ) || exit 0
        new_source=$(strip_walker_decorations "$new_source")
        apply_config tokenSource "$new_source" "Token source: $new_source"
        ;;
    *"Plan"*)
        plan_options=("max" "pro" "team" "enterprise" "unknown" "plus" "business" "edu")
        marked_text=$(mark_current "${current_plan:-unknown}" "${plan_options[@]}")

        if [[ "${DRY_RUN:-0}" == "1" ]]; then
            if [[ "${SUBMENU_DRY_RUN:-0}" == "1" ]]; then
                printf '%s\n' "$marked_text"
                exit 0
            fi
            echo "WOULD_SET: plan"
            exit 0
        fi

        new_plan=$(printf '%s\n' "$marked_text" \
            | omarchy-launch-walker --dmenu --width 200 --minheight 1 --maxheight 200 -p "Plan" 2>/dev/null
        ) || exit 0
        new_plan=$(strip_walker_decorations "$new_plan")
        apply_config plan "$new_plan" "Plan: $new_plan"
        ;;
    *"Auto-check updates"*)
        if [[ "${current_auto_check_updates:-true}" == "true" ]]; then
            new_auto_check_updates=false
        else
            new_auto_check_updates=true
        fi
        apply_config autoCheckUpdates "$new_auto_check_updates" ""
        echo "Set autoCheckUpdates = $new_auto_check_updates"
        ;;
    *"Display mode"*)
        display_options=("full" "percent-only" "bar-dots" "number-bar" "time-to-reset")
        marked_text=$(mark_current "${current_display_mode:-full}" "${display_options[@]}")

        if [[ "${DRY_RUN:-0}" == "1" ]]; then
            if [[ "${SUBMENU_DRY_RUN:-0}" == "1" ]]; then
                printf '%s\n' "$marked_text"
                exit 0
            fi
            echo "WOULD_SET: displayMode"
            exit 0
        fi

        new_display_mode=$(printf '%s\n' "$marked_text" \
            | omarchy-launch-walker --dmenu --width 200 --minheight 1 --maxheight 200 -p "Display mode" 2>/dev/null
        ) || exit 0
        new_display_mode=$(strip_walker_decorations "$new_display_mode")
        apply_config displayMode "$new_display_mode" "Display mode: $new_display_mode"
        ;;
esac
