import os
import time
import psutil
import logging
import shutil
from typing import Dict, Any

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s",
    handlers=[
        logging.StreamHandler(),  # Output to console
    ],
)

class ResourceTracker:
    """
    A class to monitor CPU, memory, and disk usage.
    """

    def __init__(self):
        """
        Initializes the ResourceTracker.
        """
        self.logger = logging.getLogger(__name__)
        self.data: Dict[str, Any] = {}

    def get_cpu_usage(self) -> float:
        """
        Returns the current CPU utilization as a percentage.

        Returns:
            float: CPU utilization percentage.
        """
        try:
            cpu_usage = psutil.cpu_percent(interval=1)
            self.data["cpu_usage"] = cpu_usage
            return cpu_usage
        except Exception as e:
            self.logger.error(f"Error getting CPU usage: {e}")
            return -1.0

    def get_memory_usage(self) -> Dict[str, float]:
        """
        Returns a dictionary containing memory usage statistics.

        Returns:
            Dict[str, float]: Memory usage statistics.
                Keys: 'total', 'available', 'used', 'percent'.
        """
        try:
            vm = psutil.virtual_memory()
            memory_usage = {
                "total": vm.total,
                "available": vm.available,
                "used": vm.used,
                "percent": vm.percent,
            }
            self.data["memory_usage"] = memory_usage
            return memory_usage
        except Exception as e:
            self.logger.error(f"Error getting memory usage: {e}")
            return {}

    def get_disk_usage(self, path: str = "/") -> Dict[str, float]:
        """
        Returns a dictionary containing disk usage statistics for a given path.

        Args:
            path (str): The path to check disk usage for. Defaults to "/".

        Returns:
            Dict[str, float]: Disk usage statistics.
                Keys: 'total', 'used', 'free', 'percent'.
        """
        try:
            disk_usage = shutil.disk_usage(path)
            disk_usage_dict = {
                "total": disk_usage.total,
                "used": disk_usage.used,
                "free": disk_usage.free,
                "percent": disk_usage.used / disk_usage.total * 100,
            }
            self.data["disk_usage"] = disk_usage_dict
            return disk_usage_dict
        except Exception as e:
            self.logger.error(f"Error getting disk usage for path {path}: {e}")
            return {}

    def collect_resource_data(self) -> Dict[str, Any]:
        """
        Collects all resource data and returns a dictionary.

        Returns:
            Dict[str, Any]: A dictionary containing CPU, memory, and disk usage data.
        """
        self.get_cpu_usage()
        self.get_memory_usage()
        self.get_disk_usage()  # uses default path "/"
        return self.data

    def log_resource_data(self):
        """
        Collects and logs the resource data.
        """
        data = self.collect_resource_data()
        self.logger.info(f"Resource Data: {data}")


def main():
    """
    Main function to demonstrate the ResourceTracker.
    """
    tracker = ResourceTracker()
    while True:
        tracker.log_resource_data()
        time.sleep(5)


if __name__ == "__main__":
    # Create the directory if it doesn't exist
    directory = "/mnt/e/genesis-system/core/monitoring"
    if not os.path.exists(directory):
        try:
            os.makedirs(directory)
        except OSError as e:
            logging.error(f"Error creating directory {directory}: {e}")
            exit(1)  # Exit if the directory cannot be created

    # Check if the script is running as intended before running main
    if os.path.dirname(os.path.abspath(__file__)) == os.path.dirname(directory):
      main()
    else:
      logging.error(f"Script must be run from: {directory}")