# Generated by Django 6.0.2 on 2026-02-22 13:51

import django.db.models.deletion
from django.db import migrations, models


def populate_weekly_activity(apps, schema_editor):
    """Populate WeeklyActivity from existing SessionItem data."""
    from datetime import timedelta

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

    # Query all user_message items with timestamps, grouped by project + week
    from django.db.models import Count
    from django.db.models.functions import TruncWeek

    rows = (
        SessionItem.objects.filter(
            kind="user_message",
            timestamp__isnull=False,
        )
        .values(
            project_id=models.F("session__project_id"),
            week_start=TruncWeek("timestamp"),
        )
        .annotate(count=Count("id"))
    )

    # Build per-project and global counts
    global_counts = {}  # week -> count
    to_create = []

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

        # Per-project entry
        to_create.append(
            WeeklyActivity(project_id=project_id, week=week, count=count)
        )

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

    # Global entries (project=NULL)
    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)


class Migration(migrations.Migration):

    dependencies = [
        ('core', '0027_recompute_project_sessions_count'),
    ]

    operations = [
        migrations.CreateModel(
            name='WeeklyActivity',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('week', models.DateField()),
                ('count', models.PositiveIntegerField(default=0)),
                ('project', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='weekly_activities', to='core.project')),
            ],
            options={
                'constraints': [models.UniqueConstraint(fields=('project', 'week'), name='unique_project_week')],
            },
        ),
        migrations.RunPython(populate_weekly_activity, migrations.RunPython.noop),
    ]
