import json
import uuid
import os

DATA_FILE = 'db/hardware/test_equipment_data.json'
BACKUP_FILE = 'db/hardware/test_equipment_data_pre_uuid.json'


def migrate():
    if not os.path.exists(DATA_FILE): return print("Keine Datei.")

    with open(DATA_FILE, 'r', encoding='utf-8') as f:
        data = json.load(f)

    # Check ob schon migriert (einfacher Check: sind Keys lang?)
    first_key = next(iter(data.get('boms', {})), None)
    if first_key and len(first_key) > 30 and '-' in first_key:
        print("Sieht schon migriert aus. Abbruch.")
        return

    # Backup
    import shutil
    shutil.copy(DATA_FILE, BACKUP_FILE)
    print("Backup erstellt.")

    old_boms = data.get('boms', {})
    new_boms = {}
    name_to_uuid = {}

    # 1. BOMs umwandeln
    for name, bom_data in old_boms.items():
        new_id = str(uuid.uuid4())
        new_boms[new_id] = {
            "name": name,
            "items": bom_data.get('items', []),
            "status": bom_data.get('status', 'missing')
        }
        name_to_uuid[name] = new_id

    data['boms'] = new_boms

    # 2. Mappings aktualisieren
    mappings = data.get('mappings', {})
    for engine, kits in mappings.items():
        new_list = []
        for kit_name in kits:
            if kit_name in name_to_uuid:
                new_list.append(name_to_uuid[kit_name])
            else:
                print(f"Warnung: Kit '{kit_name}' im Mapping, aber nicht in BOMs. Wird entfernt.")
        mappings[engine] = new_list

    # 3. Inventar aktualisieren
    inventory = data.get('inventory', {})
    for pn, part in inventory.items():
        for s in part.get('serials', []):
            old_kit = s.get('kitId', 'N/A')
            if old_kit in name_to_uuid:
                s['kitId'] = name_to_uuid[old_kit]
            else:
                s['kitId'] = 'N/A'

    with open(DATA_FILE, 'w', encoding='utf-8') as f:
        json.dump(data, f, indent=2)

    print("Migration erfolgreich.")


if __name__ == '__main__':
    migrate()