#!/usr/bin/env python3
"""
NovaLang Configuration Reader
Reads novalang.config file (similar to Spring Boot's application.properties)
"""

import os
from typing import Dict, Any


class NovaLangConfig:
    """Configuration manager for NovaLang applications"""
    
    def __init__(self, config_path: str = "novalang.config"):
        self.config_path = config_path
        self.properties: Dict[str, str] = {}
        self._load_config()
    
    def _load_config(self):
        """Load configuration from file"""
        if not os.path.exists(self.config_path):
            print(f"⚠️  Config file not found: {self.config_path}, using defaults")
            self._set_defaults()
            return
        
        with open(self.config_path, 'r', encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                
                # Skip comments and empty lines
                if not line or line.startswith('#'):
                    continue
                
                # Parse key=value
                if '=' in line:
                    key, value = line.split('=', 1)
                    self.properties[key.strip()] = value.strip()
        
        print(f"✅ Loaded configuration from {self.config_path}")
    
    def _set_defaults(self):
        """Set default configuration values"""
        self.properties = {
            'server.port': '8080',
            'server.host': 'localhost',
            'database.type': 'sqlite',
            'database.name': 'novalang_app.db',
            'app.name': 'NovaLang Application',
            'app.version': '1.0.0',
            'app.env': 'development',
            'logging.level': 'INFO'
        }
    
    def get(self, key: str, default: Any = None) -> str:
        """Get configuration value by key"""
        return self.properties.get(key, default)
    
    def get_int(self, key: str, default: int = 0) -> int:
        """Get configuration value as integer"""
        value = self.properties.get(key, default)
        try:
            return int(value)
        except (ValueError, TypeError):
            return default
    
    def get_bool(self, key: str, default: bool = False) -> bool:
        """Get configuration value as boolean"""
        value = self.properties.get(key, str(default)).lower()
        return value in ('true', 'yes', '1', 'on')
    
    def get_server_config(self) -> Dict[str, Any]:
        """Get server configuration"""
        return {
            'host': self.get('server.host', 'localhost'),
            'port': self.get_int('server.port', 8080)
        }
    
    def get_database_config(self) -> Dict[str, Any]:
        """Get database configuration"""
        return {
            'type': self.get('database.type', 'sqlite'),
            'name': self.get('database.name', 'novalang_app.db'),
            'host': self.get('database.host', 'localhost'),
            'port': self.get_int('database.port', 5432),
            'username': self.get('database.username', ''),
            'password': self.get('database.password', '')
        }
    
    def get_app_config(self) -> Dict[str, Any]:
        """Get application configuration"""
        return {
            'name': self.get('app.name', 'NovaLang Application'),
            'version': self.get('app.version', '1.0.0'),
            'env': self.get('app.env', 'development')
        }
    
    def __str__(self) -> str:
        """String representation"""
        return f"NovaLangConfig({len(self.properties)} properties)"
    
    def print_config(self):
        """Print all configuration properties"""
        print("\n=== NovaLang Configuration ===")
        for key, value in sorted(self.properties.items()):
            # Mask sensitive values
            if 'password' in key.lower():
                value = '***' if value else ''
            print(f"  {key} = {value}")
        print("=" * 32 + "\n")


if __name__ == "__main__":
    # Test the config reader
    config = NovaLangConfig()
    config.print_config()
    
    print("Server Config:", config.get_server_config())
    print("Database Config:", config.get_database_config())
    print("App Config:", config.get_app_config())
