import os
import sys
import json
from pathlib import Path
from typing import Dict, Optional

from pydm import PyDMApplication

def load_json_file(file_path: Path) -> list:
    try:
        with file_path.open('r') as json_file:
            return json.load(json_file)
    except json.JSONDecodeError:
        print(f"Error: {file_path} is not a valid JSON file.")
        sys.exit(1)

def find_matching_macros(data: list, hvm_string: str) -> Optional[Dict]:
    return next((item for item in data if item.get('HV Channel Name') == hvm_string), None)

def main(hvm: str, file: str):
    ui_file_path = f'$PYDM/mc/WireScanner/{file}'
    json_file_path = '$PYDM/mc/WireScanner/Scanners.json'
    ui_file = Path(os.path.expandvars(ui_file_path))
    json_file = Path(os.path.expandvars(json_file_path))

    if not ui_file.exists():
        print(f"Error: UI file not found: {ui_file}")
        sys.exit(1)
    if not json_file.exists():
        print(f"Error: JSON file not found: {json_file}")
        sys.exit(1)

    data = load_json_file(json_file)
    
    macros = find_matching_macros(data, hvm)
    new_macros = {
        'HVM': macros['HV Channel Name'],
        'PMT': macros['PMT'],
        'Status': macros['HV Module'],
        'HVMCard': macros['HV Card Number'],
        'HVMSig': macros['HV Channel Number'],
        'Trigger': macros['Trigger'],
        'QADC': macros['QADC Module'],
        'QADCCard': macros['QADC Card Number'],
        'QADCSig': macros['QADC Channel Number'],
	'Location': macros['Sector'],
        }
    
    if not macros:
        print(f"Error: No match found for HVM: {hvm}")
        sys.exit(1)

    app = PyDMApplication(ui_file=str(ui_file), macros=new_macros)

    try:
        main_window = app.main_window
        main_window.show()
        sys.exit(app.exec_())
    except Exception as e:
        print(f"Error: Failed to load UI file: {e}")
        sys.exit(1)

if __name__ == "__main__":
    import argparse
    
    parser = argparse.ArgumentParser(description='Launch a PyDM .ui file with macros from JSON.')
    parser.add_argument('--hvm', type=str, required=True, help='String to match against HVM in JSON.')
    parser.add_argument('--file', required=True, type=str, help='UI FIle')
    args = parser.parse_args()
    main(args.hvm, args.file)
