# Language Services - AWS CloudFormation Templates

This directory contains CloudFormation templates for deploying the Language Services Platform to AWS.

## Templates Overview

| Template | Description |
|----------|-------------|
| `master-stack.yaml` | Complete deployment including VPC, ECS, ALB, S3, Secrets, IAM |
| `secrets-only.yaml` | Secrets Manager secret only |
| `s3-buckets-only.yaml` | S3 buckets (input/output) only |
| `iam-roles-only.yaml` | IAM roles and policies only |
| `security-groups-only.yaml` | Security groups only |
| `task-definition.json` | ECS task definition template |
| `iam-policy.json` | IAM policy document template |

## Quick Start

### Prerequisites

1. AWS CLI installed and configured
2. Docker image pushed to ECR or available on Docker Hub
3. License key from Business Compass LLC

### Deploy Using the Script

```bash
# Set required environment variables
export LICENSE_KEY="your-license-key"
export AUTH_PASSWORD="your-secure-password"
export AUTH_SECRET="your-jwt-secret-min-32-chars-recommended"
export CONTAINER_IMAGE="123456789.dkr.ecr.us-east-1.amazonaws.com/language-services:latest"

# Optional
export OPENAI_API_KEY="sk-your-openai-key"
export DOMAIN_NAME="app.yourdomain.com"
export CERTIFICATE_ARN="arn:aws:acm:us-east-1:123456789:certificate/abc123"

# Run deployment
chmod +x deploy.sh
./deploy.sh
```

### Deploy Using AWS CLI

```bash
aws cloudformation deploy \
  --template-file master-stack.yaml \
  --stack-name language-services-production \
  --region us-east-1 \
  --capabilities CAPABILITY_NAMED_IAM \
  --parameter-overrides \
    AppName=language-services \
    Environment=production \
    LicenseKey="your-license-key" \
    ContainerImage="your-ecr-image-uri" \
    AuthUsername=admin \
    AuthPassword="your-password" \
    AuthSecret="your-jwt-secret"
```

## Parameters Reference

### Required Parameters

| Parameter | Description |
|-----------|-------------|
| `LicenseKey` | License key for the application |
| `ContainerImage` | Docker image URI (ECR or Docker Hub) |
| `AuthPassword` | Password for application authentication |
| `AuthSecret` | JWT secret for authentication tokens |

### Optional Parameters

| Parameter | Default | Description |
|-----------|---------|-------------|
| `AppName` | language-services | Application name for resource naming |
| `Environment` | production | Deployment environment |
| `AuthUsername` | admin | Username for authentication |
| `OpenAIApiKey` | (empty) | OpenAI API key for AI features |
| `TaskCPU` | 1024 | CPU units (256, 512, 1024, 2048, 4096) |
| `TaskMemory` | 2048 | Memory in MB |
| `DesiredCount` | 2 | Number of ECS tasks |
| `MinCapacity` | 1 | Minimum tasks for auto-scaling |
| `MaxCapacity` | 4 | Maximum tasks for auto-scaling |
| `DomainName` | (empty) | Custom domain name |
| `CertificateArn` | (empty) | ACM certificate ARN for HTTPS |

### Network Parameters

| Parameter | Default | Description |
|-----------|---------|-------------|
| `VpcCIDR` | 10.0.0.0/16 | VPC CIDR block |
| `PublicSubnet1CIDR` | 10.0.1.0/24 | Public Subnet 1 CIDR |
| `PublicSubnet2CIDR` | 10.0.2.0/24 | Public Subnet 2 CIDR |
| `PrivateSubnet1CIDR` | 10.0.3.0/24 | Private Subnet 1 CIDR |
| `PrivateSubnet2CIDR` | 10.0.4.0/24 | Private Subnet 2 CIDR |

## Architecture

```
                    ┌─────────────────────────────────────────────────────────────┐
                    │                         VPC                                  │
                    │  ┌─────────────────────────────────────────────────────────┐│
                    │  │                   Public Subnets                        ││
Internet ──────────────►  ┌─────────────┐                                        ││
                    │  │  │     ALB     │                                        ││
                    │  │  └──────┬──────┘                                        ││
                    │  │         │                     ┌──────────────┐          ││
                    │  │         │                     │  NAT Gateway │          ││
                    │  └─────────┼─────────────────────┴──────────────┴──────────┘│
                    │            │                            │                    │
                    │  ┌─────────┼────────────────────────────┼──────────────────┐│
                    │  │         │    Private Subnets         │                  ││
                    │  │         ▼                            ▼                  ││
                    │  │  ┌─────────────┐            ┌─────────────────┐         ││
                    │  │  │ ECS Fargate │───────────►│  AWS Services   │         ││
                    │  │  │   Tasks     │            │ (S3, Textract,  │         ││
                    │  │  │             │◄───────────│  Transcribe,    │         ││
                    │  │  │ Port 3000   │            │  Translate,     │         ││
                    │  │  │ Port 5000   │            │  Polly, etc.)   │         ││
                    │  │  └─────────────┘            └─────────────────┘         ││
                    │  └─────────────────────────────────────────────────────────┘│
                    └─────────────────────────────────────────────────────────────┘
```

## Resources Created

### Networking
- VPC with DNS support
- 2 Public Subnets (for ALB)
- 2 Private Subnets (for ECS tasks)
- Internet Gateway
- NAT Gateway with Elastic IP
- Route Tables
- S3 VPC Endpoint (Gateway)

### Security
- ALB Security Group (ports 80, 443)
- ECS Security Group (ports 3000, 5000 from ALB only)

### Storage
- Input S3 Bucket (encrypted, versioned, 30-day lifecycle)
- Output S3 Bucket (encrypted, versioned, 90-day lifecycle)

### Secrets
- Secrets Manager secret containing:
  - OPENAI_API_KEY
  - USER_NAME
  - PASSWORD
  - LICENSE_KEY
  - AUTH_SECRET

### IAM
- ECS Task Execution Role (ECR, Logs, Secrets Manager)
- ECS Task Role (S3, Textract, Transcribe, Translate, Polly, Comprehend, STS)

### Compute
- ECS Cluster with Container Insights
- ECS Task Definition (Fargate)
- ECS Service with deployment circuit breaker
- Application Auto Scaling (CPU and Memory based)

### Load Balancing
- Application Load Balancer
- Frontend Target Group (port 3000)
- Backend Target Group (port 5000)
- HTTP Listener (redirects to HTTPS if certificate provided)
- HTTPS Listener (optional, if certificate provided)
- Listener Rules for /api/* routing

### Monitoring
- CloudWatch Log Group (30-day retention)

## Updating Secrets

After deployment, you can update secrets in AWS Secrets Manager:

1. Go to AWS Secrets Manager in the console
2. Find the secret: `{AppName}-{Environment}-secrets`
3. Click "Retrieve secret value" then "Edit"
4. Update the JSON values
5. Click "Save"

The application can refresh secrets without restart using the `/api/license/refresh` endpoint.

## Updating the Application

To update the container image:

```bash
# Update task definition with new image
aws ecs update-service \
  --cluster language-services-production-cluster \
  --service language-services-production-service \
  --force-new-deployment
```

## Costs Estimate

Monthly costs (us-east-1, 2 tasks):

| Resource | Estimated Cost |
|----------|----------------|
| NAT Gateway | ~$32 |
| ALB | ~$16 |
| Fargate (2 x 1vCPU, 2GB) | ~$60 |
| S3 | Variable (based on usage) |
| Secrets Manager | ~$0.40 |
| CloudWatch Logs | Variable |
| **Total** | **~$110/month base** |

## Troubleshooting

### Check ECS Service Events
```bash
aws ecs describe-services \
  --cluster language-services-production-cluster \
  --services language-services-production-service \
  --query 'services[0].events[:10]'
```

### Check Task Logs
```bash
aws logs tail /ecs/language-services-production --follow
```

### Check Task Status
```bash
aws ecs list-tasks \
  --cluster language-services-production-cluster \
  --service-name language-services-production-service

aws ecs describe-tasks \
  --cluster language-services-production-cluster \
  --tasks <task-arn>
```

## Cleanup

To delete all resources:

```bash
# Delete the CloudFormation stack
aws cloudformation delete-stack --stack-name language-services-production

# Note: S3 buckets are retained by default. Delete manually if needed.
```

## Support

For issues with:
- **License activation**: Contact support@businesscompassllc.com
- **AWS deployment**: Check CloudWatch Logs and ECS events
- **Application bugs**: Submit an issue on GitHub
