# TekDek Command Center - Deployment Guide

**For**: Hephaestus, Operations Manager  
**Version**: 1.0.0  
**Status**: Ready for Production  

---

## Quick Deployment (5 Minutes)

### Option 1: Local Development

```bash
# 1. Navigate to ui directory
cd command-center/ui

# 2. Start local HTTP server
python3 -m http.server 8000

# 3. Open browser
open http://localhost:8000

# 4. Configure API URL (if needed)
# Edit api.js and change baseURL
```

### Option 2: GitHub Pages (Fastest)

```bash
# 1. Create GitHub repo
# 2. Push ui/ directory to gh-pages branch
# 3. Enable Pages in Settings
# 4. Set custom domain (optional)
# 5. Update api.js with production API URL
```

### Option 3: Docker

```bash
# 1. Create Dockerfile
cat > ui/Dockerfile << 'EOF'
FROM nginx:alpine
COPY . /usr/share/nginx/html/
EXPOSE 80
EOF

# 2. Build image
docker build -t tekdek-command-center:latest ui/

# 3. Run container
docker run -p 80:80 tekdek-command-center:latest

# 4. Visit http://localhost
```

### Option 4: AWS S3 + CloudFront

```bash
# 1. Create S3 bucket
aws s3 mb s3://tekdek-command-center

# 2. Upload files
aws s3 sync ui/ s3://tekdek-command-center --acl public-read

# 3. Create CloudFront distribution
# 4. Point domain to CloudFront
# 5. Enable HTTPS (auto via CloudFront)
```

---

## Pre-Deployment Checklist

Before going live, verify:

- [ ] **API URL** — Correct in `api.js` or environment
- [ ] **Backend API** — Running and accessible
- [ ] **CORS Headers** — Backend allows requests from UI domain
- [ ] **SSL/TLS** — If API is HTTPS, UI must be HTTPS
- [ ] **Browser Cache** — Clear before testing
- [ ] **Error Messages** — Check console for any errors
- [ ] **Mobile Testing** — Test on iOS and Android
- [ ] **Performance** — Lighthouse score 90+

### Verify Backend Connectivity

```bash
# Test API directly
curl http://localhost:3000/api/v1/projects

# Should return
# {
#   "status": "success",
#   "data": [...],
#   "meta": {...}
# }
```

---

## Environment Setup

### Development (localhost)

```javascript
// api.js - Default (no changes needed)
const api = new APIClient('http://localhost:3000/api/v1');
```

### Staging

```javascript
// api.js
const api = new APIClient('https://staging-api.tekdek.dev/api/v1');
```

### Production

```javascript
// api.js
const api = new APIClient('https://api.tekdek.dev/api/v1');
```

---

## CORS Configuration

If backend and frontend are on different domains, backend must allow:

```javascript
// Node.js/Express backend
const cors = require('cors');
app.use(cors({
    origin: ['https://command-center.tekdek.dev'],
    credentials: true
}));
```

**Backend Already Has This**: Talos implemented it ✅

---

## HTTPS Setup

### Let's Encrypt (Free)

```bash
# Using Certbot with nginx
sudo certbot certonly --nginx -d command-center.tekdek.dev

# Automatically renews every 90 days
```

### Self-Signed (Development Only)

```bash
# Create certificate
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365

# Configure nginx to use it
```

### CloudFront/Netlify (Automatic)

- ✅ Free SSL certificate
- ✅ Auto-renewal
- ✅ No configuration needed

---

## Server Configuration

### Nginx

```nginx
server {
    listen 80;
    server_name command-center.tekdek.dev;

    # Redirect HTTP to HTTPS
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name command-center.tekdek.dev;

    ssl_certificate /etc/letsencrypt/live/command-center.tekdek.dev/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/command-center.tekdek.dev/privkey.pem;

    root /usr/share/nginx/html;

    # Serve index.html for all routes (SPA)
    location / {
        try_files $uri $uri/ /index.html;
    }

    # Cache static files
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    # Compression
    gzip on;
    gzip_types text/plain text/css application/javascript;
    gzip_min_length 1000;
}
```

### Apache

```apache
<VirtualHost *:80>
    ServerName command-center.tekdek.dev
    Redirect 301 / https://command-center.tekdek.dev/
</VirtualHost>

<VirtualHost *:443>
    ServerName command-center.tekdek.dev
    DocumentRoot /var/www/tekdek-command-center

    SSLEngine on
    SSLCertificateFile /etc/letsencrypt/live/command-center.tekdek.dev/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/command-center.tekdek.dev/privkey.pem

    # SPA routing
    <Directory /var/www/tekdek-command-center>
        RewriteEngine On
        RewriteBase /
        RewriteRule ^index\.html$ - [L]
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule . /index.html [L]
    </Directory>

    # Caching
    <FilesMatch "\.(jpg|jpeg|png|gif|js|css|svg|ico)$">
        Header set Cache-Control "max-age=31536000, public"
    </FilesMatch>

    # Compression
    <IfModule mod_deflate.c>
        AddOutputFilterByType DEFLATE text/plain
        AddOutputFilterByType DEFLATE text/html
        AddOutputFilterByType DEFLATE text/xml
        AddOutputFilterByType DEFLATE text/css
        AddOutputFilterByType DEFLATE application/xml
        AddOutputFilterByType DEFLATE application/xhtml+xml
        AddOutputFilterByType DEFLATE application/rss+xml
        AddOutputFilterByType DEFLATE application/javascript
        AddOutputFilterByType DEFLATE application/x-javascript
    </IfModule>
</VirtualHost>
```

---

## Performance Optimization

### Enable Gzip Compression

Reduces file sizes by 60-80%:

```nginx
gzip on;
gzip_types text/plain text/css application/javascript text/xml application/xml;
gzip_min_length 1000;
gzip_vary on;
```

### Enable Browser Caching

```nginx
# Cache for 1 year (versioning handled by build)
location ~* \.(js|css|png|jpg|jpeg|gif|svg|ico|woff|woff2|ttf|eot)$ {
    expires 1y;
    add_header Cache-Control "public, immutable";
}
```

### Use CDN (Optional)

```javascript
// Use CDN URLs in index.html
<script src="https://cdn.tekdek.dev/ui/app.js"></script>
```

---

## Monitoring & Health Checks

### Health Check Endpoint

Add to `index.html` or API:

```bash
curl https://command-center.tekdek.dev/api/health
# Returns 200 OK if healthy
```

### Uptime Monitoring

```bash
# Using curl in cron
0 */5 * * * curl -f https://command-center.tekdek.dev || send_alert
```

### Browser Console Errors

Monitor JavaScript errors:

```javascript
// Send errors to monitoring service
window.addEventListener('error', (event) => {
    fetch('https://errors.tekdek.dev/report', {
        method: 'POST',
        body: JSON.stringify({
            message: event.message,
            url: event.filename,
            line: event.lineno
        })
    });
});
```

---

## Rollback Procedure

### If Something Goes Wrong

```bash
# 1. Revert to previous version
git revert <commit-hash>
git push

# 2. Clear CDN cache
aws cloudfront create-invalidation --distribution-id E123ABC456 --paths "/*"

# 3. Check logs
tail -f /var/log/nginx/error.log

# 4. Notify team
# Message: "Rolled back to previous version due to [reason]"
```

---

## Troubleshooting

### Users See 404

**Solution**: Configure web server for SPA routing
```nginx
try_files $uri $uri/ /index.html;
```

### API Calls Failing (CORS Error)

**Solution**: Check backend CORS headers
```bash
curl -H "Origin: https://command-center.tekdek.dev" \
     -H "Access-Control-Request-Method: GET" \
     -X OPTIONS https://api.tekdek.dev/api/v1/projects -v
```

### Slow Performance

**Solutions**:
1. Enable gzip compression
2. Enable browser caching
3. Use CDN
4. Check API response times
5. Check Lighthouse scores

### SSL Certificate Issues

**Solutions**:
```bash
# Check certificate validity
openssl x509 -in cert.pem -text -noout

# Check certificate dates
echo | openssl s_client -servername command-center.tekdek.dev -connect command-center.tekdek.dev:443 2>/dev/null | openssl x509 -noout -dates
```

---

## Deployment Checklist

### Day Before Launch

- [ ] Final code review
- [ ] All tests passing
- [ ] API connectivity verified
- [ ] SSL certificate ready
- [ ] Domain DNS updated
- [ ] Staging environment deployed
- [ ] Test all user workflows
- [ ] Check mobile responsiveness

### Day of Launch

- [ ] Team on standby
- [ ] Monitoring systems active
- [ ] Rollback procedure ready
- [ ] Backup of previous version made
- [ ] Deploy to production
- [ ] Verify all features working
- [ ] Monitor error logs
- [ ] Check analytics
- [ ] Notify users/stakeholders

### After Launch

- [ ] Monitor for 24 hours
- [ ] Check error rates
- [ ] Monitor performance metrics
- [ ] Gather user feedback
- [ ] Plan phase 2 features
- [ ] Document lessons learned

---

## Scaling Considerations

### If Traffic Increases

**CDN Option** (Recommended):
- Use Cloudflare, CloudFront, or Akamai
- Dramatically speeds up for global users
- Handles traffic spikes automatically

**Multi-Region**:
- Deploy to multiple regions
- Use geofencing to route users
- Reduces latency for international users

**API Caching**:
- Add Redis cache in front of API
- Cache project list (5 min TTL)
- Reduces database load

---

## Security Checklist

- [ ] HTTPS enabled (no HTTP)
- [ ] Headers configured:
  - `X-Content-Type-Options: nosniff`
  - `X-Frame-Options: DENY`
  - `X-XSS-Protection: 1; mode=block`
- [ ] CORS properly configured
- [ ] API authentication ready (for phase 2)
- [ ] Secrets not in code (use .env)
- [ ] Rate limiting configured on backend
- [ ] SQL injection prevented (via ORM/prepared statements)

---

## Disaster Recovery

### If Backend Goes Down

```bash
# 1. Check backend logs
ssh backend-server
tail -f /var/log/application.log

# 2. Restart backend
sudo systemctl restart tekdek-api

# 3. Check database
psql -U tekdek -d tekdek_command_center
SELECT COUNT(*) FROM projects;

# 4. Restore from backup if needed
```

### If Database Is Corrupted

```bash
# 1. Restore from latest backup
sudo systemctl stop tekdek-api
pg_restore -d tekdek_command_center /backups/latest.sql
sudo systemctl start tekdek-api

# 2. Verify data
psql -U tekdek -d tekdek_command_center -c "SELECT COUNT(*) FROM projects;"

# 3. Notify team
```

---

## Post-Deployment Tasks

1. **Update Documentation**
   - Add live URL to README
   - Update API endpoint references
   - Document any customizations

2. **Setup Monitoring**
   - Configure error tracking
   - Setup performance monitoring
   - Enable uptime checks

3. **Analytics**
   - Setup Google Analytics
   - Track user behavior
   - Monitor feature usage

4. **Backup Strategy**
   - Daily backups of database
   - Weekly backups of code
   - Test restore procedure monthly

5. **Planning**
   - Schedule phase 2 planning
   - Gather user feedback
   - Identify improvements

---

## Support & Operations

### Daily Tasks
- [ ] Check error logs
- [ ] Monitor performance
- [ ] Verify uptime

### Weekly Tasks
- [ ] Review analytics
- [ ] Check SSL certificate expiry
- [ ] Test backup/restore
- [ ] Review user feedback

### Monthly Tasks
- [ ] Update dependencies
- [ ] Security audit
- [ ] Performance tuning
- [ ] Capacity planning

---

## Contact Info

- **Frontend**: Icarus (Frontend Designer)
- **Backend**: Talos (Technical Coder)
- **Operations**: Hephaestus (Operations Manager)
- **Architecture**: Daedalus (Architect)

---

**✅ READY FOR PRODUCTION DEPLOYMENT**

Questions? Check the troubleshooting section above or contact the TekDek team.
