#!/usr/bin/env bash
# ClaudeUsageStatusLine installer for Linux/macOS
# Usage: bash install.sh [--silent] [--uninstall]

set -euo pipefail

INSTALL_DIR="$HOME/.local/bin"
CLAUDE_DIR="$HOME/.claude"
SETTINGS_PATH="$CLAUDE_DIR/settings.json"
EXE_NAME="ClaudeUsageStatusline"
ZAI_REFRESH_NAME="ClaudeUsageStatusline.ZaiRefresh"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

SILENT=false
UNINSTALL=false

for arg in "$@"; do
    case "$arg" in
        --silent)  SILENT=true ;;
        --uninstall) UNINSTALL=true ;;
    esac
done

log() { $SILENT || echo "$1"; }

# JSON merge/remove via python3 (available on all macOS/Linux)
merge_status_line() {
    local settings_file="$1"
    local exe_path="$2"
    python3 -c "
import json, sys, os

settings_file = sys.argv[1]
exe_path = sys.argv[2]

if os.path.exists(settings_file):
    with open(settings_file, 'r') as f:
        data = json.load(f)
else:
    data = {}

data['statusLine'] = {
    'type': 'command',
    'command': exe_path,
    'padding': 0
}

tmp = settings_file + '.tmp'
with open(tmp, 'w') as f:
    json.dump(data, f, indent=2)
os.replace(tmp, settings_file)
" "$settings_file" "$exe_path"
}

remove_status_line() {
    local settings_file="$1"
    python3 -c "
import json, sys, os

settings_file = sys.argv[1]
if not os.path.exists(settings_file):
    sys.exit(0)

with open(settings_file, 'r') as f:
    data = json.load(f)

data.pop('statusLine', None)

tmp = settings_file + '.tmp'
with open(tmp, 'w') as f:
    json.dump(data, f, indent=2)
os.replace(tmp, settings_file)
" "$settings_file"
}

backup_settings() {
    if [ -f "$SETTINGS_PATH" ]; then
        local timestamp
        timestamp=$(date -u +"%Y-%m-%d_%H-%M-%S")
        local backup="$CLAUDE_DIR/settings.backup.${timestamp}.json"
        cp "$SETTINGS_PATH" "$backup"
        log "Backed up settings to: $backup"
    fi
}

ensure_credentials() {
    local cred_path="$CLAUDE_DIR/.credentials.json"

    # Already exists — skip
    if [ -f "$cred_path" ]; then
        log "Credentials file already exists: $cred_path"
        return 0
    fi

    # Only attempt Keychain extraction on macOS
    if [ "$(uname -s)" != "Darwin" ]; then
        return 0
    fi

    # Try to extract from Keychain
    local keychain_data
    keychain_data=$(security find-generic-password -s "Claude Code-credentials" -w 2>/dev/null) || true

    if [ -z "$keychain_data" ]; then
        log "Warning: No credentials found in Keychain. Run 'claude auth login' first."
        return 0
    fi

    # Validate JSON
    if ! echo "$keychain_data" | python3 -c "import sys,json; json.load(sys.stdin)" 2>/dev/null; then
        log "Warning: Keychain data is not valid JSON. Skipping credentials extraction."
        return 0
    fi

    # Write with restricted permissions
    printf '%s' "$keychain_data" > "$cred_path"
    chmod 600 "$cred_path"
    log "Extracted credentials from Keychain to: $cred_path"
}

# --- Uninstall ---
if $UNINSTALL; then
    log "=== ClaudeUsageStatusLine Uninstaller ==="
    log ""
    if [ -f "$SETTINGS_PATH" ]; then
        remove_status_line "$SETTINGS_PATH"
        log "Removed statusLine configuration from: $SETTINGS_PATH"
    fi
    log ""
    log "=== Uninstall Complete ==="
    log ""
    log "Note: The executable and configuration files were not deleted."
    log "To completely remove: rm $INSTALL_DIR/$EXE_NAME $INSTALL_DIR/appsettings.json"
    exit 0
fi

# --- Install ---
log "=== ClaudeUsageStatusLine Installer ==="
log ""

# Check source executable exists
if [ ! -f "$SCRIPT_DIR/$EXE_NAME" ]; then
    echo "Error: $EXE_NAME not found in $SCRIPT_DIR" >&2
    exit 1
fi

# Create install directory
mkdir -p "$INSTALL_DIR"

# Copy executable
cp "$SCRIPT_DIR/$EXE_NAME" "$INSTALL_DIR/$EXE_NAME"
chmod +x "$INSTALL_DIR/$EXE_NAME"

# Remove macOS quarantine attribute if present (no-op on Linux)
if command -v xattr >/dev/null 2>&1; then
    xattr -d com.apple.quarantine "$INSTALL_DIR/$EXE_NAME" 2>/dev/null || true
fi

log "Installed executable to: $INSTALL_DIR/$EXE_NAME"

# Copy appsettings.json
if [ -f "$SCRIPT_DIR/appsettings.json" ]; then
    cp "$SCRIPT_DIR/appsettings.json" "$INSTALL_DIR/appsettings.json"
    log "Copied configuration to: $INSTALL_DIR/appsettings.json"
fi

# Copy ZaiRefresh companion binary if present (only needed for z.ai users)
if [ -f "$SCRIPT_DIR/$ZAI_REFRESH_NAME" ]; then
    cp "$SCRIPT_DIR/$ZAI_REFRESH_NAME" "$INSTALL_DIR/$ZAI_REFRESH_NAME"
    chmod +x "$INSTALL_DIR/$ZAI_REFRESH_NAME"
    if command -v xattr >/dev/null 2>&1; then
        xattr -d com.apple.quarantine "$INSTALL_DIR/$ZAI_REFRESH_NAME" 2>/dev/null || true
    fi
    log "Installed ZaiRefresh tool to: $INSTALL_DIR/$ZAI_REFRESH_NAME"
fi

# Configure Claude settings.json
mkdir -p "$CLAUDE_DIR"
backup_settings
merge_status_line "$SETTINGS_PATH" "$INSTALL_DIR/$EXE_NAME"
log "Updated Claude settings: $SETTINGS_PATH"

# Ensure credentials file exists (extract from macOS Keychain if needed)
ensure_credentials

log ""
log "=== Installation Complete ==="
log ""
log "Next steps:"
log "1. Restart Claude Code or Claude Desktop"
log "2. The status line should appear automatically"
log ""
log "IMPORTANT: Run 'claude auth login' if not already done."
log "  The status line requires ~/.claude/.credentials.json"
log ""
