# Local Development Setup Guide

This guide provides step-by-step instructions for setting up and running the Data Analysis Platform on your local machine.

---

## Table of Contents

1. [Prerequisites Installation](#1-prerequisites-installation)
2. [Backend Setup](#2-backend-setup)
3. [Frontend Setup](#3-frontend-setup)
4. [Running Both Services](#4-running-both-services)
5. [Verification](#5-verification)
6. [Common Issues and Solutions](#6-common-issues-and-solutions)
7. [Development Tips](#7-development-tips)

---

## 1. Prerequisites Installation

### Verify Your Installation

Before starting, verify you have the required tools installed:

```bash
# Check Python version (must be 3.12+)
python3.12 --version

# Check Node.js version (must be 20+)
node --version

# Check npm (comes with Node.js)
npm --version

# Check UV (Python package manager)
uv --version
```

### Install Missing Prerequisites

#### Python 3.12

**macOS (using Homebrew):**
```bash
brew install python@3.12
```

**Ubuntu/Debian:**
```bash
sudo apt update
sudo apt install python3.12 python3.12-venv
```

**Windows:**
Download from [python.org](https://www.python.org/downloads/)

#### Node.js 20+

**macOS (using Homebrew):**
```bash
brew install node
```

**Ubuntu/Debian:**
```bash
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs
```

**Windows:**
Download from [nodejs.org](https://nodejs.org/)

#### UV (Python Package Manager)

```bash
pip install uv
# or
pipx install uv
```

---

## 2. Backend Setup

### Step 1: Navigate to Backend Directory

```bash
cd backend
```

### Step 2: Create Virtual Environment

A virtual environment isolates your project dependencies:

```bash
# Create virtual environment
python3.12 -m venv .venv

# Activate on macOS/Linux
source .venv/bin/activate

# Activate on Windows
.venv\Scripts\activate
```

You should see `(.venv)` appear in your terminal prompt.

### Step 3: Install Dependencies with UV

UV is a fast Python package installer that resolves dependencies quickly:

```bash
uv sync
```

This reads `pyproject.toml` and `uv.lock` to install exact versions of all dependencies.

### Step 4: Verify Installation

```bash
python -c "import fastapi; import pandas; import pyarrow; print('All dependencies installed!')"
```

### Step 5: Start the Backend Server

```bash
uvicorn main:app --reload --host 0.0.0.0 --port 8000
```

**Command explained:**
- `uvicorn` - ASGI server for FastAPI
- `main:app` - Points to the FastAPI app instance in `main.py`
- `--reload` - Auto-reload on code changes (development mode)
- `--host 0.0.0.0` - Listen on all network interfaces
- `--port 8000` - Use port 8000

You should see output like:
```
INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [12345] using WatchFiles
INFO:     Started server process [12346]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
```

### Step 6: Access Backend Services

Open your browser and navigate to:

- **API Root:** http://localhost:8000
- **Swagger UI (Interactive API Docs):** http://localhost:8000/docs
- **ReDoc (Alternative API Docs):** http://localhost:8000/redoc

---

## 3. Frontend Setup

### Step 1: Open New Terminal

Keep the backend running in its terminal. Open a **new terminal** for the frontend.

### Step 2: Navigate to Frontend Directory

```bash
cd frontend
```

### Step 3: Install Dependencies

```bash
npm install
```

This downloads all packages listed in `package.json` and `package-lock.json`.

Expected output includes packages like:
- `next` (16.1.1)
- `react` (19.2.3)
- `typescript` (latest)
- `tailwindcss` (4+)
- `apache-arrow` (21+)

### Step 4: Configure Environment (Optional)

Check if `.env.local` exists:

```bash
ls -la .env.local
```

If not present, create it from the example (if available):

```bash
cp .env.local.example .env.local
```

Edit `.env.local` to configure environment-specific settings like API endpoints.

### Step 5: Start the Frontend Development Server

```bash
npm run dev
```

You should see output like:
```
   ▲ Next.js 16.1.1
   - Local:        http://localhost:3000
   - Network:      http://192.168.1.X:3000

 ✓ Ready in 2.3s
```

### Step 6: Access Frontend Application

Open your browser and navigate to:

**Frontend App:** http://localhost:3000

---

## 4. Running Both Services

For full-stack development, run both services simultaneously.

### Option 1: Two Terminals (Recommended for Development)

**Terminal 1 - Backend:**
```bash
cd backend
source .venv/bin/activate  # or .venv\Scripts\activate on Windows
uvicorn main:app --reload --host 0.0.0.0 --port 8000
```

**Terminal 2 - Frontend:**
```bash
cd frontend
npm run dev
```

### Option 2: Background Processes

**Backend:**
```bash
cd backend
source .venv/bin/activate
uvicorn main:app --reload --host 0.0.0.0 --port 8000 > ../backend.log 2>&1 &
```

**Frontend:**
```bash
cd frontend
npm run dev > ../frontend.log 2>&1 &
```

View logs:
```bash
tail -f backend.log
tail -f frontend.log
```

---

## 5. Verification

### Test Backend Health

```bash
curl http://localhost:8000/docs
```

Or open http://localhost:8000/docs in your browser.

### Test Frontend

Open http://localhost:3000 in your browser.

### Check API Connectivity

From the frontend, you should be able to make requests to the backend at `http://localhost:8000`.

---

## 6. Common Issues and Solutions

### Port Already in Use

**Error:** `Address already in use`

**Solution:**
```bash
# Find process using port 8000 (backend)
lsof -i :8000
# or
netstat -tlnp | grep :8000

# Kill the process
kill -9 <PID>

# Or use a different port
uvicorn main:app --reload --port 8001
```

### Virtual Environment Issues

**Error:** Python command not found or wrong Python version

**Solution:**
```bash
# Deactivate current environment
deactivate

# Remove and recreate virtual environment
rm -rf .venv
python3.12 -m venv .venv
source .venv/bin/activate
uv sync
```

### Module Import Errors

**Error:** `ModuleNotFoundError: No module named 'fastapi'`

**Solution:**
```bash
# Ensure virtual environment is activated
source .venv/bin/activate

# Reinstall dependencies
uv sync
```

### Frontend Build Errors

**Error:** `Cannot find module 'X'`

**Solution:**
```bash
# Clear node_modules and reinstall
rm -rf node_modules package-lock.json
npm install
```

### CORS Errors (Frontend Cannot Access Backend)

**Error:** Browser console shows CORS policy errors

**Solution:**
Ensure the backend has CORS middleware configured. Check `backend/main.py` for:

```python
from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3000"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
```

---

## 7. Development Tips

### Hot Reload

- **Backend:** UVicorn's `--reload` flag automatically restarts the server when Python files change
- **Frontend:** Next.js dev server automatically refreshes the browser when files change

### Useful Commands

**Backend:**
```bash
# Run tests
pytest

# Run with verbose output
uvicorn main:app --reload --log-level debug
```

**Frontend:**
```bash
# Run tests (when configured)
npm test

# Build for production
npm run build

# Run production build
npm start

# Lint code
npm run lint
```

### IDE Recommendations

- **VS Code** with extensions:
  - Python (Microsoft)
  - Pylance
  - ESLint
  - Tailwind CSS IntelliSense
  - Thunder Client (for API testing)

### Debugging

**Backend:** Use VS Code's debugger with launch configuration:
```json
{
    "name": "Python: FastAPI",
    "type": "debugpy",
    "request": "launch",
    "module": "uvicorn",
    "args": ["main:app", "--reload", "--host", "0.0.0.0", "--port", "8000"],
    "cwd": "${workspaceFolder}/backend"
}
```

**Frontend:** Use Chrome DevTools or React DevTools browser extension.

---

## Next Steps

Once both services are running:

1. Explore the API documentation at http://localhost:8000/docs
2. Interact with the frontend at http://localhost:3000
3. Review the project context at `_bmad-output/project-context.md`
4. Check planning artifacts in `_bmad-output/planning-artifacts/`

For Docker deployment instructions, see the main README.md (coming soon).

---

**Last Updated:** 2026-01-11
