import whatap.util.process_util as process_util
import whatap.util.logging_util as logging_util

STATE_MAP = {
    'ESTABLISHED': 'netstat_Established',
    'SYN_SENT': 'netstat_Syn_Sent',
    'SYN_RECEIVED': 'netstat_Syn_Recv',
    'SYN_RECV': 'netstat_Syn_Recv',
    'FIN_WAIT_1': 'netstat_Fin_Wait1',
    'FIN_WAIT1': 'netstat_Fin_Wait1',
    'FIN_WAIT_2': 'netstat_Fin_Wait2',
    'FIN_WAIT2': 'netstat_Fin_Wait2',
    'TIME_WAIT': 'netstat_Time_Wait',
    'CLOSE_WAIT': 'netstat_Close_Wait',
    'LAST_ACK': 'netstat_Last_Ack',
    'LISTEN': 'netstat_Listen',
    'CLOSING': 'netstat_Closing',
    'CLOSE': 'netstat_Unknown',
    'CLOSED': 'netstat_Unknown',
}

def GetNetstatCounters():
    counters = {
        'netstat_Unknown': 0,
        'netstat_Established': 0,
        'netstat_Syn_Sent': 0,
        'netstat_Syn_Recv': 0,
        'netstat_Fin_Wait1': 0,
        'netstat_Fin_Wait2': 0,
        'netstat_Time_Wait': 0,
        'netstat_Close_Wait': 0,
        'netstat_Last_Ack': 0,
        'netstat_Listen': 0,
        'netstat_Closing': 0,
        'Server_Filedescriptors': 0,
    }
    try:
        output = process_util.executeCommandShellWithTimeout('netstat -an -f inet 2>/dev/null', timeout=10)
        for line in output.split('\n'):
            tokens = line.strip().split()
            if not tokens or tokens[0] != 'tcp':
                continue
            if len(tokens) < 6:
                continue
            state = tokens[-1].upper()
            key = STATE_MAP.get(state, 'netstat_Unknown')
            counters[key] += 1
    except Exception as e:
        logging_util.error('GetNetstatCounters(HP-UX) error:', e)

    try:
        lsof_out = process_util.executeCommandShellWithTimeout('lsof 2>/dev/null | wc -l', timeout=10)
        fd_count = int(lsof_out.strip()) if lsof_out.strip().isdigit() else 0
        counters['Server_Filedescriptors'] = fd_count
    except Exception:
        pass

    return counters
