#!/usr/bin/python3
# -*- coding: utf-8 -*-

import configparser
from pathlib import Path
from typing import Any

from sun.__metadata__ import __prgnam__
from sun.sys_info import get_static_paths


class Configs:  # pylint: disable=[R0903,R0902]

    """Base configuration class. Loads sun.conf settings and system information.

    Attributes:
        data_configs (dict): System information collected from the OS.
        interval (int): Update check interval in minutes.
        standby (int): Notification display duration in milliseconds (x60000).
        repo_mirror (str): HTTP mirror URL for the Slackware repository.
        repo_log_path (str): Local path to the repository ChangeLog directory.
        repo_log_file (str): Filename of the repository ChangeLog.
        ignore_mirror_warning (bool): If True, suppress the mirror/version mismatch warning.
        http_timeout (int): Timeout in seconds for HTTP requests to the mirror.
        delay_load (int): Delay in seconds before the tray icon starts.
        max_packages (int): Maximum number of packages shown in the tray popup.
        badge_interval (int): Interval in minutes between silent badge update checks.
        notifications (bool): If True, show desktop notifications when updates are found.
        colored_output (bool): If True, colorize action labels in the tray Check Updates and OS Info dialogs.
        log_font_size (int): Font size in points for the ChangeLog and SUN Log dialogs.
    """

    def __init__(self) -> None:
        self.data_configs: dict[str, Any] = get_static_paths()
        config_file: str = f'{__prgnam__}.conf'
        sun_conf: Path = Path(self.data_configs['sun_conf_path'], config_file)

        try:
            if sun_conf.is_file():
                configs = configparser.ConfigParser()
                configs.read(sun_conf)
            else:
                raise FileNotFoundError(f"Error: Failed to find '{sun_conf}' file.")

            # Time configs.
            self.interval: int = int(configs['TIME']['INTERVAL'])
            self.standby: int = int(configs['TIME']['STANDBY'])
            self.notifications: bool = configs['TIME'].getboolean('NOTIFICATIONS', fallback=True)
            # Repositories configs.
            self.repo_mirror: str = configs['REPOSITORY']['HTTP_MIRROR']
            self.repo_log_path: str = configs['REPOSITORY']['LOG_PATH']
            self.repo_log_file: str = configs['REPOSITORY']['LOG_FILE']
            self.ignore_mirror_warning: bool = configs['REPOSITORY'].getboolean('IGNORE_MIRROR_WARNING', fallback=False)
            self.http_timeout: int = int(configs['REPOSITORY'].get('HTTP_TIMEOUT', '30'))
            # Tray app config.
            self.delay_load: int = int(configs['TRAY_ICON']['DELAY_LOAD'])
            self.max_packages: int = int(configs['TRAY_ICON']['MAX_PACKAGES'])
            self.badge_interval: int = int(configs['TRAY_ICON'].get('BADGE_INTERVAL', '180'))
            self.colored_output: bool = configs['TRAY_ICON'].getboolean('COLORED_OUTPUT', fallback=True)
            self.log_font_size: int = int(configs['TRAY_ICON'].get('LOG_FONT_SIZE', '10'))

            if self.interval < 1:
                raise ValueError(f"INTERVAL must be >= 1, got {self.interval}")
            if self.standby < 1:
                raise ValueError(f"STANDBY must be >= 1, got {self.standby}")
            if self.delay_load < 0:
                raise ValueError(f"DELAY_LOAD must be >= 0, got {self.delay_load}")
            if self.max_packages < 1:
                raise ValueError(f"MAX_PACKAGES must be >= 1, got {self.max_packages}")
            if self.badge_interval < 1:
                raise ValueError(f"BADGE_INTERVAL must be >= 1, got {self.badge_interval}")
            if self.http_timeout < 1:
                raise ValueError(f"HTTP_TIMEOUT must be >= 1, got {self.http_timeout}")
            if self.log_font_size < 1:
                raise ValueError(f"LOG_FONT_SIZE must be >= 1, got {self.log_font_size}")

        except (KeyError, FileNotFoundError, ValueError, configparser.Error) as error:
            raise SystemExit(f"Error: {error}: in the config file '{sun_conf}'.") from error


# Runtime PID files for daemon and tray processes.
DAEMON_PID_FILE: Path = Path.home() / '.run' / 'sun-daemon.pid'
TRAY_PID_FILE: Path = Path.home() / '.run' / 'sun-tray.pid'

# Single shared instance — imported by Manager and any other module that needs config.
configs_load = Configs()
