# start-dev-env

## When to Use

Use this command when you want to:
- Test your code changes in an isolated Docker Compose environment
- Verify API endpoints work correctly after modifications
- Test database interactions with a fresh copy of the main database
- Iterate on changes by testing them in a real environment
- Debug issues in an isolated environment before committing

## Prerequisites

- .NET SDK installed (`dotnet --version`)
- Main PostgreSQL database running on localhost:5432
- Docker installed and running
- PostgreSQL client (psql) installed
- Scripts are executable: `chmod +x scripts/*.sh`

## Execution Steps

### Step 1: Verify Prerequisites

Check that all prerequisites are met:

1. **Check main database is accessible:**
   Run: `PGPASSWORD=postgres psql -h localhost -p 5432 -U postgres -d managing -c '\q'`

   **If connection fails:**
   - Error: "❌ Cannot connect to main database at localhost:5432"
   - **Fix**: Start the main PostgreSQL container:
     ```bash
     cd src/Managing.Docker
     docker-compose -f docker-compose.yml -f docker-compose.local.yml up -d postgres
     ```
   - Wait 15 seconds for PostgreSQL to start
   - Retry connection check
   - **STOP** if database cannot be started

2. **Check Docker is running:**
   Run: `docker ps`

   **If Docker is not running:**
   - Error: "❌ Docker is not running"
   - **Fix**: Start Docker Desktop or Docker daemon
   - **STOP** if Docker cannot be started

### Step 2: Generate Task ID

Generate a unique task ID for this dev session:

- Use format: `DEV-{timestamp}` or `DEV-{random}`
- Example: `DEV-20250101-143022` or `DEV-A3X9`
- Store this ID for later reference

### Step 3: Find Available Port

Find an available port offset to avoid conflicts:

- Start with offset 0 (ports: 5433, 5000, 6379)
- If ports are in use, try offset 10, 20, 30, etc.
- Check if ports are available:
  ```bash
  lsof -i :5433 || echo "Port 5433 available"
  lsof -i :5000 || echo "Port 5000 available"
  ```

### Step 4: Start Docker Environment

Start the Docker Compose environment with database copy:

Run: `bash scripts/start-task-docker.sh {TASK_ID} {PORT_OFFSET}`

**Example:**
```bash
bash scripts/start-task-docker.sh DEV-A3X9 0
```

**Or use the simple wrapper:**
```bash
bash scripts/start-dev-env.sh DEV-A3X9 0
```

**What this does:**
1. Creates task-specific Docker Compose file
2. Starts PostgreSQL on port 5433 (or 5432 + offset)
3. Starts Redis on port 6379 (or 6379 + offset)
4. Waits for PostgreSQL to be ready
5. Copies database from main repo (localhost:5432) to test instance
6. Starts API and Workers with correct connection strings
7. Uses main InfluxDB instance at localhost:8086

**If start succeeds:**
- Note the API URL (e.g., "http://localhost:5000")
- Note the database name (e.g., "managing_dev-a3x9")
- Continue to Step 5

**If start fails:**
- Check error messages
- Common issues:
  - Port conflicts: Try different port offset
  - Database connection: Verify main database is running
  - Docker issues: Check Docker is running
- **Try to fix:**
  - Use different port offset
  - Restart Docker
  - Verify main database is accessible
- **STOP** if cannot start after multiple attempts

### Step 5: Verify Environment is Running

Verify the Docker environment is working:

1. **Check API health endpoint:**
   Run: `curl http://localhost:{API_PORT}/health`

   **If health check fails:**
   - Wait 30 seconds for services to start
   - Check Docker logs: `docker logs managing-api-{TASK_ID}`
   - Check for errors
   - **STOP** if services don't start after 2 minutes

2. **Verify database was copied:**
   Run: `PGPASSWORD=postgres psql -h localhost -p {POSTGRES_PORT} -U postgres -d managing_{TASK_ID} -c "SELECT COUNT(*) FROM \"Users\";"`

   **If database is empty or missing:**
   - Error: "❌ Database was not copied correctly"
   - **Fix**: Re-run database copy script manually
   - **STOP** if database cannot be copied

### Step 6: Test Your Changes

Now you can test your changes:

1. **API endpoints:**
   - Use API URL: `http://localhost:{API_PORT}`
   - Test modified endpoints
   - Verify responses are correct

2. **Database interactions:**
   - Changes are isolated to this test database
   - Main database remains unchanged
   - Can test migrations, data changes, etc.

3. **Iterate:**
   - Make code changes
   - Rebuild solution: `/build-solution`
   - Rebuild Docker images if needed: `docker-compose -f {COMPOSE_FILE} build`
   - Restart services: `docker-compose -f {COMPOSE_FILE} restart managing-api-{TASK_ID}`
   - Test again

### Step 7: Stop Instance When Done

When finished testing, stop the Docker environment:

Run: `bash scripts/stop-task-docker.sh {TASK_ID}`

**Example:**
```bash
bash scripts/stop-task-docker.sh DEV-A3X9
```

This will:
- Stop all containers
- Remove volumes
- Clean up compose file

## Integration with Development Workflow

### After Making Code Changes

1. **Build solution:**
   - Run: `/build-solution`
   - Fix any build errors

2. **Start Docker environment for testing:**
   - Run: `/start-aspire-dev`
   - Note the URLs

3. **Test your changes:**
   - Use the API endpoints
   - Verify database interactions
   - Check logs: `docker logs managing-api-{TASK_ID}`

4. **Iterate if needed:**
   - Fix issues found during testing
   - Rebuild Docker images if code changed
   - Restart services
   - Test again

5. **Stop when done:**
   - Stop the Docker environment
   - Clean up if needed

### When to Use This Command

- ✅ After modifying API endpoints
- ✅ After changing database models
- ✅ After updating business logic
- ✅ Before committing changes
- ✅ When debugging issues
- ✅ When testing integrations

### When NOT to Use This Command

- ❌ For production deployments (use proper CI/CD)
- ❌ For running unit tests (use test runner)
- ❌ For code review (use static analysis)

## Error Handling

**If main database is not accessible:**
- Start PostgreSQL container: `cd src/Managing.Docker && docker-compose up -d postgres`
- Wait 15 seconds
- Retry connection check
- **STOP** if database cannot be started

**If ports are in use:**
- Try different port offset (10, 20, 30, etc.)
- Check what's using the ports: `lsof -i :{PORT}`
- Stop conflicting services if needed

**If database copy fails:**
- Verify main database is accessible
- Check PostgreSQL client is installed: `which psql`
- Verify connection strings are correct
- Check disk space
- **STOP** if copy cannot complete

**If Docker services don't start:**
- Check Docker logs: `docker logs {container_id}`
- Verify all dependencies are installed
- Check .NET SDK version matches requirements
- **STOP** if services cannot start after multiple attempts

## Example Execution

**User input:** `/start-dev-env`

**AI execution:**

1. Verify prerequisites:
   - Check main database: ✅ Accessible
   - Check Docker: ✅ Running

2. Generate task ID: `DEV-A3X9`

3. Find available port: Offset 0 (ports available)

4. Start Docker environment:
   ```bash
   bash scripts/start-task-docker.sh DEV-A3X9 0
   ```
   - Creating compose file...
   - Starting PostgreSQL...
   - ✅ PostgreSQL ready
   - Copying database...
   - ✅ Database copied
   - Starting API and Workers...
   - ✅ Services started

5. Verify:
   - API: http://localhost:5000 ✅
   - Health check: ✅ Healthy
   - Database: ✅ Copied (1234 users found)

6. Success: "✅ Docker dev environment ready!"
   - API: http://localhost:5000
   - Database: managing_dev-a3x9 on port 5433
   - To stop: `bash scripts/stop-task-docker.sh DEV-A3X9`

## Important Notes

- ✅ **Always verify main database first** - Must be accessible
- ✅ **Use unique task IDs** - Prevents conflicts
- ✅ **Check port availability** - Avoids port conflicts
- ✅ **Wait for services to start** - Can take 30-60 seconds
- ✅ **Database is isolated** - Changes don't affect main database
- ✅ **InfluxDB uses main instance** - No separate InfluxDB per task
- ✅ **Stop when done** - Frees up resources
- ⚠️ **Multiple instances** - Each needs unique ports
- ⚠️ **Resource usage** - Each instance uses memory/CPU
- 📦 **Script location**: `scripts/start-task-docker.sh`
- 🔧 **Main database**: localhost:5432
- 🗄️ **Test databases**: localhost:5433+ (isolated per task)
- 📊 **InfluxDB**: Uses main instance at localhost:8086

