"""
Database Migration: Standardize device_type values

This migration ensures all device_type values follow the official schema:
- "seismograph" - Seismic monitoring devices
- "modem" - Field modems and network equipment
- "slm" - Sound level meters (NL-43/NL-53)

Changes:
- Converts "sound_level_meter" → "slm"
- Safe to run multiple times (idempotent)
- No data loss

Usage:
    python backend/migrate_standardize_device_types.py
"""

import sys
import os

# Add parent directory to path so we can import backend modules
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker

# Database configuration
SQLALCHEMY_DATABASE_URL = "sqlite:///./data/seismo_fleet.db"
engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)


def migrate():
    """Standardize device_type values in the database"""
    db = SessionLocal()

    try:
        print("=" * 70)
        print("Database Migration: Standardize device_type values")
        print("=" * 70)
        print()

        # Check for existing "sound_level_meter" values
        result = db.execute(
            text("SELECT COUNT(*) as count FROM roster WHERE device_type = 'sound_level_meter'")
        ).fetchone()

        count_to_migrate = result[0] if result else 0

        if count_to_migrate == 0:
            print("✓ No records need migration - all device_type values are already standardized")
            print()
            print("Current device_type distribution:")

            # Show distribution
            distribution = db.execute(
                text("SELECT device_type, COUNT(*) as count FROM roster GROUP BY device_type ORDER BY count DESC")
            ).fetchall()

            for row in distribution:
                device_type, count = row
                print(f"  - {device_type}: {count} units")

            print()
            print("Migration not needed.")
            return

        print(f"Found {count_to_migrate} record(s) with device_type='sound_level_meter'")
        print()
        print("Converting 'sound_level_meter' → 'slm'...")

        # Perform the migration
        db.execute(
            text("UPDATE roster SET device_type = 'slm' WHERE device_type = 'sound_level_meter'")
        )
        db.commit()

        print(f"✓ Successfully migrated {count_to_migrate} record(s)")
        print()

        # Show final distribution
        print("Updated device_type distribution:")
        distribution = db.execute(
            text("SELECT device_type, COUNT(*) as count FROM roster GROUP BY device_type ORDER BY count DESC")
        ).fetchall()

        for row in distribution:
            device_type, count = row
            print(f"  - {device_type}: {count} units")

        print()
        print("=" * 70)
        print("Migration completed successfully!")
        print("=" * 70)

    except Exception as e:
        db.rollback()
        print(f"\n❌ Error during migration: {e}")
        print("\nRolling back changes...")
        raise
    finally:
        db.close()


if __name__ == "__main__":
    migrate()
