from m365_user_manager.managers.environment_manager import EnvironmentManager
from cw_rpa import HttpClient, Input
from typing import Any, Optional
import json

class InputProcessor:
    """
    Processes and validates input parameters from Input form.
    
    Handles input processing logic for form inputs, providing consistent 
    parameter formatting.
    
    Usage:
        processor = InputProcessor()
        kwargs, error = processor.process_input()
        
    Methods:
        process_input(): Processes form inputs
        
    Returns:
        tuple[dict[str, Any], Optional[str]]: Processed parameters and error message
    """
    def __init__(self, discord_webhook_url: str = None):
        self.discord_webhook_url = discord_webhook_url
        self.logger = EnvironmentManager(discord_webhook_url=self.discord_webhook_url).setup_logging()
        try:
            self.input_form = Input()
            self.http_client = HttpClient()
            self.integration_name = "azure_o365"
        except Exception as e:
            self.logger.error(f"Failed to initialize Input: {str(e)}")
            raise

    def process_input(self) -> tuple[dict[str, Any], Optional[str]]:
        """Process input from form."""
        try:
            self.logger.info("Starting to process input form")

            # Process license SKUs - handle as list
            try:
                license_skus = self.input_form.get_value("LicenseSKUs_1737154745588")
                self.logger.debug(f"Raw license SKUs: {license_skus}")
                if isinstance(license_skus, list):
                    license_skus = ','.join(license_skus)
            except Exception as e:
                self.logger.error(f"Error processing license SKUs: {str(e)}")
                license_skus = None

            # Process Groups - handle as list
            try:
                groups = self.input_form.get_value("Groups_1737154746910")
                self.logger.debug(f"Raw groups: {groups}")
                if isinstance(groups, list):
                    groups = ','.join(groups)
            except Exception as e:
                self.logger.error(f"Error processing groups: {str(e)}")
                groups = None

            # Process copy_licenses flag
            try:
                copy_licenses = self.input_form.get_value("CopyLicenses_1737159741637")
                if not copy_licenses:
                    copy_licenses = False
                if isinstance(copy_licenses, str):
                    copy_licenses = copy_licenses.lower() == 'yes'
            except Exception as e:
                self.logger.error(f"Error processing copy_licenses flag: {str(e)}")
                copy_licenses = False

            # Build kwargs dictionary
            try:
                kwargs = {
                    'display_name': self.input_form.get_value("DisplayName_1737154608192"),
                    'email_address': self.input_form.get_value("EmailAddress_1737154657850"),
                    'password': self.input_form.get_value("Password_1737154656469"),
                    'job_title': self.input_form.get_value("JobTitle_1737154733788"),
                    'department': self.input_form.get_value("Department_1737154731291"),
                    'office_location': self.input_form.get_value("OfficeLocation_1737154659481"),
                    'city': self.input_form.get_value("City_1737154742161"),
                    'state': self.input_form.get_value("State_1737154743922"),
                    'business_phone': self.input_form.get_value("BusinessPhone_1737154735784"),
                    'mobile_phone': self.input_form.get_value("MobilePhone_1737154737302"),
                    'groups': groups,
                    'license_skus': license_skus,
                    'user_to_copy': self.input_form.get_value("UserToCopy_1737154748715"),
                    'copy_licenses': copy_licenses
                }
            except Exception as e:
                self.logger.error(f"Error building kwargs dictionary: {str(e)}")
                return {}, f"Failed to process input form: {str(e)}"

            # Log processed parameters
            self.logger.info(f"Processed input parameters: {json.dumps(kwargs, indent=2)}")

            # Validate required fields
            if not kwargs['display_name'] or not kwargs['email_address']:
                return kwargs, "Required fields missing: display name and email address"

            return kwargs, None

        except Exception as e:
            self.logger.error(f"Failed to process input: {str(e)}")
            return {}, (f"Failed to process input: {str(e)}")
          
