"""
Management command: close_inactive_chats

Finds active chat sessions where the last message is older than
tenant.chat_inactivity_minutes, sends a farewell message, then closes
the session.

Usage:
    python manage.py close_inactive_chats
    python manage.py close_inactive_chats --dry-run

Schedule via cron (every 5 minutes):
    */5 * * * * cd /path/to/project && python manage.py close_inactive_chats
"""
from django.core.management.base import BaseCommand
from django.utils import timezone
from datetime import timedelta

from apps.chat.models import ChatSession, ChatMessage


class Command(BaseCommand):
    help = 'Close inactive chat sessions and send a farewell message.'

    def add_arguments(self, parser):
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='Print sessions that would be closed without actually closing them.',
        )

    def handle(self, *args, **options):
        from apps.ftlink.models import JobRun
        dry_run = options['dry_run']
        now = timezone.now()
        closed = 0

        active_sessions = (
            ChatSession.objects
            .filter(status=ChatSession.STATUS_ACTIVE)
            .select_related('tenant')
            .prefetch_related('messages')
        )

        for session in active_sessions:
            timeout_minutes = getattr(session.tenant, 'chat_inactivity_minutes', 30) or 30
            threshold = now - timedelta(minutes=timeout_minutes)

            last_msg = session.messages.order_by('-created_at').first()
            last_activity = last_msg.created_at if last_msg else session.created_at

            if last_activity >= threshold:
                continue  # still active

            if dry_run:
                idle_mins = int((now - last_activity).total_seconds() / 60)
                self.stdout.write(
                    f'[DRY RUN] Would close session {session.session_id.hex[:8]} '
                    f'(idle {idle_mins}m, tenant: {session.tenant.name})'
                )
            else:
                farewell = (
                    getattr(session.tenant, 'chat_farewell_message', '') or
                    "Thank you for contacting us, I'll be happy to help you at your return, have a good one!"
                )
                ChatMessage.objects.create(
                    session=session,
                    role=ChatMessage.ROLE_ASSISTANT,
                    content=farewell,
                )
                session.status = ChatSession.STATUS_CLOSED
                session.save(update_fields=['status'])
                self.stdout.write(f'Closed session {session.session_id.hex[:8]}')

            closed += 1

        label = 'Would close' if dry_run else 'Closed'
        self.stdout.write(self.style.SUCCESS(f'{label} {closed} inactive session(s).'))
        if not dry_run:
            JobRun.record('close_inactive_chats', note=f'{closed} closed')
