import json
import os
from robot_tools.database import DatabaseManager


def migrate_json_to_db():
    json_path = os.path.join(os.path.dirname(__file__), '..', 'zmq_monitor', 'publishers.json')
    
    if not os.path.exists(json_path):
        print("No publishers.json found. Nothing to migrate.")
        return
    
    with open(json_path, 'r') as f:
        publishers = json.load(f)
    
    if not publishers:
        print("publishers.json is empty. Nothing to migrate.")
        return
    
    db = DatabaseManager()
    migrated = 0
    skipped = 0
    
    print("Migrating publishers from JSON to SQLite database...\n")
    
    for name, info in publishers.items():
        port = info.get('port')
        host = info.get('host', 'localhost')
        description = info.get('description', '')
        
        if db.add_publisher(name, port, host, description):
            print(f"✓ Migrated: {name} -> {host}:{port}")
            migrated += 1
        else:
            print(f"✗ Skipped (already exists): {name}")
            skipped += 1
    
    print(f"\nMigration complete: {migrated} migrated, {skipped} skipped")
    print(f"\nBackup your publishers.json and remove it manually if desired.")


if __name__ == "__main__":
    migrate_json_to_db()
