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

class SNSSubscriptionFeature(InfraFeature):
    CLOUDFORMATION_TYPE = 'AWS::SNS::Subscription'

    def discover(self, context):
        """Discover SNS subscription configurations"""
        return self._discover_instances(context, SNSSubscription)

    def generate(self, context: GenerationStageContext) -> Dict[str, CloudFormationTemplate]:
        """Generate CloudFormation resources for SNS subscriptions."""
        # 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)
            resource_name = f"{name_value}Subscription"

            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):
        """Map config to SNS subscription properties"""
        if hasattr(config, 'to_cloudformation_properties'):
            return config.to_cloudformation_properties()
        # Fallback to basic properties
        return {
            "Protocol": config.protocol,
            "Endpoint": config.endpoint,
            "TopicArn": config.topic_arn
        }

