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_RCVD': 'netstat_Syn_Recv',
    'SYN_RECEIVED': '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',
    'IDLE': 'netstat_Unknown',
    'BOUND': '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,
    }
    psutil_ok = False
    try:
        import psutil as _psutil
        for conn in _psutil.net_connections(kind='tcp'):
            status = conn.status.upper() if conn.status else ''
            key = STATE_MAP.get(status, 'netstat_Unknown')
            counters[key] += 1
        psutil_ok = True
    except Exception:
        psutil_ok = False

    if not psutil_ok:
        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(Solaris) error:', e)

    try:
        import os, glob
        fd_total = 0
        for pid_dir in glob.glob('/proc/*/fd'):
            try:
                fd_total += len(os.listdir(pid_dir))
            except Exception:
                pass
        counters['Server_Filedescriptors'] = fd_total
    except Exception:
        pass

    return counters
