# Generated by Django 6.0.2 on 2026-02-23

from django.db import migrations, models


def populate_activity_session_count(apps, schema_editor):
    """Backfill session_count on WeeklyActivity and DailyActivity from Session.created_at.

    For each session with a created_at timestamp, increments session_count on the
    corresponding daily and weekly activity rows (both per-project and global).
    Only counts real sessions (type="session"), not subagents.
    """
    from collections import Counter
    from datetime import timedelta

    Session = apps.get_model("core", "Session")
    WeeklyActivity = apps.get_model("core", "WeeklyActivity")
    DailyActivity = apps.get_model("core", "DailyActivity")

    # Count sessions per project per day and per week
    # { (project_id, date): count }
    daily_counts = Counter()
    weekly_counts = Counter()

    sessions = Session.objects.filter(
        created_at__isnull=False,
        type="session",
    ).values_list("project_id", "created_at")

    for project_id, created_at in sessions.iterator(chunk_size=1000):
        day = created_at.date()
        monday = day - timedelta(days=day.weekday())

        # Per-project
        daily_counts[(project_id, day)] += 1
        weekly_counts[(project_id, monday)] += 1
        # Global
        daily_counts[(None, day)] += 1
        weekly_counts[(None, monday)] += 1

    # Apply to DailyActivity
    for (project_id, day), count in daily_counts.items():
        filters = {"date": day}
        if project_id is None:
            filters["project__isnull"] = True
        else:
            filters["project_id"] = project_id

        updated = DailyActivity.objects.filter(**filters).update(
            session_count=models.F("session_count") + count
        )
        if not updated:
            DailyActivity.objects.create(
                project_id=project_id, date=day, session_count=count,
            )

    # Apply to WeeklyActivity
    for (project_id, monday), count in weekly_counts.items():
        filters = {"date": monday}
        if project_id is None:
            filters["project__isnull"] = True
        else:
            filters["project_id"] = project_id

        updated = WeeklyActivity.objects.filter(**filters).update(
            session_count=models.F("session_count") + count
        )
        if not updated:
            WeeklyActivity.objects.create(
                project_id=project_id, date=monday, session_count=count,
            )


class Migration(migrations.Migration):

    dependencies = [
        ("core", "0033_add_session_created_at"),
    ]

    operations = [
        migrations.AddField(
            model_name="weeklyactivity",
            name="session_count",
            field=models.PositiveIntegerField(default=0),
        ),
        migrations.AddField(
            model_name="dailyactivity",
            name="session_count",
            field=models.PositiveIntegerField(default=0),
        ),
        migrations.RunPython(populate_activity_session_count, migrations.RunPython.noop),
    ]
