import subprocess
import os
import epics
import pandas as pd
from rich import print as rprint
from rich.table import Table
from rich.text import Text
from datetime import datetime

def ExecuteCollect(command: str) -> str:
    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=True)
    stdout, _ = process.communicate()
    return stdout

def main(args: list[str]) -> None:
    IOC = os.environ.get('IOC')
    if not IOC:
        print("IOC environment variable is not set.")
        return

    table1 = pd.DataFrame(columns=['IOC', 'Last User', 'Date Taken', 'Application','CPU Load'])
    
    year = str(datetime.now().year)
    
    for ioc in args:
        try:
            ioc_pv = ioc.upper().replace('-',':')
            ls_output = ExecuteCollect(f'ls -ll {IOC}/{ioc}/iocSpecificRelease')
            if not ls_output:
                continue
            pv = epics.PV(f'{ioc_pv}:LOAD')
            if pv.wait_for_connection(timeout=0.1):
                test_ioc_load = pv.get()
            else:
                test_ioc_load = 'Offline'
            history = ls_output.split()
            stats = {
                'IOC': ioc,
                'Last User': history[2],
                'Date Taken': f'{history[5]} {history[6] if len(history[6]) > 1 else "0" + history[6]}, {year if ":" in history[7] else history[7]}',
                'Application': '/'.join(history[-1].split('/')[-2::]) if len(history[-1].split('/')[-1]) else '/'.join(history[-1].split('/')[-3:-1]),
                'CPU Load': f'{100 * test_ioc_load:.2f}%' if test_ioc_load != 'Offline' else 'Offline'
            }
            
            table1 = pd.concat([table1, pd.DataFrame([stats])], ignore_index=True)
        except Exception as Error:
            continue
    
    table1 = table1.sort_values('IOC')
    table = Table(title="IOC Status")

    for column in table1.columns:
        table.add_column(column, style="cyan")

    table1['CPU Load'] = table1['CPU Load'].apply(lambda x: Text(x, style="yellow") if x == 'Offline' else x)

    for _, row in table1.iterrows():
        table.add_row(*[str(cell) if not isinstance(cell, Text) else cell for cell in row])

    rprint(table)

if __name__ == "__main__":
    args = [
        'ioc-b081-mc01', 'ioc-b081-mc02', 'ioc-b081-mc03', 'ioc-b081-mc04', 'ioc-b081-mc05',
        'sioc-b081-tm01', 'sioc-b34-mc01', 'sioc-b34-mc02', 'sioc-b34-mc03', 'sioc-b34-mc07',
        'sioc-b34-mc96', 'sioc-b81-mc00', 'sioc-b81-mc01', 'sioc-b81-mc02', 'sioc-b81-mc03',
        'sioc-b81-mc04', 'sioc-b81-mc05', 'sioc-b81-mc06', 'sioc-b81-mc07', 'sioc-b81-mc08',
        'sioc-b81-mc09', 'sioc-b81-mc10', 'sioc-b81-mc11', 'sioc-b81-mc12', 'sioc-b81-mc15',
        'sioc-b81-ps01', 'sioc-b81-ps02',
    ]
    
    print('\n')
    main(args)
    print('\n')
