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 = []

    # 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.append(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")

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

    return ioc_dict


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)

    # Determine if we print out the error causing the PV to be invalid
    # Determine if we need to include which IOC contains a given PV
    err_out = sys.argv[2] == '1'
    check_iocs = sys.argv[3] == '1'
    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 ':'
        for pv in line:
            fields = pv.split(":")
            err_code = []

            # Check if PV is invalid (<3 ':' | invalid device | invalid area). If so, save the
            #   error code to be accessed later.
            if len(fields) < 4:
                err_code.append("<3 :")
            if (len(fields) > 1) and (fields[1] not in file_data["areas"]):
                err_code.append(f"{fields[1]} not found")
            if (len(fields) > 0) and (fields[0] not in file_data["devices"]):
                err_code.append(f"{fields[0]} not found")

            # If the PV is invalid, then print the PV. Include the IOC and/or Error if requested.
            if not err_code:
                continue
            output = pv
            if check_iocs:
                ioc = all_ioc_data.get(pv, 'ERROR: Not in $IOC_DATA')
                output = ioc + ',' + output
            if err_out:
                output += ',' + err_code[-1]
            print(output)


if __name__ == "__main__":
    main()
