from django.core.management.base import BaseCommand
from calls.models import Call
from conversations.models import Conversation, Memory, ConversationInsight
from calls.tasks import extract_and_store_memories, generate_insights


class Command(BaseCommand):
    help = 'Generate memories and insights for conversations that are missing them'

    def add_arguments(self, parser):
        parser.add_argument(
            '--call-id',
            type=int,
            help='Process specific call ID',
        )
        parser.add_argument(
            '--all',
            action='store_true',
            help='Process all completed calls',
        )

    def handle(self, *args, **options):
        if options['call_id']:
            calls = Call.objects.filter(id=options['call_id'])
        elif options['all']:
            calls = Call.objects.filter(twilio_status='completed')
        else:
            # Default: process calls that have conversations but no memories or insights
            calls_with_conversations = Call.objects.filter(
                twilio_status='completed',
                conversation__isnull=False
            )
            
            calls_to_process = []
            for call in calls_with_conversations:
                conversation = call.conversation
                has_memories = Memory.objects.filter(conversation=conversation).exists()
                has_insights = ConversationInsight.objects.filter(senior=call.senior).exists()
                
                if not has_memories or not has_insights:
                    calls_to_process.append(call)
            
            calls = calls_to_process

        self.stdout.write(f'Processing {len(calls)} calls...')

        for call in calls:
            try:
                conversation = call.conversation
                if not conversation:
                    self.stdout.write(f'No conversation found for call {call.id}')
                    continue

                self.stdout.write(f'Processing call {call.id} ({call.senior.name})...')

                # Generate memories
                memory_count_before = Memory.objects.filter(conversation=conversation).count()
                extract_and_store_memories(call.senior, conversation, conversation.summary)
                memory_count_after = Memory.objects.filter(conversation=conversation).count()
                memories_created = memory_count_after - memory_count_before

                # Generate insights
                insight_count_before = ConversationInsight.objects.filter(senior=call.senior).count()
                generate_insights(call.senior, conversation)
                insight_count_after = ConversationInsight.objects.filter(senior=call.senior).count()
                insights_created = insight_count_after - insight_count_before

                self.stdout.write(
                    self.style.SUCCESS(
                        f'Call {call.id}: Created {memories_created} memories, {insights_created} insights'
                    )
                )

            except Exception as e:
                self.stdout.write(
                    self.style.ERROR(f'Error processing call {call.id}: {str(e)}')
                )

        self.stdout.write(self.style.SUCCESS('Memory and insight generation completed!'))

