# Generated by Django 6.0.2 on 2026-02-22

from django.db import migrations, models


def recompute_weekly_activity(apps, schema_editor):
    """Recompute WeeklyActivity excluding subagent sessions.

    The original migration (0028) and live increment did not filter by session
    type, so subagent user messages were incorrectly counted. This migration
    clears all existing rows and recomputes from scratch, only counting
    user_message items from sessions with type="session".
    """
    from django.db.models import Count
    from django.db.models.functions import TruncWeek

    SessionItem = apps.get_model("core", "SessionItem")
    WeeklyActivity = apps.get_model("core", "WeeklyActivity")

    # Clear all existing rows
    WeeklyActivity.objects.all().delete()

    # Recompute from SessionItem, filtering for session type="session" only
    rows = (
        SessionItem.objects.filter(
            kind="user_message",
            timestamp__isnull=False,
            session__type="session",
        )
        .values(
            project_id=models.F("session__project_id"),
            week_start=TruncWeek("timestamp"),
        )
        .annotate(count=Count("id"))
    )

    global_counts = {}  # week -> count
    to_create = []

    for row in rows:
        week = row["week_start"].date()
        project_id = row["project_id"]
        count = row["count"]

        to_create.append(
            WeeklyActivity(project_id=project_id, week=week, count=count)
        )

        global_counts[week] = global_counts.get(week, 0) + count

    for week, count in global_counts.items():
        to_create.append(WeeklyActivity(project=None, week=week, count=count))

    if to_create:
        WeeklyActivity.objects.bulk_create(to_create)


def recompute_daily_activity(apps, schema_editor):
    """Recompute DailyActivity excluding subagent sessions.

    The original migration (0029) and live increment did not filter by session
    type, so subagent user messages were incorrectly counted. This migration
    clears all existing rows and recomputes from scratch, only counting
    user_message items from sessions with type="session".
    """
    from django.db.models import Count
    from django.db.models.functions import TruncDate

    SessionItem = apps.get_model("core", "SessionItem")
    DailyActivity = apps.get_model("core", "DailyActivity")

    # Clear all existing rows
    DailyActivity.objects.all().delete()

    # Recompute from SessionItem, filtering for session type="session" only
    rows = (
        SessionItem.objects.filter(
            kind="user_message",
            timestamp__isnull=False,
            session__type="session",
        )
        .values(
            project_id=models.F("session__project_id"),
            day=TruncDate("timestamp"),
        )
        .annotate(count=Count("id"))
    )

    global_counts = {}  # date -> count
    to_create = []

    for row in rows:
        day = row["day"]
        if hasattr(day, "date"):
            day = day.date()
        project_id = row["project_id"]
        count = row["count"]

        to_create.append(
            DailyActivity(project_id=project_id, date=day, count=count)
        )

        global_counts[day] = global_counts.get(day, 0) + count

    for day, count in global_counts.items():
        to_create.append(DailyActivity(project=None, date=day, count=count))

    if to_create:
        DailyActivity.objects.bulk_create(to_create)


class Migration(migrations.Migration):

    dependencies = [
        ('core', '0029_add_daily_activity'),
    ]

    operations = [
        migrations.RunPython(recompute_weekly_activity, migrations.RunPython.noop),
        migrations.RunPython(recompute_daily_activity, migrations.RunPython.noop),
    ]
