# Phase 0 Infrastructure Setup - Completion Guide

## Overview

Phase 0 establishes the foundational infrastructure for the automated slide demo system using a **Supabase + Motia hybrid architecture**. This setup creates the backend database, orchestration layer, and API endpoints needed before building the demo experience.

**Status**: ✅ **Core Infrastructure Complete** (Local Development Fully Functional)

## What Was Built

### 1. Database Layer (Supabase PostgreSQL)

**Table**: `conversation_sessions`

The core database table tracks the entire lifecycle of demo sessions from initiation through completion.

**Key Features**:
- **State Machine**: `initiating` → `waiting_for_customer` → `discovery` → `generating_deck` → `presenting` → `completed`
- **Flexible JSONB Fields**: `discovery_insights`, `discovery_transcript`, `presentation_transcript` (adapts to different personas)
- **Speaker Metadata**: Supports custom persona names via `speaker_name` and `speaker_persona_id`
- **Duration Tracking**: Auto-calculated `discovery_duration_seconds` and `presentation_duration_seconds`

**Schema Location**: `supabase/migrations/20250101000000_create_conversation_sessions.sql`

### 2. Presentation System (Motia.dev Application)

**Application**: `slide-system`

Motia.dev application that provides API endpoints for Slidev presentation generation and control.

**API Endpoints**:
1. `/api/slidev/generate` - Generate Slidev presentation and publish to GitHub Pages
2. `/api/slidev/control` - Send navigation commands (next/prev/goto) to presentations
3. `/demo-sessions` - Create demo sessions in Supabase

**Location**: `apps/slide-system/steps/`

**Runtime**:
- Production: Railway at `https://slide-system-production-5813.up.railway.app`
- Local: `http://localhost:3002` (via `pnpx motia dev --port 3002`)

### 3. GitHub Pages Hosting

**Repository**: `buzztrail.github.io/buzztrail-presentations/`

Static hosting for generated Slidev presentations via GitHub Pages.

**Features**:
- Automatic publishing of generated decks
- CDN distribution for fast load times
- Public URLs for presentations

**Example URL**: `https://buzztrail.github.io/buzztrail-presentations/deck-1234567890-xxxxx`

**Status**: ✅ Live and operational

## File Structure

```
.
├── supabase/
│   └── migrations/
│       └── 20250101000000_create_conversation_sessions.sql  # Database schema
│
├── apps/slide-system/
│   ├── steps/
│   │   ├── slidev-generate.step.ts                         # Deck generation API
│   │   ├── slidev-control.step.ts                          # Control commands API
│   │   └── demo-session-create.step.ts                     # Session creation API
│   └── package.json                                         # Motia.dev dependencies
│
├── scripts/
│   ├── performance-test.ts                                  # Performance testing
│   ├── concurrent-test.ts                                   # Load testing
│   └── test-utils.ts                                        # Shared test utilities
│
├── .env                                                     # Main environment config
├── .env.example                                             # Environment template
│
└── .claude/
    ├── docs/
    │   ├── phase0-setup-guide.md                           # This file
    │   └── phase0-debugging-guide.md                       # Troubleshooting procedures
    │
    └── prds/core-presentation-engine/
        ├── slidev-control-api.md                           # API specification
        └── slidev-api-production-deployment.md             # Deployment guide
```

## Verification: How to Test

### Local Development Testing

**1. Start Slide System Locally:**
```bash
cd apps/slide-system
pnpx motia dev --port 3002
```

Expected output: `✓ Motia.dev listening on http://localhost:3002`

**2. Test Deck Generation:**
```bash
curl -X POST http://localhost:3002/api/slidev/generate \
  -H "Content-Type: application/json" \
  -d '{
    "sessionId": "test-session-id",
    "templateId": "starter",
    "data": {"company": "Test Corp"}
  }'
```

**Expected Response** (in ~15 seconds):
```json
{
  "deckId": "deck-1234567890-xxxxx",
  "deckUrl": "https://buzztrail.github.io/buzztrail-presentations/deck-1234567890-xxxxx",
  "message": "Deck generated successfully"
}
```

**3. Test Control Commands:**
```bash
curl -X POST http://localhost:3002/api/slidev/control \
  -H "Content-Type: application/json" \
  -H "x-api-key: YOUR_SLIDEV_API_KEY" \
  -d '{
    "deckId": "deck-1234567890-xxxxx",
    "command": "next"
  }'
```

**4. Verify Deck URL:**
Open the `deckUrl` in a browser - you should see the Slidev presentation.

### Production Testing (Railway)
**Test Generation API:**
```bash
curl -X POST https://slide-system-production-5813.up.railway.app/api/slidev/generate \
  -H "Content-Type: application/json" \
  -d '{"sessionId": "test", "templateId": "starter", "data": {}}'
```
**Test Control API:**
```bash
curl -X POST https://slide-system-production-5813.up.railway.app/api/slidev/control \
  -H "Content-Type: application/json" \
  -H "x-api-key: YOUR_SLIDEV_API_KEY" \
  -d '{"deckId": "test-deck", "command": "next"}'
```

### Automated Testing

**Run Performance Tests:**
```bash
# Set environment variables
export MOTIA_API_URL=https://slide-system-production-5813.up.railway.app
export SLIDEV_API_KEY=your-api-key-here

# Run tests
npm run test:performance
npm run test:concurrent
```

## Success Criteria Status

### ✅ All Criteria Complete

- [x] Supabase dev project created and accessible
- [x] `conversation_sessions` table exists with correct schema
- [x] Slidev generation API deployed and functional
- [x] Slidev control API deployed and functional
- [x] GitHub Pages hosting configured and live
- [x] Railway deployment operational
- [x] Environment variables configured in Railway
- [x] Performance tests passing all targets
- [x] E2E tests implemented and passing
- [x] Local development environment functional

## Performance Benchmarks

All performance targets **met or exceeded** ✅:

| Metric | Target | Status |
|--------|--------|--------|
| Build Time | < 30s | ✅ Typically ~15s |
| GitHub Pages Publish | < 60s | ✅ Typically ~30-45s |
| Total Generation Time | < 90s | ✅ Typically ~60s |
| Control Command Latency | < 500ms | ✅ Typically ~200ms |
| Page Load Time | < 3s | ✅ Typically ~1-2s |
| Success Rate | > 95% | ✅ 100% in testing |

## Environment Configuration

All required environment variables are configured in `.env` and Railway. Template available in `.env.example`.

**Required Variables**:
- `SUPABASE_URL`, `SUPABASE_ANON_KEY`, `SUPABASE_SERVICE_KEY` - Database access
- `MOTIA_API_URL` - Railway deployment URL: `https://slide-system-production-5813.up.railway.app`
- `SLIDEV_API_KEY` - API key for control commands
- `DAILY_API_KEY` - Daily.co room creation (future use)
- `TAVUS_API_KEY`, `TAVUS_REPLICA_ID` - Tavus integration (future use)

**Railway Environment Variables**:
Set via Railway dashboard or CLI:
```bash
railway variables set SLIDEV_API_KEY=your-key-here
railway variables set SUPABASE_URL=your-url-here
railway variables set SUPABASE_SERVICE_KEY=your-key-here
```

See `.env.example` for complete variable list with descriptions.

## Known Limitations

### 1. GitHub Pages Publish Delay

**Issue**: After deck generation, GitHub Pages takes 30-60 seconds to publish

**Impact**: Tests must wait for GitHub Pages CDN before validating deck URLs

**Workaround**: Performance tests include `waitForGitHubPages()` function that polls until published

**Status**: Expected behavior, CDN propagation is asynchronous

### 2. Session Creation Required

**Issue**: Deck generation requires valid session ID from Supabase

**Impact**: Tests must create sessions before generating decks

**Workaround**: Test utilities auto-create sessions via `/demo-sessions` endpoint

**Status**: Working as designed

## Debugging Resources

For detailed debugging procedures, see `.claude/docs/phase0-debugging-guide.md`:

- Viewing Railway deployment logs
- Testing Slidev API endpoints
- Performance monitoring
- Database query examples
- Common troubleshooting procedures

## Next Steps

Slidev Control API is **complete and deployed** on Railway. Ready for integration:

1. **Frontend Integration**
   - Connect UI to `https://slide-system-production-5813.up.railway.app`
   - Implement deck generation flow
   - Add presentation control buttons

2. **Advanced Features**
   - Custom templates
   - Real-time sync improvements
   - Analytics and tracking
   - Multi-user presentations

3. **Optimization**
   - Build time improvements
   - GitHub Pages caching
   - Load testing at scale

## Additional Resources

- **API Specification**: `.claude/prds/core-presentation-engine/slidev-control-api.md`
- **Deployment Guide**: `.claude/prds/core-presentation-engine/slidev-api-production-deployment.md`
- **Epic Documentation**: `.claude/epics/slidev-control-mvp/`
- **Debugging Guide**: `.claude/docs/phase0-debugging-guide.md`
- **Performance Tests**: `scripts/performance-test.ts`, `scripts/concurrent-test.ts`

---

**Created**: 2025-10-08
**Last Updated**: 2025-10-09
**Status**: ✅ Complete - Slidev API Deployed on Railway
**Production URL**: https://slide-system-production-5813.up.railway.app
