#!/bin/bash
set -e

echo "🚀 Setting up Trax development environment..."

# Color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Check Python version - prefer python3.11
if command -v python3.11 &> /dev/null; then
    PYTHON_CMD="python3.11"
    python_version=$($PYTHON_CMD --version | cut -d' ' -f2)
    echo -e "${GREEN}✅ Python $python_version${NC}"
elif command -v python3 &> /dev/null; then
    PYTHON_CMD="python3"
    python_version=$($PYTHON_CMD --version | cut -d' ' -f2 | cut -d'.' -f1,2)
    required_version="3.11"
    if [ "$(printf '%s\n' "$required_version" "$python_version" | sort -V | head -n1)" != "$required_version" ]; then
        echo -e "${RED}❌ Python 3.11+ required (found $python_version)${NC}"
        echo -e "${YELLOW}💡 Try: brew install python@3.11${NC}"
        exit 1
    fi
    echo -e "${GREEN}✅ Python $python_version${NC}"
else
    echo -e "${RED}❌ Python 3 not found${NC}"
    exit 1
fi

# Install uv if needed
if ! command -v uv &> /dev/null; then
    echo -e "${YELLOW}📦 Installing uv...${NC}"
    curl -LsSf https://astral.sh/uv/install.sh | sh
    export PATH="$HOME/.cargo/bin:$PATH"
fi
echo -e "${GREEN}✅ uv installed${NC}"

# Setup virtual environment
echo -e "${YELLOW}🔧 Creating virtual environment...${NC}"
uv venv
source .venv/bin/activate

# Install dependencies
echo -e "${YELLOW}📚 Installing dependencies...${NC}"
uv pip install -e ".[dev]"

# Setup pre-commit hooks
echo -e "${YELLOW}🪝 Setting up pre-commit hooks...${NC}"
cat > .git/hooks/pre-commit << 'EOF'
#!/bin/bash
source .venv/bin/activate
echo "Running pre-commit checks..."
uv run black --check src/ tests/
uv run ruff check src/ tests/
uv run mypy src/
EOF
chmod +x .git/hooks/pre-commit

# Create directories
echo -e "${YELLOW}📁 Creating project directories...${NC}"
mkdir -p data/{media,exports,cache}
mkdir -p tests/{unit,integration,fixtures/audio,fixtures/transcripts}
mkdir -p src/agents/rules
mkdir -p docs/{reports,team,architecture}

# Check PostgreSQL
if command -v psql &> /dev/null; then
    echo -e "${GREEN}✅ PostgreSQL installed${NC}"
else
    echo -e "${YELLOW}⚠️  PostgreSQL not found - please install${NC}"
fi

# Check FFmpeg
if command -v ffmpeg &> /dev/null; then
    echo -e "${GREEN}✅ FFmpeg installed${NC}"
else
    echo -e "${YELLOW}⚠️  FFmpeg not found - please install${NC}"
fi

# Setup test data
echo -e "${YELLOW}🎵 Setting up test fixtures...${NC}"
cat > tests/fixtures/README.md << 'EOF'
# Test Fixtures

Place test audio files here:
- sample_5s.wav (5-second test)
- sample_30s.mp3 (30-second test)
- sample_2m.mp4 (2-minute test)

These should be real audio files for testing.
EOF

echo -e "${GREEN}✅ Development environment ready!${NC}"
echo ""
echo "📝 Next steps:"
echo "  1. source .venv/bin/activate"
echo "  2. Set up PostgreSQL database"
echo "  3. Add test audio files to tests/fixtures/audio/"
echo "  4. uv run pytest  # Run tests"
echo "  5. uv run python src/cli/main.py --help  # Run CLI"
