from __future__ import annotations

from django.core.management import call_command
from django.test import TestCase

from core.models import (
    ChatSession,
    Message,
    Person,
    PersonIdentifier,
    User,
    WorkspaceMetricSnapshot,
)
from core.views.workspace import _conversation_for_person


class ReconcileWorkspaceMetricHistoryCommandTests(TestCase):
    def setUp(self):
        self.user = User.objects.create_user(
            "reconcile-user",
            "reconcile@example.com",
            "x",
        )
        self.person = Person.objects.create(user=self.user, name="Reconcile Person")
        self.identifier = PersonIdentifier.objects.create(
            user=self.user,
            person=self.person,
            service="whatsapp",
            identifier="15551230000@s.whatsapp.net",
        )
        self.session = ChatSession.objects.create(
            user=self.user, identifier=self.identifier
        )
        base_ts = 1_700_000_000_000
        for idx in range(10):
            inbound = idx % 2 == 0
            Message.objects.create(
                user=self.user,
                session=self.session,
                ts=base_ts + (idx * 60_000),
                text=f"m{idx}",
                source_service="whatsapp",
                source_chat_id="120363402761690215@g.us",
                sender_uuid=f"actor-{idx}@s.whatsapp.net",
                custom_author="OTHER" if inbound else "USER",
            )

    def test_reconcile_builds_checkpoints_and_no_reset_is_idempotent(self):
        call_command(
            "reconcile_workspace_metric_history",
            "--person-id",
            str(self.person.id),
            "--service",
            "whatsapp",
            "--days",
            "36500",
            "--step-messages",
            "2",
            "--skip-compact",
        )
        conversation = _conversation_for_person(self.user, self.person)
        first_count = WorkspaceMetricSnapshot.objects.filter(
            conversation=conversation
        ).count()
        self.assertGreaterEqual(first_count, 5)

        call_command(
            "reconcile_workspace_metric_history",
            "--person-id",
            str(self.person.id),
            "--service",
            "whatsapp",
            "--days",
            "36500",
            "--step-messages",
            "2",
            "--no-reset",
            "--skip-compact",
        )
        second_count = WorkspaceMetricSnapshot.objects.filter(
            conversation=conversation
        ).count()
        self.assertEqual(first_count, second_count)
        latest = conversation.metric_snapshots.first()
        self.assertEqual(5, int(latest.inbound_messages or 0))
        self.assertEqual(5, int(latest.outbound_messages or 0))

    def test_no_reset_does_not_duplicate_when_messages_share_timestamp(self):
        Message.objects.all().delete()
        base_ts = 1_700_100_000_000
        for idx in range(8):
            inbound = idx % 2 == 0
            Message.objects.create(
                user=self.user,
                session=self.session,
                ts=base_ts + ((idx // 2) * 60_000),
                text=f"d{idx}",
                source_service="whatsapp",
                source_chat_id="120363402761690215@g.us",
                sender_uuid=f"dup-{idx}@s.whatsapp.net",
                custom_author="OTHER" if inbound else "USER",
            )

        call_command(
            "reconcile_workspace_metric_history",
            "--person-id",
            str(self.person.id),
            "--service",
            "whatsapp",
            "--days",
            "36500",
            "--step-messages",
            "2",
            "--skip-compact",
        )
        conversation = _conversation_for_person(self.user, self.person)
        first_count = WorkspaceMetricSnapshot.objects.filter(
            conversation=conversation
        ).count()

        call_command(
            "reconcile_workspace_metric_history",
            "--person-id",
            str(self.person.id),
            "--service",
            "whatsapp",
            "--days",
            "36500",
            "--step-messages",
            "2",
            "--no-reset",
            "--skip-compact",
        )
        second_count = WorkspaceMetricSnapshot.objects.filter(
            conversation=conversation
        ).count()
        self.assertEqual(first_count, second_count)

    def test_reconcile_compacts_historical_snapshots_by_age_bucket(self):
        call_command(
            "reconcile_workspace_metric_history",
            "--person-id",
            str(self.person.id),
            "--service",
            "whatsapp",
            "--days",
            "36500",
            "--step-messages",
            "1",
        )
        conversation = _conversation_for_person(self.user, self.person)
        count_after_compact = WorkspaceMetricSnapshot.objects.filter(
            conversation=conversation
        ).count()
        self.assertGreaterEqual(count_after_compact, 1)
        self.assertLess(count_after_compact, 10)
