from pydantic import BaseModel, Field
from pydantic_settings import BaseSettings
import yaml
from pathlib import Path

class DelaysConfig(BaseModel):
    mcu_seconds: int = Field(2, ge=0, description="Delay after device connect before accessing the MCU")
    lighthouse_seconds: int = Field(4, ge=0, description="Added delay after mcu_seconds before accessing the lighthouse device")
    firmware_update_interval: int = Field(3, ge=0, description="Time between hmd firmware updates")

class Settings(BaseSettings):
    firmware_path: str = Field("", description="Firmware file to be used for updates. If empty, the latest version will be sought from the default utility folder")
    fpga_firmware_path: str = Field("", description="FPGA firmware file to be used for updates. If empty, the latest version will be sought from the default utility folder")
    clear_device_monitor_history: bool = Field(True, description="Whether to reset history of processed devices at end of run")
    usb_cleanup_threshold: int = Field(500, ge=0, description="Number of consecutive HMDs processed before cleaning up USB devices")
    max_threads: int = Field(16, ge=1, description="Maximum number of concurrent threads for processing devices")

    delays: DelaysConfig
        
    @classmethod
    def from_yaml(cls, yaml_path="quick_updater_config.yaml"):
        """Load settings from YAML file"""
        config_path = Path(yaml_path)
        if not config_path.exists():
            raise FileNotFoundError(f"Config file not found: {yaml_path}")
            
        with open(config_path, 'r') as f:
            yaml_data = yaml.safe_load(f)
        
        # Create instance with YAML data and env overrides
        return cls(**yaml_data)
    
    # Reload config into the current class instance. Return true if there is a change in any field.
    def reload(self, yaml_path="quick_updater_config.yaml"):
        new_config = Settings.from_yaml(yaml_path)
        changed = False
        for field in self.__fields__:
            if getattr(self, field) != getattr(new_config, field):
                changed = True
                setattr(self, field, getattr(new_config, field))
        return changed


# Load settings when module is imported
config = Settings.from_yaml()