# Migration Guide: File-Based to Database Storage

## Overview

This guide covers the transition from file-based series metadata storage to the new database-backed system introduced in v2.0.

## What Changed

**Before v2.0**: Series metadata stored in `key` and `data` files alongside anime folders.

**After v2.0**: All metadata stored in SQLite database (`aniworld.db`). Files are deprecated but still supported for backward compatibility during migration.

## Automated Migration

The application automatically migrates on first startup:

1. Scans anime directory for `key` and `data` files
2. Parses legacy files into `AnimeSeries` and `Episode` records
3. Loads series into in-memory cache
4. Logs migration results

**No manual action required.**

## Manual Verification

After first startup with the new version:

1. **Check logs** for: `"Migrated X series from files to DB"`
2. **Verify series count**: UI shows same number of series as before
3. **Confirm episodes**: Episode counts match expected totals

```bash
# Check migration log
grep "Migrated" logs/app.log

# Verify series via API
curl http://localhost:8000/api/anime | jq '.total'
```

## After Migration

### Safe to Delete

Once verified, these files can be removed:

```
<anime_folder>/
├── Attack on Titan (2013)/
│   ├── key     # ❌ Can delete
│   ├── data    # ❌ Can delete
│   └── Season 1/
│       └── ...
```

**Deleting these files does not affect the database.** The metadata now lives in `aniworld.db`.

### Backup (Recommended)

Before deleting, backup the files:

```bash
# Create backup directory
mkdir -p backup/legacy_series_files

# Copy all key and data files
find /path/to/anime -name "key" -o -name "data" | while read f; do
    cp "$f" "backup/legacy_series_files/"
done
```

## Reverting (Not Recommended)

If you must revert to file-based storage:

1. **Restore from database backup** (if available)
2. **Export manually** (no export script exists)

**Warning**: File-based storage is deprecated and will be removed in v3.0.0.

## Troubleshooting

### Series Not Appearing After Migration

1. Check logs for migration errors: `grep -i error logs/app.log`
2. Verify `key` and `data` files exist and are readable
3. Manually trigger rescan: `POST /api/scheduler/trigger-rescan`

### Duplicate Series

1. Check for duplicate `key` files (same series in multiple folders)
2. Verify series key uniqueness in database:

```bash
sqlite3 aniworld.db "SELECT key, COUNT(*) FROM anime_series GROUP BY key HAVING COUNT(*) > 1;"
```

### Missing Episodes

1. Trigger targeted scan for affected series
2. Check episode sync logs
3. Verify file permissions on anime directory

## Deprecation Timeline

| Version | Status |
|---------|--------|
| v2.0.x  | Legacy files supported, migration automated |
| v2.1.x  | Legacy files still supported, warnings in logs |
| v3.0.0  | **Legacy files removed** - database only |

Upgrade to v3.0.0 before legacy file support ends.