# Generated by Django 6.0.2 on 2026-02-22

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


def populate_daily_activity(apps, schema_editor):
    """Populate DailyActivity from existing SessionItem data."""
    SessionItem = apps.get_model("core", "SessionItem")
    DailyActivity = apps.get_model("core", "DailyActivity")

    from django.db.models import Count
    from django.db.models.functions import TruncDate

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

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

    for row in rows:
        day = row["day"]
        # TruncDate may return a datetime, convert to date
        if hasattr(day, "date"):
            day = day.date()
        project_id = row["project_id"]
        count = row["count"]

        # Per-project entry
        to_create.append(
            DailyActivity(project_id=project_id, date=day, count=count)
        )

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

    # Global entries (project=NULL)
    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', '0028_add_weekly_activity'),
    ]

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