import os
import subprocess
from pathlib import Path
from pandas import read_csv
from fnmatch import filter
from argparse import ArgumentParser
from typing import List
import math

MAXLINE = 100
ALLOWED = {'TYPE': ["ai", "ao", "bi", "bo", "longin", "longout", "calc", "calcout", "motor", "sub"],
           'LVPOS': ["A", "B", "C", "D", "E", "F", "G", "H", "LVRAW"],
           'MOTR': ["LLM", "HLM", "ACCL", "MRES", "VAL", "RBV", "DRBV", "VELO", "STAT", "MSTA", "ERES", "RRES"],
           'POSN': ["ESLO"],
           }

def Refresh(ioc: List[str]) -> None:
    subprocess.run(['rm', '-rf', 'epics-temp'], check=True)
    Path('epics-temp').mkdir(exist_ok=True)
    head = Path(os.environ.get('IOC_DATA', ''))
    globbed = []

    if bool(ioc):
        folders = list(set(os.listdir(head)))
        for pattern in ioc:
            found = filter(folders, pattern)
            for variable in found:
                globbed.append(f'{variable}')

        if bool(globbed):
            for ioc_name in sorted(globbed):
                savename = Path('epics-temp') / ioc_name
                data = read_csv(head / ioc_name / 'iocInfo' / 'IOC.pvlist', header=None, names=['Record', 'Type'])
                data['Type'] = data['Type'].str.strip().str.strip('"')
                data = data[data['Type'].isin(ALLOWED['TYPE'])]

                subprocess.run(f'rm -rf {head}/{ioc_name}/archive/AUTO_*.archive', shell=True, check=True)
                data['Record'].to_csv(f'{savename}_MASTER.txt', index=False, header=False)

                with open(f'{savename}_MASTER.txt', "a+") as file:
                    for record in data['Record']:
                        for name in ALLOWED.keys():
                            if name != 'TYPE' and record.endswith(f':{name}'):
                                for subrecord in ALLOWED[name]:
                                    file.write(f'{record}.{subrecord}\n')

                data = read_csv(f'{savename}_MASTER.txt', header=None, names=['Record'])
                num_files = math.ceil(len(data) / MAXLINE)

                for i in range(num_files):
                    chunk = data.iloc[(i * MAXLINE):((i + 1) * MAXLINE)]
                    file_suffix = f'_{i+1}' if num_files > 1 else ''
                    chunk['Record'].to_csv(f'{savename}{file_suffix}.txt', index=False, header=False)

                    subprocess.run(f'mv {savename}{file_suffix}.txt {savename}{file_suffix}.archive', shell=True, check=True)
                    subprocess.run(f'cp {savename}{file_suffix}.archive {head}/{ioc_name}/archive/AUTO_{file_suffix}.archive', shell=True, check=True)

                subprocess.run(f'rm -rf epics-temp', shell=True, check=True)

if __name__ == '__main__':
    parser = ArgumentParser()
    parser.add_argument('ioc', type=str, nargs='+')

    args = parser.parse_args()
    Refresh(args.ioc)