#!/bin/bash
# Kimi Workspace Bootstrap Script
# Run this once to set up the Kimi agent workspace

set -e

echo "==============================================="
echo "  Kimi Agent Workspace Bootstrap"
echo "==============================================="
echo ""

# Navigate to project root
cd "$(dirname "$0")/../.."
PROJECT_ROOT=$(pwd)

echo "📁 Project Root: $PROJECT_ROOT"
echo ""

# Check Python version
echo "🔍 Checking Python version..."
python3 -c "import sys; exit(0 if sys.version_info >= (3,11) else 1)" || {
    echo "❌ ERROR: Python 3.11+ required (found $(python3 --version))"
    exit 1
}
echo "✅ Python $(python3 --version)"
echo ""

# Check if virtual environment exists
echo "🔍 Checking virtual environment..."
if [ -d ".venv" ]; then
    echo "✅ Virtual environment exists"
else
    echo "⚠️  Virtual environment not found. Creating..."
    python3 -m venv .venv
    echo "✅ Virtual environment created"
fi
echo ""

# Check dependencies
echo "🔍 Checking dependencies..."
if [ -f ".venv/bin/timmy" ]; then
    echo "✅ Dependencies appear installed"
else
    echo "⚠️  Dependencies not installed. Running make install..."
    make install || {
        echo "❌ Failed to install dependencies"
        echo "   Try: poetry install --with dev"
        exit 1
    }
    echo "✅ Dependencies installed"
fi
echo ""

# Check .env file
echo "🔍 Checking environment configuration..."
if [ -f ".env" ]; then
    echo "✅ .env file exists"
else
    echo "⚠️  .env file not found. Creating from template..."
    cp .env.example .env
    echo "✅ Created .env from template (edit as needed)"
fi
echo ""

# Check Git configuration
echo "🔍 Checking Git configuration..."
git config --local user.name &>/dev/null || {
    echo "⚠️  Git user.name not set. Setting..."
    git config --local user.name "Kimi Agent"
}
git config --local user.email &>/dev/null || {
    echo "⚠️  Git user.email not set. Setting..."
    git config --local user.email "kimi@timmy.local"
}
echo "✅ Git config: $(git config --local user.name) <$(git config --local user.email)>"
echo ""

# Run tests to verify setup
echo "🧪 Running quick test verification..."
if tox -e unit -- -q 2>/dev/null | grep -q "passed"; then
    echo "✅ Tests passing"
else
    echo "⚠️  Test status unclear - run 'make test' manually"
fi
echo ""

# Show current branch
echo "🌿 Current Branch: $(git branch --show-current)"
echo ""

# Display summary
echo "==============================================="
echo "  ✅ Bootstrap Complete!"
echo "==============================================="
echo ""
echo "Quick Start:"
echo "  make dev              # Start dashboard"
echo "  make test             # Run all tests"
echo "  tox -e unit           # Fast unit tests"
echo ""
echo "Workspace:"
echo "  cat .kimi/CHECKPOINT.md     # Current state"
echo "  cat .kimi/TODO.md           # Task list"
echo "  bash .kimi/scripts/resume.sh # Status check"
echo ""
echo "Happy coding! 🚀"
