from rest_framework.serializers import CharField, ModelSerializer, SerializerMethodField

from apps.accounts.serializers import OrganizationSerializer, RoleSerializer, UserSerializer
from apps.onboarding.models import AgentConfig, AgentInteractionLog, OnboardingFlow, OnboardingSession

class AgentConfigSerializer(ModelSerializer):
    organization = OrganizationSerializer(read_only=True)
    role = RoleSerializer(read_only=True)

    class Meta:
        model = AgentConfig
        fields = [
            'id', 'uuid', 'organization', 'role', 'name', 'agent_type', 
            'system_prompt', 'llm_config',
            'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'uuid', 'created_at', 'updated_at']

class AgentInteractionLogSerializer(ModelSerializer):
    agent_name = CharField(source='agent_config.name', read_only=True)

    class Meta:
        model = AgentInteractionLog
        fields = [
            'id', 'uuid', 'session', 'agent_config', 'agent_name', 
            'sender_type', 'content', 'tool_call_metadata', 'created_at'
        ]
        read_only_fields = ['id', 'uuid', 'created_at']

class OnboardingSessionSerializer(ModelSerializer):
    user = UserSerializer(read_only=True)
    role = RoleSerializer(read_only=True)
    flow = SerializerMethodField()
    logs = AgentInteractionLogSerializer(many=True, read_only=True)
    progress_percentage = SerializerMethodField()

    class Meta:
        model = OnboardingSession
        fields = [
            'id', 'uuid', 'user', 'role', 'flow', 'status', 'state', 
            'active_configs', 'logs', 'completed_at', 'created_at', 
            'updated_at', 'progress_percentage'
        ]
        read_only_fields = ['id', 'uuid', 'user', 'completed_at', 'created_at', 'updated_at']

    def get_progress_percentage(self, obj: OnboardingSession) -> int:
        return obj.state.get('progress_percentage', 0)

    def get_flow(self, obj: OnboardingSession):
        if not obj.flow:
            return None
        return {
            'uuid': str(obj.flow.uuid),
            'title': obj.flow.title,
            'is_active': obj.flow.is_active,
        }

class OnboardingFlowSerializer(ModelSerializer):
    role = RoleSerializer(read_only=True)
    session_count = SerializerMethodField()
    pages = SerializerMethodField()
    description = SerializerMethodField()

    class Meta:
        model = OnboardingFlow
        fields = ['id', 'uuid', 'title', 'role', 'is_active', 'description', 'pages', 'session_count', 'created_at']
        read_only_fields = ['id', 'uuid', 'created_at']

    def get_session_count(self, obj: OnboardingFlow) -> int:
        return obj.role.onboarding_sessions.count()

    def get_pages(self, obj: OnboardingFlow):
        return obj.structure or []

    def get_description(self, obj: OnboardingFlow) -> str:
        return ''
