# Asset URL Updater Guide

## Overview

The `update_asset_urls.py` script automatically replaces old Discord/Midjourney URLs in your Python code with new AI-generated image URLs from the database.

## What It Updates

### education_manager.py
- **6 Elementary Schools** (lines 253-258)
  - Maple Elementary School
  - Eagle Private Academy
  - Greenwood Elementary
  - Bright Stars School
  - Lakeview Elementary
  - Grand Oak Elementary

- **6 High Schools** (lines 261-266)
  - Valley High School
  - Prestige Prep School
  - Northview High
  - Academic Excellence Institute
  - Harmony High
  - Mountain Ridge High

- **10 Colleges** (lines 293-302)
  - University of Science
  - Artistic Minds University
  - Eastern Commerce College
  - Law and Governance University
  - Institute of Tech Innovation
  - Liberal Arts Academy
  - Northern Agriculture College
  - Health and Medicine University
  - Oceanography Institute
  - Performing Arts School

### shop_manager.py
- **Shop Items** (lines 62-90)
  - Sports Car
  - Designer Suit
  - Artisan Coffee Machine
  - Designer Handbag
  - Diamond Ring
  - Rare Wine
  - Limited Edition Sneakers
  - Designer Sunglasses
  - Luxury Fragrance

- **Diamond Packs** (lines 167, 181-182)
  - Default diamond image
  - Diamond Pack 1
  - Diamond Pack 2

## Prerequisites

1. **Generate all game assets** using `generate_game_assets.py`:
   ```bash
   python generate_game_assets.py --all
   ```
   This creates 73 images in the database (IDs 48-120).

2. **Verify images in database**:
   ```sql
   SELECT COUNT(*) FROM generated_images WHERE event_category IN ('education_elementary', 'education_high_school', 'education_college', 'shop_item');
   ```
   Should return 73 images.

## Usage

### Step 1: Preview Changes (Recommended)
Preview what will be changed without modifying files:

```bash
cd ws
python update_asset_urls.py --preview
```

**Example Output:**
```
2025-11-13 - INFO - Fetching generated image URLs from database...
2025-11-13 - INFO - Found 6 elementary school images
2025-11-13 - INFO - Found 6 high school images
2025-11-13 - INFO - Found 10 college images
2025-11-13 - INFO - Found 11 shop item images

PREVIEW - education_manager.py changes:
  Elementary school 1: https://cdn.discordapp.com/... → https://fal.ai/...
  Elementary school 2: https://cdn.discordapp.com/... → https://fal.ai/...
  ...
  High school 1: https://cdn.midjourney.com/... → https://fal.ai/...
  ...
  College 1: https://cdn.discordapp.com/... → https://fal.ai/...
  ...

Total changes: 22

PREVIEW - shop_manager.py changes:
  Sports Car: https://cdn.discordapp.com/... → https://fal.ai/...
  ...

Total changes: 11

======================================================================
PREVIEW MODE - No files were changed
Total changes that would be made: 33
To apply changes, run:
  python update_asset_urls.py --update --backup
======================================================================
```

### Step 2: Apply Changes with Backup
Update the files with automatic backup:

```bash
python update_asset_urls.py --update --backup
```

**What happens:**
1. Creates backup files with timestamp:
   - `education_manager.py.backup_20251113_143052`
   - `shop_manager.py.backup_20251113_143052`

2. Updates files with new URLs

3. Shows summary of changes made

**Example Output:**
```
✓ Created backup: education/education_manager.py.backup_20251113_143052
✓ Created backup: shop/shop_manager.py.backup_20251113_143052
✓ Updated education/education_manager.py with 22 changes
✓ Updated shop/shop_manager.py with 11 changes

======================================================================
UPDATE COMPLETE
Total changes made: 33
  education_manager.py: 22 URLs updated
  shop_manager.py: 11 URLs updated
======================================================================
```

## How It Works

### Database Queries
The script queries the `generated_images` table:

```sql
-- Elementary schools
SELECT event_type, image_url
FROM generated_images
WHERE event_category = 'education_elementary'
ORDER BY id;

-- High schools
SELECT event_type, image_url
FROM generated_images
WHERE event_category = 'education_high_school'
ORDER BY id;

-- Colleges
SELECT event_type, image_url
FROM generated_images
WHERE event_category = 'education_college'
ORDER BY id;

-- Shop items (mapped by event_type)
SELECT event_type, image_url
FROM generated_images
WHERE event_category = 'shop_item'
ORDER BY id;
```

### URL Pattern Matching
Uses regex to find and replace URLs:

```python
# Elementary schools
elementary_pattern = r"elementary_schools\.append\(ElementarySchoolClass\([^)]+,\s*'(https://[^']+)'\)\)"

# High schools
high_school_pattern = r"high_schools\.append\(HighSchoolClass\([^)]+,\s*'(https://[^']+)'\)\)"

# Colleges
college_pattern = r"colleges\.append\(CollegeClass\([^)]+,\s*'(https://[^']+)'\)\)"

# Shop items
store_item_pattern = r'StoreItem\("([^"]+)",\s*\d+,\s*"[^"]+",\s*\d+,\s*"([^"]+)"\)'
```

These patterns match **both Discord and Midjourney CDN URLs**.

### Shop Item Mapping
Shop items are matched by name to event_type:

```python
item_mappings = {
    "Sports Car": "sports_car",
    "Designer Suit": "designer_suit",
    "Artisan Coffee Machine": "coffee_machine",
    "Designer Handbag": "handbag",
    "Diamond Ring": "diamond_ring",
    "Rare Wine": "rare_wine",
    "Limited Edition Sneakers": "sneakers",
    "Designer Sunglasses": "sunglasses",
    "Luxury Fragrance": "perfume",
}
```

## Troubleshooting

### "Mismatch: Found X schools in code, but Y URLs"
**Cause**: Number of schools in code doesn't match database entries

**Fix**:
1. Check database has correct number of images:
   ```sql
   SELECT event_category, COUNT(*) FROM generated_images GROUP BY event_category;
   ```
2. Verify `generate_game_assets.py` generated all images successfully
3. Run `--preview` to see which schools are missing

### "No mapping found for item: [Item Name]"
**Cause**: Shop item name doesn't have a mapping in `item_mappings`

**Fix**:
1. Add missing mapping to `update_asset_urls.py`:
   ```python
   item_mappings = {
       "Case of Energy Drinks": "energy_drinks",
       # Add your new item here
       "New Item Name": "new_item_event_type",
   }
   ```
2. Ensure `generate_game_assets.py` has matching event_type

### "Can't connect to MySQL server"
**Cause**: MySQL database is not running

**Fix**:
```bash
sudo service mysql start
# or on macOS
brew services start mysql
```

### Changes didn't apply
**Cause**: Script ran in preview mode (default)

**Fix**: Use `--update` flag:
```bash
python update_asset_urls.py --update --backup
```

## Restoring from Backup

If you need to revert changes:

```bash
cd ws/education
cp education_manager.py.backup_20251113_143052 education_manager.py

cd ../shop
cp shop_manager.py.backup_20251113_143052 shop_manager.py
```

## Verification

After updating, verify the changes:

1. **Check files were modified**:
   ```bash
   git diff education/education_manager.py
   git diff shop/shop_manager.py
   ```

2. **Search for old URLs**:
   ```bash
   grep -r "cdn.discordapp.com" education/
   grep -r "cdn.midjourney.com" education/
   grep -r "cdn.discordapp.com" shop/
   ```
   Should return no results (or only in backup files).

3. **Test the game**:
   - Start the server: `./startServer.sh`
   - Create a new game
   - Verify images load correctly in events
   - Check school selection screen
   - Check shop items

## Command Reference

```bash
# Preview only (default)
python update_asset_urls.py
python update_asset_urls.py --preview

# Update without backup
python update_asset_urls.py --update

# Update with backup (recommended)
python update_asset_urls.py --update --backup
```

## Integration with Workflow

Complete workflow for updating all game assets:

```bash
# 1. Generate all game asset images (one-time)
cd ws
python generate_game_assets.py --all
# Wait ~17 minutes for 73 images

# 2. Preview URL updates
python update_asset_urls.py --preview

# 3. Apply updates with backup
python update_asset_urls.py --update --backup

# 4. Verify changes
git diff education/education_manager.py
git diff shop/shop_manager.py

# 5. Test in game
./startServer.sh

# 6. Commit changes if all looks good
git add education/education_manager.py shop/shop_manager.py
git commit -m "feat: Replace Discord/Midjourney URLs with AI-generated image URLs"
git push
```

## Related Files

- `generate_game_assets.py` - Generates the images
- `IMAGE_GENERATION_GUIDE.md` - Complete image generation system documentation
- `pregenerate_images.py` - Generates general event images (60+ images)
- `image_generation.py` - Core image generation module

## Database Schema

```sql
CREATE TABLE generated_images (
    id INT AUTO_INCREMENT PRIMARY KEY,
    image_url VARCHAR(500) NOT NULL,
    prompt TEXT,
    event_type VARCHAR(100),
    event_category VARCHAR(50),
    provider ENUM('imagen4', 'flux', 'dalle3', 'manual') DEFAULT 'imagen4',
    generation_cost DECIMAL(10,4) DEFAULT 0.00,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    is_active BOOLEAN DEFAULT TRUE
);
```

## Cost Summary

If you regenerated all 73 images with Google Imagen 4 Ultra:
- Estimated cost: ~$7-15 (varies by fal.ai pricing)
- Generation time: ~17 minutes
- One-time cost for permanent asset URLs

## Notes

- **Order matters**: Schools must be in the same order in database (ORDER BY id) as they appear in the Python files
- **Backup files**: Automatically created with timestamp, can accumulate over time
- **Safe operation**: Always use `--preview` first before `--update`
- **URL format**: Works with Discord, Midjourney CDN, and fal.ai URLs
- **Case sensitive**: Shop item names must match exactly
