import platform
import socket
import subprocess
import sys
from datetime import datetime
from typing import Dict, Any

import psutil


class OSATime:
    def __init__(self, osaf_core):
        self.osaf_core = osaf_core
        self.log = osaf_core.log

    def getNowISO8601(self):
        now = datetime.now()
        return now.astimezone().replace(microsecond=0).isoformat()

    def getNowForFileName(self):
        now = datetime.now()
        return now.strftime('%Y-%m-%d_%H-%M-%S')

    def getNowForFileNameDos(self):
        now = datetime.now()
        return now.strftime('%y%m%d')

    def getNowPretty(self):
        now = datetime.now()
        return now.strftime('%Y/%m/%d %H:%M:%S')

    def getNowTime(self):
        now = datetime.now()
        return now.strftime('%H:%M:%S')





class OSAUtils:
    def __init__(self, conf):
        self.arch_data = conf.get("platform", {}).get("arch_aliases", {})

    def arch_normalize(self, arch_name):
        for k, v in self.arch_data.items():
            v.append(k)
            lowercase_v = [s.lower() for s in v]
            if arch_name.lower() in lowercase_v:
                return k.lower()
        return None

    def is_windows(self):
        return sys.platform.startswith('win')

    def is_linux(self):
        return sys.platform.startswith('linux')

    def is_mac(self):
        return sys.platform.startswith('darwin')

    def command_probe(self, command, normal_code=0):
        c = 127
        try:
            result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                    timeout=10, shell=False)
            c = result.returncode
        except:
            pass
        if c != normal_code:
            self.log.d(f'Probe command {" ".join(command)} failed, code={c}')
            return False
        return True

    def get_system_info(self) -> Dict[str, Any]:
        """Get comprehensive system information"""
        return {
            'platform': sys.platform,
            'architecture': platform.machine(),
            'hostname': socket.gethostname(),
            'cpu_cores': psutil.cpu_count(),
            'total_memory': psutil.virtual_memory().total,
            'disk_usage': {p.mountpoint: psutil.disk_usage(p.mountpoint)._asdict()
                           for p in psutil.disk_partitions()},
            'python_version': sys.version
        }

