from rest_framework import serializers
from igny8_core.business.content.models import Content
from igny8_core.business.optimization.models import OptimizationTask


class OptimizeContentSerializer(serializers.Serializer):
    """Serializer for optimizing content"""
    content_id = serializers.IntegerField(required=True)
    entry_point = serializers.ChoiceField(
        choices=['auto', 'writer', 'wordpress', 'external', 'manual'],
        default='auto',
        required=False
    )
    
    def validate_content_id(self, value):
        try:
            content = Content.objects.get(id=value)
            account = self.context['request'].user.account if hasattr(self.context['request'].user, 'account') else None
            if account and content.account != account:
                raise serializers.ValidationError("Content not found or access denied")
            return value
        except Content.DoesNotExist:
            raise serializers.ValidationError("Content not found")


class BatchOptimizeContentSerializer(serializers.Serializer):
    """Serializer for batch optimization"""
    content_ids = serializers.ListField(
        child=serializers.IntegerField(),
        min_length=1,
        max_length=20
    )
    entry_point = serializers.ChoiceField(
        choices=['auto', 'writer', 'wordpress', 'external', 'manual'],
        default='auto',
        required=False
    )


class OptimizationResultSerializer(serializers.ModelSerializer):
    """Serializer for optimization results"""
    content_title = serializers.CharField(source='content.title', read_only=True)
    content_id = serializers.IntegerField(source='content.id', read_only=True)
    
    class Meta:
        model = OptimizationTask
        fields = [
            'id',
            'content_id',
            'content_title',
            'scores_before',
            'scores_after',
            'status',
            'credits_used',
            'created_at',
            'updated_at',
        ]
        read_only_fields = fields


class AnalyzeContentSerializer(serializers.Serializer):
    """Serializer for content analysis (preview only)"""
    content_id = serializers.IntegerField(required=True)
    
    def validate_content_id(self, value):
        try:
            content = Content.objects.get(id=value)
            account = self.context['request'].user.account if hasattr(self.context['request'].user, 'account') else None
            if account and content.account != account:
                raise serializers.ValidationError("Content not found or access denied")
            return value
        except Content.DoesNotExist:
            raise serializers.ValidationError("Content not found")

