"""
SQS Feature - AWS SQS Queue Support

This module provides support for analyzing Python code that uses iicy.SQSQueueConfig
constructs and generating the corresponding CloudFormation resources using the
generic feature factory system.

This implementation uses the generic feature factory system, which:
- Automatically handles AST analysis for finding resource instantiations
- Automatically creates configuration instances with validation
- Uses strategy pattern for property mapping and output generation
- Provides seamless variable reference resolution
"""

from typing import Dict, Any
from ..infra.infra_feature import InfraFeature
from ...models.cloudformation import SQSQueueProperties, CloudFormationTemplate, Resource
from ...models.context import GenerationStageContext

class SQSFeature(InfraFeature):
    CLOUDFORMATION_TYPE = 'AWS::SQS::Queue'


    def discover(self, context):
        """Discover SQS queue configurations"""
        from ...queue import SQSQueueConfig
        return self._discover_instances(context, SQSQueueConfig)
    

    def generate(self, context: GenerationStageContext) -> Dict[str, CloudFormationTemplate]:
        """Generate CloudFormation resources for SQS queues."""
        # Get discovered configs for this feature
        feature_name = self.__class__.__name__
        instances = []
        for config_type_name, config_list in context.feature_configs.get(feature_name, {}).items():
            instances.extend(config_list)

        stacks = {}

        for config in instances:
            stack_name = getattr(config, 'stack', 'IICYStack')
            name_value = self._get_name_value(config)
            # Convert name to valid CloudFormation resource name (alphanumeric only)
            sanitized_name = name_value.replace('-', '').replace('_', '')
            resource_name = f"{sanitized_name}Queue"

            properties = self.map_properties(config)

            if stack_name not in stacks:
                stacks[stack_name] = CloudFormationTemplate(
                    description=f"CloudFormation template for stack {stack_name}",
                    resources={},
                    outputs={}
                )

            # Create resource using Pydantic model
            resource = Resource(
                logical_id=resource_name,
                type=self.CLOUDFORMATION_TYPE,
                properties=properties
            )
            stacks[stack_name].resources[resource_name] = resource

            # Generate outputs using Pydantic models
            outputs = self.generate_outputs(config, resource_name)
            stacks[stack_name].outputs.update(outputs)

        return stacks

    def map_properties(self, config) -> SQSQueueProperties:
        queue_name = config.name
        
        if config.fifo:
            if not config.name.endswith('.fifo'):
                queue_name = f"{config.name}.fifo"
            
            return SQSQueueProperties(
                QueueName=queue_name,
                FifoQueue=True,
                ContentBasedDeduplication=True
            )
        else:
            # For standard queues, don't include FifoQueue property at all
            return SQSQueueProperties(
                QueueName=queue_name
            )
