from m365_user_manager.managers.environment_manager import EnvironmentManager
from m365_user_manager.utils.input_identifiers import FormFields
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()
    """
    def __init__(self, discord_webhook_url: Optional[str] = None):
        self.discord_webhook_url = discord_webhook_url
        self.logger = EnvironmentManager(discord_webhook_url=self.discord_webhook_url).setup_logging()
        self.input_ids = FormFields()
        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_list_field(self, field_id: str) -> Optional[str]:
        """Process a field that should be handled as a list."""
        try:
            value = self.input_form.get_value(field_id)
            self.logger.debug(f"Raw list field value: {value}")
            if isinstance(value, list):
                return ','.join(value)
            return value
        except Exception as e:
            self.logger.error(f"Error processing list field {field_id}: {str(e)}")
            return None

    def _process_boolean_field(self, field_id: str) -> bool:
        """Process a field that should be handled as a boolean."""
        try:
            value = self.input_form.get_value(field_id)
            if not value:
                return False
            if isinstance(value, str):
                return value.lower() == 'yes'
            return bool(value)
        except Exception as e:
            self.logger.error(f"Error processing boolean field {field_id}: {str(e)}")
            return False

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

            # Process fields according to their type
            field_mapping = self.input_ids.get_field_mapping()
            for field_name, field_id in field_mapping.items():
                if field_id in self.input_ids.list_fields:
                    kwargs[field_name] = self._process_list_field(field_id)
                elif field_id in self.input_ids.boolean_fields:
                    kwargs[field_name] = self._process_boolean_field(field_id)
                else:
                    try:
                        kwargs[field_name] = self.input_form.get_value(field_id)
                    except Exception as e:
                        self.logger.error(f"Error processing field {field_name}: {str(e)}")
                        kwargs[field_name] = None

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

            # Validate required fields
            missing_fields = [
                field_name for field_name, field_id in field_mapping.items()
                if field_id in self.input_ids.required_fields and not kwargs[field_name]
            ]
            
            if missing_fields:
                return kwargs, f"Required fields missing: {', '.join(missing_fields)}"

            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)}"