#!/usr/bin/env python3
"""
One-time script to sync existing SLM devices from Terra-View roster to SLMM cache.
Run this after implementing the automatic sync to backfill existing devices.
"""
import asyncio
import sys
import os

# Add parent directory to path for imports
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from backend.database import SessionLocal
from backend.models import RosterUnit
from backend.routers.roster_edit import sync_slm_to_slmm_cache
import logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)


async def sync_all_slms():
    """Sync all SLM devices from Terra-View roster to SLMM cache."""
    db = SessionLocal()
    try:
        # Get all SLM devices from Terra-View (source of truth)
        slm_devices = db.query(RosterUnit).filter_by(
            device_type="slm"
        ).all()

        logger.info(f"Found {len(slm_devices)} SLM devices in Terra-View roster")

        success_count = 0
        failed_count = 0

        for device in slm_devices:
            logger.info(f"\nProcessing: {device.id}")
            logger.info(f"  Host: {device.slm_host}")
            logger.info(f"  TCP Port: {device.slm_tcp_port}")
            logger.info(f"  Modem: {device.deployed_with_modem_id}")

            result = await sync_slm_to_slmm_cache(
                unit_id=device.id,
                host=device.slm_host,
                tcp_port=device.slm_tcp_port,
                ftp_port=device.slm_ftp_port,
                deployed_with_modem_id=device.deployed_with_modem_id,
                db=db
            )

            if result["success"]:
                logger.info(f"✓ {device.id}: {result['message']}")
                success_count += 1
            else:
                logger.error(f"✗ {device.id}: {result['message']}")
                failed_count += 1

        logger.info(f"\n{'='*60}")
        logger.info(f"Cache sync complete: {success_count} succeeded, {failed_count} failed")
        logger.info(f"{'='*60}")

    finally:
        db.close()


if __name__ == "__main__":
    asyncio.run(sync_all_slms())
