from typing import Dict, List, Optional, Tuple
from pathlib import Path
import json
import logging
from cw_rpa_unified_logger import UnifiedLogger
from m365_user_manager.config import logging_config

class EnvironmentManager():
    """
    Manages environment configuration and setup for the application.
    
    This class handles environment detection (local vs Asio RPA), logging setup,
    and configuration management. It maintains a predefined list of Microsoft 365
    product licenses and their corresponding SKU IDs.
    
    Usage:
        env_manager = EnvironmentManager()
        is_asio, config = env_manager.initialize()
        
        # Access logger
        env_manager.logger.info("Application started")
        
    Attributes:
        PRODUCT_LICENSES (List[Dict]): Mapping of M365 license names to SKU IDs
        running_in_asio (bool): Indicates if running in Asio environment
        config (Dict): Configuration parameters loaded from file
        logger (Logger): Logging instance for the application
        
    Methods:
        initialize(): Sets up environment and returns (is_asio, config)
        setup_logging(): Configures logging handlers
        determine_environment(): Detects runtime environment
    """
    PRODUCT_LICENSES = [
        {"ProductName": "Microsoft 365 E1", "StringID": "STANDARDPACK"},
        {"ProductName": "Microsoft 365 E3", "StringID": "SPE_E3"},
        {"ProductName": "Microsoft 365 E5", "StringID": "SPE_E5"},
        {"ProductName": "Microsoft 365 Business Basic", "StringID": "O365_BUSINESS_ESSENTIALS"},
        {"ProductName": "Microsoft 365 Business Standard", "StringID": "O365_BUSINESS_PREMIUM"},
        {"ProductName": "Microsoft 365 Business Premium", "StringID": "SPB"},
        {"ProductName": "Microsoft Defender for Endpoint", "StringID": "DEFENDER_ENDPOINT_P1"},
        {"ProductName": "Power Automate Free", "StringID": "FLOW_FREE"},
        {"ProductName": "Power Automate Premium", "StringID": "POWERAUTOMATE_ATTENDED_RPA"},
        {"ProductName": "Power BI Pro", "StringID": "POWER_BI_PRO"},
        {"ProductName": "Microsoft Teams Essentials", "StringID": "Teams_Ess"},
        {"ProductName": "Exchange Online Plan 1", "StringID": "EXCHANGESTANDARD"},
        {"ProductName": "Exchange Online Plan 2", "StringID": "EXCHANGEENTERPRISE"},
        {"ProductName": "Copilot for Microsoft 365", "StringID": "Microsoft_365_Copilot"}
    ]

    def __init__(self, discord_webhook_url: Optional[str] = None):
        self.running_in_asio = False
        self.config = None
        self.discord_webhook_url = discord_webhook_url
        print(f"Discord webhook URL: {self.discord_webhook_url}")
        from cw_rpa_unified_logger import LoggerType
        self.logging_config = logging_config(discord_webhook_url=self.discord_webhook_url)
        self.logger = self.setup_logging()
        self.configuration_path = Path(__file__).parent.parent.parent.parent / "environments" / "asio_365_config.json"

    def setup_logging(self):
        """Configure logging for the application."""
        unified_logger = UnifiedLogger(self.logging_config)
        return unified_logger
        
    def determine_environment(self) -> bool:
        """Determine and configure the running environment."""
        try:
            print(f"Config file exists: {self.configuration_path}")
            try:
                with open(self.configuration_path, 'r') as f:
                    self.config = json.load(f)
                    print(f"Loaded config: {self.config}")  # Add this line
            except json.JSONDecodeError as e:
                print(f"Failed to parse config file: {str(e)}")  # Add this line
                self.config = None

            # Check for local configuration keys
            if self.config and all(key in self.config for key in ['client_id', 'client_secret', 'tenant_id']):
                self.running_in_asio = False
            else:
                self.running_in_asio = True

        except FileNotFoundError:
            print("Config file not found")  # Add this line
            self.running_in_asio = True

        return self.running_in_asio

    def initialize(self) -> Tuple[bool, Optional[Dict]]:
        """Initialize the environment and return configuration."""
        # Move logger setup after environment determination
        is_asio = self.determine_environment()
        if not hasattr(self, 'logger'):  # Only set up logging if not already done
            self.setup_logging()
        return is_asio, self.config