import json
import os

def get_structured_path(view_name, equipment_path, MCM):
    """
    Create a structured path based on the equipment type
    """
    base_path = f"System/{MCM}/"
    
    # Check if it's a TPE (Photoeye) equipment
    if "TPE" in view_name and "Photoeye" in equipment_path:
        return f"{base_path}Photoeye/TPE/{view_name}"
    
    # Check if it's a LRPE (Photoeye) equipment  
    elif "LRPE" in view_name and "Photoeye" in equipment_path:
        return f"{base_path}Photoeye/LRPE/{view_name}"

    elif "PE" in view_name and "Photoeye" in equipment_path:
        return f"{base_path}Photoeye/PE/{view_name}"
    
    # Check if it's an SIO equipment
    elif "SIO" in view_name and "IO_Block" in equipment_path:
        return f"{base_path}IO_Block/SIO/{view_name}"
    
    # Check if it's an FIO equipment
    elif "FIOM" in view_name and "IO_Block" in equipment_path:
        return f"{base_path}IO_Block/FIO/{view_name}"
    
    elif "DPM" in view_name and "DPM" in equipment_path:
        return f"{base_path}IO_Block/DPM/{view_name}"
    
    # Check if it's an Encoder equipment
    elif "ENSH" in view_name and "Encoder" in equipment_path:
        return f"{base_path}ENCODER/ENSH/{view_name}"

    elif "ENW" in view_name and "Encoder" in equipment_path:
        return f"{base_path}ENCODER/ENW/{view_name}"

    elif "BCN" in view_name and "Beacon" in equipment_path:
        return f"{base_path}Beacon/{view_name}"

    elif "EPC" in view_name and "EPC" in equipment_path:
        return f"{base_path}STATION/EPC/{view_name}"

    elif "SS" in view_name and "SS_Button" in equipment_path:
        return f"{base_path}STATION/SS/{view_name}"

    elif "JR" in view_name and "S03" in view_name and "Button" in equipment_path:
        return f"{base_path}STATION/Chute_JR/{view_name}"

    elif "JR" in view_name and "Button" in equipment_path:
        return f"{base_path}STATION/JR/{view_name}"

    elif "EN" in view_name and "Button" in equipment_path:
        return f"{base_path}STATION/EN/{view_name}"

    elif "VFD" in view_name and "VFD" in equipment_path:
        return f"{base_path}VFD/{view_name}"

    elif "MCM" in view_name and "MCM" in equipment_path:
        return f"{base_path}/{view_name}"

    elif "Camera" in view_name and "Camera" in equipment_path:
        return f"{base_path}Camera/{view_name}"

    elif "Conveyor" in equipment_path:
        return f"{base_path}Conveyor/{view_name}"

    elif "SOL" in view_name and "Solenoid" in equipment_path:
        return f"{base_path}SOL/{view_name}"

    elif "PRX" in view_name and "ProxSensor" in equipment_path:
        return f"{base_path}PRX/{view_name}"

    elif "CH" in view_name and "Chute" in equipment_path:
        return f"{base_path}Chute/{view_name}"

    # We can expand this later for other equipment types
    else:
        return view_name

def update_tagprops_in_file(file_path):
    """
    Update the first item in tagProps array for each view with structured paths
    """
    try:
        # Read the JSON file
        with open(file_path, 'r', encoding='utf-8') as file:
            data = json.load(file)

        
        name = os.path.basename(file_path)
        MCM = name.split('.')[0]  # Extract MCM from filename

        # Counter for updated views
        updated_count = 0
        
        # Navigate to the container with children
        if 'root' in data and 'children' in data['root']:
            container = data['root']['children'][0] # First child is the CoordinateContainer
            
            if 'children' in container:
                # Iterate through all views in the container
                for view in container['children']:
                    # Check if this view has meta.name and params.tagProps
                    if ('meta' in view and 'name' in view['meta'] and 
                        'props' in view and 'params' in view['props'] and 
                        'tagProps' in view['props']['params']):
                        
                        # Get the view name and equipment path
                        view_name = view['meta']['name']
                        equipment_path = view['props'].get('path', '')
                        
                        # Get the structured path
                        structured_path = get_structured_path(view_name, equipment_path, MCM)
                        
                        # Update the first item in tagProps array
                        if len(view['props']['params']['tagProps']) > 0:
                            view['props']['params']['tagProps'][0] = structured_path
                            updated_count += 1
                            print(f"Updated {view_name} -> {structured_path}")
        
        # Write the updated data back to the file
        with open(file_path, 'w', encoding='utf-8') as file:
            json.dump(data, file, indent=2, ensure_ascii=False)
        
        print(f"\nSuccessfully updated {updated_count} views in {file_path}")
        
    except FileNotFoundError:
        print(f"Error: File {file_path} not found")
    except json.JSONDecodeError as e:
        print(f"Error: Invalid JSON in file {file_path}: {e}")
    except Exception as e:
        print(f"Error: {e}")


def main():
    # Find all JSON files in the current directory
    json_files = [f for f in os.listdir('.') if f.endswith('.json')]
    
    if not json_files:
        print("No JSON files found in the current directory.")
        return

    # Display files to the user
    print("Available JSON files:")
    for i, f in enumerate(json_files, start=1):
        print(f"{i}. {f}")
    
    # Ask user to pick one
    try:
        choice = int(input("Select a file by number: ")) - 1
        if choice < 0 or choice >= len(json_files):
            print("Invalid choice.")
            return
    except ValueError:
        print("Invalid input. Please enter a number.")
        return

    file_path = json_files[choice]

    # Check if file exists (should always be true here)
    if not os.path.exists(file_path):
        print(f"File {file_path} not found in current directory")
        return
    
    # Update the file
    update_tagprops_in_file(file_path)



if __name__ == "__main__":
    main()
