> ## Documentation Index
> Fetch the complete documentation index at: https://docs.risklegion.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Environment Setup

> Configure environments for Risk Legion deployment

## Environment Overview

Risk Legion supports three environments:

| Environment     | Purpose           | Domain                  |
| --------------- | ----------------- | ----------------------- |
| **Development** | Local development | localhost               |
| **Staging**     | Testing and QA    | api-test.risklegion.com |
| **Production**  | Live system       | api.risklegion.com      |

## Supabase Project Setup

### 1. Create Project

1. Go to [supabase.com](https://supabase.com)
2. Create a new project
3. Note down:
   * Project URL
   * Anon Key (public)
   * Service Role Key (secret)

### 2. Database Setup

Run migrations to set up the database schema:

```sql theme={null}
-- See /backend/migrations/ for full schema
-- Tables: enterprises, profiles, enterprise_users, etc.
```

### 3. Enable Row Level Security

```sql theme={null}
-- Enable RLS on all tables
ALTER TABLE enterprises ENABLE ROW LEVEL SECURITY;
ALTER TABLE business_risk_assessments ENABLE ROW LEVEL SECURITY;
-- ... for all tables
```

### 4. Configure Auth

In Supabase Dashboard → Authentication:

1. Enable Email/Password provider
2. Configure password requirements
3. Set up email templates (optional)
4. Configure redirect URLs

## Backend Environment

### Required Variables

```bash theme={null}
# backend/.env

# Supabase
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
SUPABASE_SERVICE_ROLE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
DATABASE_URL=postgresql://postgres:[password]@db.[project].supabase.co:5432/postgres

# Application
SECRET_KEY=your-256-bit-secret-key
ENVIRONMENT=development  # development, staging, production
DEBUG=true  # false in production
APP_VERSION=1.0.0

# Redis
REDIS_URL=redis://localhost:6379

# CORS
ALLOWED_ORIGINS=http://localhost:5173,https://app.risklegion.com

# Rate Limiting
RATE_LIMIT_REQUESTS=100
RATE_LIMIT_WINDOW=60

# Optional: Error Tracking
SENTRY_DSN=https://your-sentry-dsn
```

### Generate Secret Key

```bash theme={null}
# Python
python -c "import secrets; print(secrets.token_hex(32))"

# OpenSSL
openssl rand -hex 32
```

## Frontend Environment

### Required Variables

```bash theme={null}
# risk-legion-frontend/.env.local

VITE_SUPABASE_URL=https://your-project.supabase.co
VITE_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
VITE_API_URL=http://localhost:8000
```

### Environment-Specific Files

```
.env.local          # Local overrides (not committed)
.env.development    # Development defaults
.env.staging        # Staging values
.env.production     # Production values
```

## AWS Setup (EC2)

### 1. Create EC2 Instance

* **Type:** t3.small or larger
* **AMI:** Ubuntu 22.04 LTS
* **Security Group:** Allow ports 22, 80, 443, 8000

### 2. Install Docker

```bash theme={null}
ssh ec2-user@your-instance

# Install Docker
curl -fsSL https://get.docker.com | sh
sudo usermod -aG docker $USER
```

### 3. Configure nginx

```nginx theme={null}
# /etc/nginx/sites-available/risklegion

server {
    listen 80;
    server_name api.risklegion.com;

    location / {
        proxy_pass http://localhost:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
```

### 4. Set Up SSL

```bash theme={null}
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d api.risklegion.com
```

## GitHub Secrets

Configure these secrets in GitHub repository settings:

### AWS Secrets

| Secret                  | Description            |
| ----------------------- | ---------------------- |
| `AWS_ACCESS_KEY_ID`     | AWS access key         |
| `AWS_SECRET_ACCESS_KEY` | AWS secret key         |
| `EC2_HOST`              | EC2 instance public IP |
| `EC2_USER`              | SSH username (ubuntu)  |
| `EC2_SSH_KEY`           | Private SSH key        |
| `EC2_SSH_PORT`          | SSH port (22)          |

### Application Secrets

| Secret                      | Description                             |
| --------------------------- | --------------------------------------- |
| `SUPABASE_URL`              | Supabase project URL                    |
| `SUPABASE_ANON_KEY`         | Supabase anon key                       |
| `SUPABASE_SERVICE_ROLE_KEY` | Supabase service role key               |
| `DATABASE_URL`              | Direct database connection string       |
| `SECRET_KEY`                | Application secret key                  |
| `SENTRY_DSN`                | Sentry error tracking DSN               |
| `GH_PAT`                    | GitHub Personal Access Token (for GHCR) |

## Vercel Setup (Frontend)

### 1. Connect Repository

1. Go to [vercel.com](https://vercel.com)
2. Import GitHub repository
3. Select `risk-legion-frontend` directory

### 2. Configure Environment

In Vercel Dashboard → Settings → Environment Variables:

| Variable                 | Value                        |
| ------------------------ | ---------------------------- |
| `VITE_SUPABASE_URL`      | Your Supabase URL            |
| `VITE_SUPABASE_ANON_KEY` | Your anon key                |
| `VITE_API_URL`           | `https://api.risklegion.com` |

### 3. Configure Rewrites

In `vercel.json`:

```json theme={null}
{
  "rewrites": [
    { "source": "/(.*)", "destination": "/" }
  ]
}
```

## Environment Validation

### Backend Startup Check

The backend validates required environment variables on startup:

```python theme={null}
# app/config.py
from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    SUPABASE_URL: str
    SUPABASE_ANON_KEY: str
    SECRET_KEY: str
    
    class Config:
        env_file = ".env"

settings = Settings()  # Raises error if missing required vars
```

### Health Check Validation

```bash theme={null}
# Verify backend is configured correctly
curl http://localhost:8000/health
```

Expected response:

```json theme={null}
{
  "status": "healthy",
  "components": {
    "database": "healthy",
    "redis": "healthy"
  }
}
```
