# Production Deployment Guide

## Overview

This guide covers deploying the production launch with:
- Token & payment system
- Open access (no whitelist)
- 1000 token bonus for original whitelist users
- YooKassa TEST payment for moderation review

## Pre-requisites

✅ All changes committed and pushed (commit `cb2e18b`)
✅ Prod .env updated with:
- `BUILD_SOURCE=prod`
- `ALLOWED_USERS=` (empty - open to everyone)
- `PAYMENT_PROVIDER_TOKEN=YOUR_PAYMENT_PROVIDER_TOKEN` (TEST token for YooKassa review)
- `POLLO_KEY` configured
- `WEBHOOK_URL` configured

## Deployment Steps

### 1. Pull Latest Code to Prod

```bash
cd /home/videobot/prod
git pull origin main
```

**Expected**: Should pull commit `cb2e18b` with 31 files changed

### 2. Update Python Dependencies

```bash
cd /home/videobot/prod
source venv/bin/activate
pip install -r viewer/requirements.txt  # New admin bot dependencies
```

**New dependencies**: None (all existing)

### 3. Update Prod .env

The prod .env file is NOT in git (it's in .gitignore), so we need to update it manually.

**Critical changes needed:**

```bash
# Edit /home/videobot/prod/.env
nano /home/videobot/prod/.env
```

Add these lines (if not already there):

```ini
BUILD_SOURCE=prod
PAYMENT_PROVIDER_TOKEN=YOUR_PAYMENT_PROVIDER_TOKEN
```

Update this line:

```ini
# Change from:
ALLOWED_USERS=100000001,100000002,100000003,100000004,100000005,100000006,100000007,100000008,100000009,100000010

# To:
ALLOWED_USERS=
```

**Verify final .env has:**
- ✅ `BUILD_SOURCE=prod`
- ✅ `ALLOWED_USERS=` (empty)
- ✅ `PAYMENT_PROVIDER_TOKEN=YOUR_PAYMENT_PROVIDER_TOKEN`
- ✅ `POLLO_KEY=pollo_YOUR_KEY_HERE`
- ✅ `WEBHOOK_URL=https://your-server.example.com/webhook/prod`

### 4. Run Database Migration

Grant 1000 tokens to original whitelist users:

```bash
cd /home/videobot/prod/scripts
source ../venv/bin/activate

# Dry-run first (verify)
python migrate_prod_launch.py --source prod

# Actually execute
python migrate_prod_launch.py --source prod --execute
```

**Expected output:**
```
✅ Migration complete!
   Total granted: 10000 tokens to 10 users
```

**Verify migration worked:**
```bash
cd /home/videobot/prod/scripts
python -c "
import sys
sys.path.insert(0, '.')
from token_manager import get_balance
from database import get_db_path
import os
os.environ['BUILD_SOURCE'] = 'prod'

# Check first user
balance = get_balance(100000001)
print(f'User 100000001 balance: {balance}')
assert balance == 1000, f'Expected 1000, got {balance}'
print('✅ Migration verified!')
"
```

### 5. Restart Production Bot

```bash
sudo systemctl restart videobot-prod
sudo systemctl status videobot-prod
```

**Verify startup:**
```bash
sudo journalctl -u videobot-prod -f
```

Look for:
- ✅ `Initializing database: /mnt/video/videobot_prod.db`
- ✅ `BUILD_SOURCE: prod` (or similar log)
- ✅ `ALLOWED_USERS: set()`
- ✅ `Webhook mode: https://your-server.example.com/webhook/prod`
- ✅ Bot started successfully

**Verify webhook is working:**
```bash
# Check bot is listening on port 8444
netstat -tlnp | grep 8444
# Should show: tcp 0 0 127.0.0.1:8444 ... LISTEN <pid>/python

# Check nginx proxy
curl -X POST http://127.0.0.1:8444/
# Should return: {"ok":false,"error_code":401,"description":"Unauthorized"}

# Check external webhook endpoint
curl -X POST https://your-server.example.com/webhook/prod
# Should return: {"ok":false,"error_code":401,"description":"Unauthorized"}
```

### 7. Test Basic Functionality

**Test 1: Access without whitelist**
- Have a new user (not in original whitelist) send `/start` to the bot
- Should work without "access denied" message

**Test 2: Token balance**
- Have an original whitelist user send `/balance`
- Should show: `💰 Ваш баланс: 1000 токенов`

**Test 3: Generate video**
- Send a Wildberries URL
- Should work and deduct 1 token

**Test 4: Payment (TEST mode)**
- Send `/buy`
- Try to purchase tokens
- Should show YooKassa test payment form

**Test 5: Portfolio**
- Send `/portfolio`
- Should show example videos (if any in showcase.db)

## YooKassa Moderation Process

**Current setup**: Using TEST payment token

**To submit for YooKassa moderation:**

1. Go to BotFather → Payments → YooKassa
2. Submit bot for moderation
3. YooKassa will test the bot using TEST payments
4. Once approved, they'll provide LIVE payment token

**After approval:**

```bash
# Update prod .env with LIVE token
nano /home/videobot/prod/.env

# Change:
PAYMENT_PROVIDER_TOKEN=YOUR_PAYMENT_PROVIDER_TOKEN
# To:
PAYMENT_PROVIDER_TOKEN=<LIVE_TOKEN_FROM_YOOKASSA>

# Restart bot
sudo systemctl restart videobot-prod
```

## Rollback Plan

If something goes wrong:

### Option 1: Quick rollback
```bash
cd /home/videobot/prod
git checkout 5021b22  # Previous commit
sudo systemctl restart videobot-prod
```

### Option 2: Re-enable whitelist
```bash
# Edit /home/videobot/prod/.env
nano /home/videobot/prod/.env

# Change:
ALLOWED_USERS=
# Back to:
ALLOWED_USERS=100000001,100000002,100000003,100000004,100000005,100000006,100000007,100000008,100000009,100000010

sudo systemctl restart videobot-prod
```

## Monitoring

**Watch logs:**
```bash
# Bot logs
sudo journalctl -u videobot-prod -f

# Pipeline logs (per-generation)
tail -f /mnt/video/wb_*/*/pipeline.log

# Activity logs (user actions)
tail -f /mnt/video/activity.log
```

**Check token stats:**
```bash
cd /home/videobot/prod/scripts
python -c "
import sys
sys.path.insert(0, '.')
from database import get_connection, get_db_path
import os
os.environ['BUILD_SOURCE'] = 'prod'

with get_connection() as conn:
    stats = conn.execute('''
        SELECT
            COUNT(*) as total_users,
            SUM(balance) as total_balance,
            SUM(total_purchased) as total_purchased,
            SUM(total_spent) as total_spent
        FROM users
    ''').fetchone()

    print(f'Users: {stats[0]}')
    print(f'Total balance: {stats[1]}')
    print(f'Total purchased: {stats[2]}')
    print(f'Total spent: {stats[3]}')
"
```

## Known Issues

1. **YooKassa TEST payments**: Users will see "Test Payment" in the payment form. This is expected until we get LIVE token.

2. **Database migration**: Can only run once. Running again will grant another 1000 tokens to the same users.

3. **Viewer bot**: Admin bot is separate - see [viewer/viewer_bot.py](../viewer/viewer_bot.py)

## Next Steps After Launch

1. **Monitor first 24 hours**: Watch for errors, payment issues, generation failures
2. **YooKassa submission**: Submit for moderation once bot is stable
3. **Promo slots**: Adjust promo slot count in `promo_config` table
4. **Showcase**: Add good examples to portfolio via admin bot
5. **Analytics**: Monitor token usage, popular products, conversion rates

## Support

**Git**: Use the project repository
**Issues**: Use git issues
