"""
Configuration management for Context Custodians
"""

import os
import yaml
from pathlib import Path
from typing import Dict, List, Any


class Config:
    """Configuration manager for the Memory Warden system"""

    def __init__(self, workspace_path: str = None):
        self.workspace_path = Path(workspace_path or os.getcwd())
        self.config_dir = self.workspace_path / '.vmw'
        self.config_file = self.config_dir / 'config.yaml'
        self._config = self._load_config()

    def _load_config(self) -> Dict[str, Any]:
        """Load configuration from YAML file"""
        if self.config_file.exists():
            with open(self.config_file, 'r') as f:
                return yaml.safe_load(f) or {}

        # Return default configuration
        return self._get_default_config()

    def _get_default_config(self) -> Dict[str, Any]:
        """Get default configuration"""
        return {
            'version': '0.1.0',
            'workspace': str(self.workspace_path),
            'monitoring': {
                'enabled': True,
                'interval_seconds': 300,  # 5 minutes
                'watched_files': [
                    '.github/copilot-instructions.md',
                    'docker-compose.yml',
                    '.env',
                    'pyproject.toml',
                    'setup.py',
                    'requirements.txt',
                    'README.md'
                ],
                'ignored_patterns': [
                    '*.log',
                    '*.tmp',
                    '__pycache__/*',
                    '.git/*',
                    'node_modules/*'
                ]
            },
            'agents': {
                'file_watcher': {'enabled': True},
                'vital_extractor': {'enabled': True},
                'context_updater': {'enabled': True},
                'health_monitor': {'enabled': True},
                'coordinator': {'enabled': True}
            },
            'output': {
                'context_file': 'ALWAYS_AVAILABLE_CONTEXT.md',
                'vital_updates_file': 'VITAL_UPDATES.md',
                'log_file': 'agent_logs.json'
            },
            'systemd': {
                'enabled': False,
                'service_name': 'vitruvyan-memory-warden',
                'user': os.getenv('USER', 'user')
            }
        }

    def save_config(self):
        """Save current configuration to file"""
        self.config_dir.mkdir(exist_ok=True)
        with open(self.config_file, 'w') as f:
            yaml.dump(self._config, f, default_flow_style=False, indent=2)

    def get(self, key: str, default=None):
        """Get configuration value"""
        keys = key.split('.')
        value = self._config
        for k in keys:
            if isinstance(value, dict):
                value = value.get(k, default)
            else:
                return default
        return value

    def set(self, key: str, value: Any):
        """Set configuration value"""
        keys = key.split('.')
        config = self._config
        for k in keys[:-1]:
            if k not in config:
                config[k] = {}
            config = config[k]
        config[keys[-1]] = value
        self.save_config()

    @property
    def watched_files(self) -> List[str]:
        """Get list of watched files"""
        return self.get('monitoring.watched_files', [])

    @property
    def monitoring_interval(self) -> int:
        """Get monitoring interval in seconds"""
        return self.get('monitoring.interval_seconds', 300)

    def is_agent_enabled(self, agent_name: str) -> bool:
        """Check if agent is enabled"""
        return self.get(f'agents.{agent_name}.enabled', True)