#!/usr/bin/env python3
import os
import configparser


class Config:
    def __init__(self):
        self.BASE_DIR = os.path.dirname(os.path.abspath(__file__))
        self.SESSIONS_DIR = os.path.join(self.BASE_DIR, "sessions")
        
        # Значения по умолчанию
        self.MQTT_HOST = "0.0.0.0"
        self.MQTT_PORT = 1883
        self.SESSION_TIMEOUT = 180
        self.UDP_PORT = 48899
        self.UDP_INTERVAL = 5
        self.DEVICE_NAME = "SamovarichLogger"
        self.MAX_POINTS_PER_SESSION = 1000 
        self.MASK = '255.255.255.255' 
        
        self._load_config()
    
    def _load_config(self):
        config_file = os.path.join(self.BASE_DIR, "config.ini")
        
        if not os.path.exists(config_file):
            self._create_default_config(config_file)
            return
        
        try:
            config = configparser.ConfigParser()
            config.read(config_file, encoding='utf-8')
            
            if config.has_section('MQTT'):
                self.MQTT_PORT = config.getint('MQTT', 'port', fallback=1883)
                self.SESSION_TIMEOUT = config.getint('MQTT', 'session_timeout', fallback=600)
            
            if config.has_section('UDP'):
                self.UDP_PORT = config.getint('UDP', 'port', fallback=48899)
                self.UDP_INTERVAL = config.getint('UDP', 'interval', fallback=5)
                self.DEVICE_NAME = config.get('UDP', 'device_name', fallback='SamovarichLogger')
                self.MASK = config.get('UDP', 'mask', fallback='255.255.255.255')
            
            if config.has_section('LOGGING'):
                self.MAX_POINTS_PER_SESSION = config.getint('LOGGING', 'max_points', fallback=1000)
                
        except Exception as e:
            print(f"Ошибка чтения config.ini: {e}")
    
    def _create_default_config(self, filename: str):
        with open(filename, 'w', encoding='utf-8') as f:
            f.write("""# Конфигурация Logger PC

[MQTT]
port = 1883
session_timeout = 180

[UDP]
port = 48899
interval = 5
device_name = SamovarichLogger
mask = 255.255.255.255

[LOGGING]
max_points = 1000
""")
        print(f"Создан файл конфигурации: {filename}")