"""Utility script to convert targets.ini to flash_profiles.json.

This script reads the legacy targets.ini file and creates a properly
structured JSON configuration file for the new profile system.
"""
from pathlib import Path
import sys

# Add parent directory to path to import pydownloadfwviasrio
sys.path.insert(0, str(Path(__file__).parent.parent))

from pydownloadfwviasrio.profiles import initialize_from_targets_ini


def main() -> None:
    """Convert targets.ini to flash_profiles.json."""
    ini_path = Path("_OLD/Vecchia_app/FpgaBeamMeUp/targets.ini")
    json_path = Path("flash_profiles.json")
    
    if not ini_path.exists():
        print(f"Error: {ini_path} not found!")
        return
    
    print(f"Reading configuration from {ini_path}...")
    manager = initialize_from_targets_ini(ini_path, json_path)
    
    print(f"\nConfiguration loaded successfully!")
    print(f"- Global IP: {manager.global_config.ip}:{manager.global_config.port}")
    print(f"- Default target: {manager.global_config.default_target}")
    print(f"- Models loaded: {len(manager.models)}")
    print(f"- Targets loaded: {len(manager.targets)}")
    
    print(f"\nModels:")
    for id_model, model in sorted(manager.models.items()):
        print(f"  [{id_model}] {model.model}: {model.description}")
        print(f"      Sectors: {model.num_sectors}, 4-byte addr: {model.is_4byte_addressing}")
        print(f"      Golden: 0x{model.golden_start:08X} - 0x{model.golden_stop:08X}")
        print(f"      User:   0x{model.user_start:08X} - 0x{model.user_stop:08X}")
    
    print(f"\nTargets:")
    for id_target, target in sorted(manager.targets.items()):
        model = manager.get_model(target.id_model)
        model_name = model.model if model else "UNKNOWN"
        print(f"  {target.id_target}: {target.description}")
        print(f"      Slot: 0x{target.slot_address:02X}, Arch: {target.architecture}, Model: {model_name}")
    
    print(f"\nConfiguration saved to {json_path}")


if __name__ == "__main__":
    main()
