r"""
Migrate existing db.sqlite3 from project directory to %APPDATA%/TianXuan/.

This script is called during the first startup after the DB path change.
It preserves the old database and only copies if the new location is empty.

Usage:
    runtime\python\python.exe scripts\migrate_db_to_appdata.py
"""
import os
import sys
import shutil
from pathlib import Path


def migrate():
    project_dir = Path(__file__).resolve().parent.parent

    old_db = project_dir / 'db.sqlite3'
    old_wal = project_dir / 'db.sqlite3-wal'
    old_shm = project_dir / 'db.sqlite3-shm'

    appdata = Path(os.environ.get('APPDATA', str(Path.home() / '.tianxuan'))) / 'TianXuan'
    appdata.mkdir(parents=True, exist_ok=True)
    new_db = appdata / 'db.sqlite3'

    if new_db.exists():
        print(f"[SKIP] {new_db} already exists — migration already done or data present")
        return 0

    if not old_db.exists():
        print(f"[SKIP] No {old_db} to migrate — clean install or already migrated")
        return 0

    # Copy WAL and SHM files first (WAL must be flushed before main DB)
    for f in [old_wal, old_shm]:
        if f.exists():
            shutil.copy2(str(f), str(appdata / f.name))
            print(f"  Copied {f.name}")

    # Copy main database
    size_mb = old_db.stat().st_size / (1024 * 1024)
    print(f"Migrating {old_db.name} ({size_mb:.1f} MB) to {new_db}...")
    shutil.copy2(str(old_db), str(new_db))

    # Verify
    if new_db.exists() and new_db.stat().st_size > 0:
        print(f"[OK] Migration complete: {new_db}")
        print(f"[INFO] Old database preserved at: {old_db}")
        print(f"[INFO] You can safely delete the old file after verification")
        return 0
    else:
        print(f"[ERROR] Migration failed: {new_db} not created or empty", file=sys.stderr)
        return 1


if __name__ == '__main__':
    sys.exit(migrate())
