#!/usr/bin/env bash
# tesla-check — pre-flight validation for the Tesla Claude Code plugin
# Checks if tesla-cli is installed and configured.

set -euo pipefail

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m'

errors=0

# Check tesla CLI
if command -v tesla &>/dev/null; then
    version=$(tesla --version 2>/dev/null || echo "unknown")
    echo -e "${GREEN}✓${NC} tesla-cli installed ($version)"
else
    echo -e "${RED}✗${NC} tesla-cli not found"
    echo "  Install: uv tool install tesla-cli"
    errors=$((errors + 1))
fi

# Check configuration
if [ -f "$HOME/.tesla-cli/config.toml" ]; then
    echo -e "${GREEN}✓${NC} Config file exists"
else
    echo -e "${RED}✗${NC} No config file found"
    echo "  Run: tesla setup"
    errors=$((errors + 1))
fi

# Check VIN configured
if command -v tesla &>/dev/null; then
    vin=$(tesla config show --json 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('general',{}).get('default_vin',''))" 2>/dev/null || echo "")
    if [ -n "$vin" ]; then
        echo -e "${GREEN}✓${NC} VIN configured (${vin:0:6}...)"
    else
        echo -e "${YELLOW}!${NC} No VIN configured"
        echo "  Run: tesla setup"
    fi
fi

# Check auth token
if command -v tesla &>/dev/null; then
    auth=$(tesla config show --json 2>/dev/null | python3 -c "import sys,json; d=json.load(sys.stdin); print('ok' if d.get('auth',{}).get('has_token') else '')" 2>/dev/null || echo "")
    if [ -n "$auth" ]; then
        echo -e "${GREEN}✓${NC} Authentication token present"
    else
        echo -e "${YELLOW}!${NC} No auth token"
        echo "  Run: tesla config auth order  (or tesla setup)"
    fi
fi

if [ $errors -gt 0 ]; then
    echo ""
    echo -e "${RED}$errors issue(s) found.${NC} Run 'tesla setup' to get started."
    exit 1
else
    echo ""
    echo -e "${GREEN}All checks passed.${NC} Ready to use /tesla:status"
    exit 0
fi
