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

# Read update state from runtime dir
UPDATE_STATE_FILE="${XDG_RUNTIME_DIR:-/tmp}/ai-gauge/update-state.json"
UPDATE_VERSION=""
UPDATE_INSTALLING=false
UPDATE_ERROR=""
UPDATE_CHANGELOG_URL=""

# 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"

STATE_DIR="${XDG_RUNTIME_DIR:-/tmp}/ai-gauge"
mkdir -p "$STATE_DIR"

if [[ -f "$UPDATE_STATE_FILE" ]]; then
    UPDATE_VERSION=$(jq -r '.version // empty' "$UPDATE_STATE_FILE" 2>/dev/null || true)
    UPDATE_INSTALLING=$(jq -r '.installing // false' "$UPDATE_STATE_FILE" 2>/dev/null || echo "false")
    UPDATE_ERROR=$(jq -r '.error // empty' "$UPDATE_STATE_FILE" 2>/dev/null || true)
    UPDATE_CHANGELOG_URL=$(jq -r '.changelogUrl // empty' "$UPDATE_STATE_FILE" 2>/dev/null || true)
fi

# Build usage summary for clipboard
build_summary() {
    if [[ ! -f "$STATE_DIR/usage.json" ]]; then
        echo "No usage data available"
        return
    fi
    local five_pct seven_pct
    five_pct=$(jq -r '.five_hour.utilization // "N/A"' "$STATE_DIR/usage.json" 2>/dev/null)
    seven_pct=$(jq -r '.seven_day.utilization // "N/A"' "$STATE_DIR/usage.json" 2>/dev/null)
    five_reset=$(jq -r '.five_hour.resets_at // "N/A"' "$STATE_DIR/usage.json" 2>/dev/null)
    seven_reset=$(jq -r '.seven_day.resets_at // "N/A"' "$STATE_DIR/usage.json" 2>/dev/null)
    printf '5-hour: %s%% (resets: %s)\nWeekly: %s%% (resets: %s)' \
        "${five_pct%.*}" "$five_reset" "${seven_pct%.*}" "$seven_reset"
}

# macOS: menu handled by Swift app
if is_macos && [[ "${DRY_RUN:-0}" != "1" ]]; then
    echo "Menu options available via menubar icon right-click (AI Gauge in menu bar)"
    exit 0
fi

# Menu
ITEMS=()
current_display_mode=$(read_config_field displayMode full)
current_source=$(read_config_field tokenSource claude-code)
current_plan=$(read_config_field plan unknown)
current_auto_check_updates=$(read_config_field autoCheckUpdates true)

# Update items
if [[ "$UPDATE_INSTALLING" == "true" ]]; then
    ITEMS+=("⏳ Updating...")
elif [[ -n "$UPDATE_VERSION" ]]; then
    ITEMS+=("✨ Update to v${UPDATE_VERSION}")
fi
if [[ -n "$UPDATE_ERROR" ]]; then
    ITEMS+=("⚠ Update failed: ${UPDATE_ERROR}")
fi
if [[ -n "$UPDATE_CHANGELOG_URL" ]]; then
    ITEMS+=("📄 View changelog")
fi
ITEMS+=("🔍 Check for updates")
ITEMS+=("↻  Refresh Now")
ITEMS+=("  Copy Usage")
ITEMS+=("  Raw Data")
ITEMS+=("🔑  Token source: ${current_source:-claude-code}")
ITEMS+=("📋  Plan: ${current_plan:-unknown}")
ITEMS+=("🎨  Display mode: ${current_display_mode}")
ITEMS+=("🔄  Auto-check updates: $(if [[ "${current_auto_check_updates:-true}" == "true" ]]; then echo ON; else echo OFF; fi)")

if [[ "${DRY_RUN:-0}" == "1" ]]; then
    printf '%s\n' "${ITEMS[@]}"
    SELECTED="${SELECTED_ITEM:-}"
elif [[ -n "${SELECTED_ITEM:-}" ]]; then
    SELECTED="$SELECTED_ITEM"
else
    SELECTED=$(printf '%s\n' "${ITEMS[@]}" | omarchy-launch-walker --dmenu --width 240 --minheight 1 --maxheight 300 -p "AI Gauge" 2>/dev/null) || exit 0
fi

SEND_WS="$SCRIPT_DIR/../lib/send-ws.js"

case "$SELECTED" in
    "✨ Update to v"*)
        if [[ "${DRY_RUN:-0}" == "1" ]]; then
            echo 'WOULD_SEND: {"type":"doUpdate"}'
        else
            echo '{"type":"doUpdate"}' | bun "$SEND_WS"
        fi
        ;;
    "🔍 Check for updates")
        if [[ "${DRY_RUN:-0}" == "1" ]]; then
            echo 'WOULD_SEND: {"type":"checkUpdate"}'
        else
            echo '{"type":"checkUpdate"}' | bun "$SEND_WS"
        fi
        ;;
    "📄 View changelog")
        if [[ "${DRY_RUN:-0}" == "1" ]]; then
            echo "WOULD_OPEN: $UPDATE_CHANGELOG_URL"
        else
            xdg-open "$UPDATE_CHANGELOG_URL" 2>/dev/null || true
        fi
        ;;
    "⚠ Update failed: "*)
        if [[ "${DRY_RUN:-0}" == "1" ]]; then
            echo 'WOULD_SEND: {"type":"doUpdate"}'
        else
            echo '{"type":"doUpdate"}' | bun "$SEND_WS"
            notify-send -t 2000 -a "AI Gauge" "Retrying update..." 2>/dev/null || true
        fi
        ;;
    *"Refresh"*)
        bun -e 'const ws = new WebSocket("ws://localhost:19876"); ws.onopen = () => { ws.send(JSON.stringify({command:"refresh"})); ws.close(); };'
        notify-send -t 2000 -a "AI Gauge" "Refreshing usage data..."
        ;;
    *"Copy"*)
        summary=$(build_summary)
        printf '%s' "$summary" | wl-copy 2>/dev/null
        notify-send -t 2000 -a "AI Gauge" "Copied to clipboard"
        ;;
    *"Raw"*)
        if [[ -f "$STATE_DIR/usage.json" ]]; then
            jq . "$STATE_DIR/usage.json" | wl-copy 2>/dev/null
            notify-send -t 2000 -a "AI Gauge" "Raw JSON copied to clipboard"
        else
            notify-send -t 2000 -a "AI Gauge" "No data available yet"
        fi
        ;;
    *"Token source"*)
        if [[ "${DRY_RUN:-0}" == "1" ]]; then
            echo "WOULD_OPEN: token-source-submenu"
            exit 0
        fi
        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_sources=$(mark_current "${current_source:-claude-code}" "${all_options[@]}")
        new_source=$(printf '%s\n' "$marked_sources" | 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")
        [[ -z "$new_source" ]] && exit 0
        echo "{\"type\":\"setConfig\",\"key\":\"tokenSource\",\"value\":\"$new_source\"}" | bun "$SEND_WS" 2>/dev/null \
            || "${SCRIPT_DIR}/ai-gauge-config" set tokenSource "$new_source"
        notify-send -t 2000 -a "AI Gauge" "Token source: $new_source" 2>/dev/null || true
        ;;
    *"Plan"*)
        if [[ "${DRY_RUN:-0}" == "1" ]]; then
            echo "WOULD_OPEN: plan-submenu"
            exit 0
        fi
        plan_options=("max" "pro" "team" "enterprise" "unknown" "plus" "business" "edu")
        marked_plans=$(mark_current "${current_plan:-unknown}" "${plan_options[@]}")
        new_plan=$(echo "$marked_plans" | omarchy-launch-walker --dmenu --width 200 --minheight 1 --maxheight 200 -p "Plan" 2>/dev/null) || exit 0
        new_plan=$(strip_walker_decorations "$new_plan")
        [[ -z "$new_plan" ]] && exit 0
        echo "{\"type\":\"setConfig\",\"key\":\"plan\",\"value\":\"$new_plan\"}" | bun "$SEND_WS" 2>/dev/null \
            || "${SCRIPT_DIR}/ai-gauge-config" set plan "$new_plan"
        notify-send -t 2000 -a "AI Gauge" "Plan: $new_plan" 2>/dev/null || true
        ;;
    *"Auto-check"*)
        if [[ "${current_auto_check_updates:-true}" == "true" ]]; then
            new_auto=false
        else
            new_auto=true
        fi
        if [[ "${DRY_RUN:-0}" == "1" ]]; then
            echo "WOULD_TOGGLE: autoCheckUpdates -> $new_auto"
            exit 0
        fi
        echo "{\"type\":\"setConfig\",\"key\":\"autoCheckUpdates\",\"value\":$new_auto}" | bun "$SEND_WS" 2>/dev/null \
            || "${SCRIPT_DIR}/ai-gauge-config" set autoCheckUpdates "$new_auto"
        notify-send -t 2000 -a "AI Gauge" "Auto-check updates: $new_auto" 2>/dev/null || true
        ;;
    *"Display mode"*)
        if [[ "${DRY_RUN:-0}" == "1" ]]; then
            echo "WOULD_OPEN: display-mode-submenu"
            exit 0
        fi
        display_options=("full" "percent-only" "bar-dots" "number-bar" "time-to-reset")
        marked_modes=$(mark_current "${current_display_mode:-full}" "${display_options[@]}")
        new_mode=$(printf '%s\n' "$marked_modes" | omarchy-launch-walker --dmenu --width 200 --minheight 1 --maxheight 200 -p "Display mode" 2>/dev/null) || exit 0
        new_mode=$(strip_walker_decorations "$new_mode")
        [[ -z "$new_mode" ]] && exit 0
        echo "{\"type\":\"setConfig\",\"key\":\"displayMode\",\"value\":\"$new_mode\"}" | bun "$SEND_WS" 2>/dev/null \
            || "${SCRIPT_DIR}/ai-gauge-config" set displayMode "$new_mode"
        notify-send -t 2000 -a "AI Gauge" "Display mode: $new_mode" 2>/dev/null || true
        ;;
esac
