import sys
import json
import subprocess

from os import getenv

# Calls a subprocess to find all IOCs containing an IOC.pvlist file. Then a dict object is constructed
#   consisting of (key=IOC Name, value={key}/iocInfo/IOC.pvlist)
def get_ioc_data():
    # Save path to $IOC_DATA for removal later and initialize ioc_data
    ioc_path = getenv('IOC_DATA')
    ioc_data = dict()

    # Call find and capture the ouput as a list of IOC directories. Save individual IOC names to ioc_data
    try:
        output = subprocess.check_output("find $IOC_DATA/*/iocInfo/ -iname IOC.pvlist", stderr=subprocess.DEVNULL, text=True, shell=True).split()
        for curr_dir in output:
            curr_dir = curr_dir.replace(ioc_path, '')
            ioc_data[curr_dir.split('/')[1]] = ''

    # If there is an error, then parse the output based on the returncode
    except subprocess.CalledProcessError as e:
        if e.returncode != 0:
            print("ERROR: Find command failed")
        else:
            print("ERROR: Unknown subprocess error occurred")

    # Populate the values of ioc_data based on the existing keys
    for ioc in ioc_data.keys():
        with open(f'{ioc_path}/{ioc}/iocInfo/IOC.pvlist', 'r') as f:
            ioc_data[ioc] = f.read()

    return ioc_data

def main():
    # Load information stored in .json file (Device names, Area names, etc.)
    with open(sys.argv[1], 'r') as f:
        file_data = json.load(f)

    # Save incorrect PVs to be assessed later if needed
    # invalid_pvs = []
    check_iocs = sys.argv[2] == 'True'
    if check_iocs:
        all_ioc_data = get_ioc_data()

    # Read input and parse into list of pv names (str)
    for line in sys.stdin:
        # Allows interrupt if PVs are input manually
        if 'exit' == line.lower().rstrip():
            break

        line = line.split()

        # Process each pv and split it at ':'. Check the following
        for pv in line:
            fields = pv.split(":")

            # Check if PV is invalid (<3 ':' | invalid device | invalid area). If so, print the
            #   PV and include the IOC name if requested.
            if (len(fields) < 4) \
                    or (fields[0] not in file_data["devices"]) \
                    or (fields[1] not in file_data["areas"]):
                if check_iocs:
                    ioc = 'ERROR: Not in $IOC_DATA'
                    for key, value in all_ioc_data.items():
                        if pv + ',' in value:
                            ioc = key
                            break
                    print(ioc + ',' + pv)
                else:
                    print(pv)


if __name__ == "__main__":
    main()
