"""
Configuration management for FHEnom AI client.
"""

import os
from pathlib import Path
from typing import Optional, Dict, Any
import yaml
from dataclasses import dataclass, field


@dataclass
class FHEnomConfig:
    """Configuration for FHEnom AI client."""
    
    # Admin API
    admin_host: str = "localhost"
    admin_port: int = 9099
    admin_api_key: str = ""
    
    # User API
    user_host: str = "localhost"
    user_port: int = 9999
    user_api_key: str = ""
    
    # Authentication
    auth_token: str = "default-auth-token-2026"
    
    # SFTP Configuration
    sftp_host: str = "localhost"
    sftp_port: int = 22
    sftp_username: str = "admin"
    sftp_password: Optional[str] = None
    sftp_key_path: Optional[str] = None
    sftp_models_dir: str = "models"
    sftp_datasets_dir: str = "datasets"
    
    # Local workspace
    workspace: Optional[str] = None
    
    # Connection defaults
    timeout: int = 30
    max_retries: int = 3
    verify_ssl: bool = True
    
    @property
    def admin_url(self) -> str:
        """Get admin API URL."""
        return f"http://{self.admin_host}:{self.admin_port}"
    
    @property
    def user_url(self) -> str:
        """Get user API URL."""
        return f"http://{self.user_host}:{self.user_port}"
    
    @classmethod
    def from_env(cls) -> "FHEnomConfig":
        """Create configuration from environment variables."""
        return cls(
            admin_host=os.getenv("FHENOM_ADMIN_HOST", "localhost"),
            admin_port=int(os.getenv("FHENOM_ADMIN_PORT", "9099")),
            admin_api_key=os.getenv("FHENOM_ADMIN_API_KEY", ""),
            user_host=os.getenv("FHENOM_USER_HOST", "localhost"),
            user_port=int(os.getenv("FHENOM_USER_PORT", "9999")),
            user_api_key=os.getenv("FHENOM_USER_API_KEY", ""),
            sftp_host=os.getenv("FHENOM_SFTP_HOST", "localhost"),
            sftp_port=int(os.getenv("FHENOM_SFTP_PORT", "22")),
            sftp_username=os.getenv("FHENOM_SFTP_USERNAME", "admin"),
            sftp_password=os.getenv("FHENOM_SFTP_PASSWORD"),
            sftp_key_path=os.getenv("FHENOM_SFTP_KEY_PATH"),
            timeout=int(os.getenv("FHENOM_TIMEOUT", "30")),
            max_retries=int(os.getenv("FHENOM_MAX_RETRIES", "3")),
            auth_token=os.getenv("FHENOM_AUTH_TOKEN", "default-auth-token-2026"),
        )
    
    @classmethod
    def from_file(cls, config_path: Optional[str] = None) -> "FHEnomConfig":
        """
        Load configuration from YAML file.
        
        Args:
            config_path: Path to config file. If None, looks in:
                         - ~/.fhenomai/config.yaml
                         - ./fhenomai.yaml
                         - ./fhenomai_config.yaml
        """
        if config_path is None:
            # Check default locations
            home_config = Path.home() / ".fhenomai" / "config.yaml"
            local_config = Path.cwd() / "fhenomai.yaml"
            local_config2 = Path.cwd() / "fhenomai_config.yaml"
            
            if home_config.exists():
                config_path = str(home_config)
            elif local_config.exists():
                config_path = str(local_config)
            elif local_config2.exists():
                config_path = str(local_config2)
            else:
                raise FileNotFoundError(
                    "No config file found. Create ~/.fhenomai/config.yaml or ./fhenomai.yaml"
                )
        
        with open(config_path, 'r') as f:
            data = yaml.safe_load(f)
        
        # Extract and flatten nested configurations
        config_data = {}
        
        # Handle admin section
        if 'admin' in data:
            admin = data['admin']
            config_data['admin_host'] = admin.get('host', 'localhost')
            config_data['admin_port'] = admin.get('port', 9099)
            config_data['admin_api_key'] = admin.get('api_key', '')
        
        # Handle sftp section
        if 'sftp' in data:
            sftp = data['sftp']
            config_data['sftp_host'] = sftp.get('host', config_data.get('admin_host', 'localhost'))
            config_data['sftp_port'] = sftp.get('port', 22)
            config_data['sftp_username'] = sftp.get('username', 'admin')
            config_data['sftp_password'] = sftp.get('password')
            config_data['sftp_key_path'] = sftp.get('key_path')
            config_data['sftp_models_dir'] = sftp.get('models_dir', 'models')
            config_data['sftp_datasets_dir'] = sftp.get('datasets_dir', 'datasets')
        
        # Handle user section
        if 'user' in data:
            user = data['user']
            config_data['user_host'] = user.get('host', config_data.get('admin_host', 'localhost'))
            config_data['user_port'] = user.get('port', 9999)
            config_data['user_api_key'] = user.get('api_key', '')
        
        # Handle defaults section
        if 'defaults' in data:
            defaults = data['defaults']
            config_data['timeout'] = defaults.get('timeout', 30)
            config_data['max_retries'] = defaults.get('max_retries', 3)
        
        # Handle flat structure (for backwards compatibility)
        flat_keys = ['admin_host', 'admin_port', 'user_host', 'user_port',
                     'sftp_host', 'sftp_port', 'sftp_username', 'sftp_password',
                     'workspace', 'timeout', 'max_retries']
        for key in flat_keys:
            if key in data and key not in config_data:
                config_data[key] = data[key]
        
        return cls(**config_data)
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert config to dictionary."""
        result = {
            'admin': {
                'host': self.admin_host,
                'port': self.admin_port,
                'api_key': self.admin_api_key,
            },
            'user': {
                'host': self.user_host,
                'port': self.user_port,
                'api_key': self.user_api_key,
            },
            'sftp': {
                'host': self.sftp_host,
                'port': self.sftp_port,
                'username': self.sftp_username,
                'models_dir': self.sftp_models_dir,
                'datasets_dir': self.sftp_datasets_dir,
            },
            'defaults': {
                'timeout': self.timeout,
                'max_retries': self.max_retries,
            }
        }
        
        # Add workspace if set
        if self.workspace:
            result['workspace'] = self.workspace
        
        return result
    
    def save(self, config_path: Optional[str] = None):
        """
        Save configuration to YAML file.
        
        Args:
            config_path: Path to save config. If None, saves to ~/.fhenomai/config.yaml
        """
        if config_path is None:
            config_path = str(Path.home() / ".fhenomai" / "config.yaml")
        
        # Ensure directory exists
        Path(config_path).parent.mkdir(parents=True, exist_ok=True)
        
        with open(config_path, 'w') as f:
            yaml.dump(self.to_dict(), f, default_flow_style=False)
