import os
import yaml
import json
from pathlib import Path
from typing import Any, Dict, Optional
from pydantic import BaseModel, ValidationError


class ConfigSchema(BaseModel):
    """Base configuration schema"""
    app_name: str = "FeatherOS App"
    debug: bool = False
    host: str = "0.0.0.0"
    port: int = 5000
    database_url: Optional[str] = None
    secret_key: Optional[str] = None
    
    class Config:
        extra = "allow"


class ConfigManager:
    """Manage application configuration"""
    
    def __init__(self, config_file: str = 'config.yaml'):
        self.config_file = Path(config_file)
        self.config = {}
        self._load()
    
    def _load(self):
        """Load configuration from file"""
        if not self.config_file.exists():
            self.config = self._get_defaults()
            return
        
        if self.config_file.suffix in ['.yaml', '.yml']:
            with open(self.config_file, 'r') as f:
                self.config = yaml.safe_load(f) or {}
        elif self.config_file.suffix == '.json':
            with open(self.config_file, 'r') as f:
                self.config = json.load(f)
        
        self.config = {**self._get_defaults(), **self.config}
        
        for key in self.config.keys():
            env_key = key.upper()
            if env_key in os.environ:
                self.config[key] = os.environ[env_key]
    
    def _get_defaults(self) -> Dict[str, Any]:
        """Get default configuration"""
        return ConfigSchema().dict()
    
    def get(self, key: str, default: Any = None) -> Any:
        """Get a configuration value"""
        return self.config.get(key, default)
    
    def set(self, key: str, value: Any):
        """Set a configuration value"""
        self.config[key] = value
    
    def save(self):
        """Save configuration to file"""
        if self.config_file.suffix in ['.yaml', '.yml']:
            with open(self.config_file, 'w') as f:
                yaml.dump(self.config, f, default_flow_style=False)
        elif self.config_file.suffix == '.json':
            with open(self.config_file, 'w') as f:
                json.dump(self.config, f, indent=2)
    
    def validate(self) -> bool:
        """Validate configuration against schema"""
        try:
            ConfigSchema(**self.config)
            return True
        except ValidationError as e:
            print(f"Configuration validation failed: {e}")
            return False


config = ConfigManager()
