# PRIME Deployment Guide

Step-by-step guide to deploying PRIME to production.

---

## Prerequisites

- Node.js 18+
- Netlify account
- Supabase account
- OpenAI API key

---

## Database Setup (Supabase)

### 1. Create Supabase Project

1. Go to [https://supabase.com](https://supabase.com)
2. Create a new project
3. Note your project URL and anon key

### 2. Run Migrations

Navigate to **SQL Editor** in Supabase dashboard and run:

```sql
-- Create gallery table (if not exists)
CREATE TABLE IF NOT EXISTS gallery (
  id SERIAL PRIMARY KEY,
  image_url TEXT NOT NULL,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Create prime_declarations table for voting
CREATE TABLE IF NOT EXISTS prime_declarations (
  id SERIAL PRIMARY KEY,
  ip_hash VARCHAR(16) NOT NULL UNIQUE,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
```

### 3. Create Storage Bucket

1. Navigate to **Storage** in Supabase dashboard
2. Create a new bucket named `gallery`
3. Set bucket to **Public**
4. Enable uploads

### 4. Set Row Level Security (RLS)

For `gallery` table:

```sql
-- Enable RLS
ALTER TABLE gallery ENABLE ROW LEVEL SECURITY;

-- Allow public read
CREATE POLICY "Public read access"
ON gallery FOR SELECT
USING (true);

-- Allow authenticated insert
CREATE POLICY "Authenticated insert access"
ON gallery FOR INSERT
WITH CHECK (true);
```

For `prime_declarations` table:

```sql
-- Enable RLS
ALTER TABLE prime_declarations ENABLE ROW LEVEL SECURITY;

-- Allow public read for count
CREATE POLICY "Public read access"
ON prime_declarations FOR SELECT
USING (true);

-- Allow public insert
CREATE POLICY "Public insert access"
ON prime_declarations FOR INSERT
WITH CHECK (true);
```

---

## Environment Variables

### Local Development (`.env.local`)

```bash
# Site URL
NEXT_PUBLIC_SITE_URL=http://localhost:3000

# OpenAI API
OPENAI_API_KEY=sk-proj-...

# Supabase
NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGc...

# Optional: Upstash Redis
UPSTASH_REDIS_REST_URL=https://...upstash.io
UPSTASH_REDIS_REST_TOKEN=...
```

### Production (Netlify Environment Variables)

1. Go to Netlify dashboard
2. Navigate to **Site configuration** → **Environment variables**
3. Add the following:

| Variable | Value |
|----------|-------|
| `NEXT_PUBLIC_SITE_URL` | `https://primenow.ltd` |
| `OPENAI_API_KEY` | Your OpenAI API key |
| `NEXT_PUBLIC_SUPABASE_URL` | Your Supabase URL |
| `NEXT_PUBLIC_SUPABASE_ANON_KEY` | Your Supabase anon key |

---

## Build & Deploy

### Manual Deployment

```bash
# Test build locally
npm run build

# Deploy to Netlify
netlify deploy --prod
```

### Automatic Deployment (Git)

1. Connect repository to Netlify
2. Set build command: `npm run build`
3. Set publish directory: `.next`
4. Every push to `master` automatically deploys

---

## Post-Deployment Checklist

- [ ] Verify site loads at production URL
- [ ] Test image transformation with `/api/prime`
- [ ] Test gallery submission
- [ ] Test voting system
- [ ] Check security headers in browser DevTools
- [ ] Verify rate limiting is working
- [ ] Test all archetype transformations
- [ ] Check Supabase logs for any errors
- [ ] Monitor OpenAI API usage

---

## Monitoring & Maintenance

### Netlify

- **Build logs**: https://app.netlify.com/projects/findyourprime/deploys
- **Function logs**: https://app.netlify.com/projects/findyourprime/logs/functions
- **Analytics**: Available in Netlify dashboard

### Supabase

- **Database logs**: Supabase dashboard → Logs
- **Storage usage**: Supabase dashboard → Storage
- **API usage**: Supabase dashboard → Settings → API

### OpenAI

- **Usage dashboard**: https://platform.openai.com/usage
- **API keys**: https://platform.openai.com/api-keys
- **Rate limits**: Check usage to avoid hitting limits

---

## Troubleshooting

### Build Fails

```bash
# Clear Next.js cache
rm -rf .next

# Reinstall dependencies
rm -rf node_modules package-lock.json
npm install

# Rebuild
npm run build
```

### API Errors

1. Check environment variables are set in Netlify
2. Verify Supabase URL and keys are correct
3. Check OpenAI API key is valid and has credits
4. Review function logs in Netlify

### Database Issues

1. Verify migrations ran successfully
2. Check RLS policies are enabled
3. Test queries in Supabase SQL Editor
4. Check storage bucket permissions

### Rate Limiting Not Working

- In-memory rate limiting is enabled by default
- Redis is optional - app works without it
- If using Redis, verify Upstash credentials

---

## Security Best Practices

1. **Rotate API keys regularly**
   - OpenAI keys should be rotated every 90 days
   - Use different keys for dev/prod

2. **Monitor API usage**
   - Set up billing alerts in OpenAI
   - Track unusual spikes in Netlify functions

3. **Keep dependencies updated**
   ```bash
   npm outdated
   npm update
   ```

4. **Review security headers**
   - Check `netlify.toml` configuration
   - Test with https://securityheaders.com

---

## Scaling Considerations

### Current Limits

- **Rate limiting**: 5 AI requests/hour per IP (in-memory)
- **File upload**: 8MB max via `/api/prime`
- **Supabase**: 500MB database, 1GB storage (free tier)
- **OpenAI**: GPT-4o image costs ~$0.04-0.08 per generation

### If Traffic Grows

1. **Enable Redis** for distributed rate limiting
2. **Increase rate limits** if needed
3. **Upgrade Supabase** plan for more storage
4. **Monitor OpenAI costs** - consider usage caps
5. **Add CDN caching** for static assets
6. **Consider image compression** for gallery

---

## Rollback Procedure

If deployment breaks production:

```bash
# Revert to previous deployment in Netlify UI
# OR deploy specific commit
git checkout <previous-commit-hash>
netlify deploy --prod
```

---

## Support

- **API Documentation**: See [API.md](API.md)
- **Architecture**: See [CLAUDE.md](CLAUDE.md)
- **Issues**: https://github.com/anthropics/claude-code/issues
