"""Seed synthetic Access / Download / Search events for the last 12 months."""

from __future__ import annotations

import logging
import random
from datetime import timedelta

from django.utils import timezone

logger = logging.getLogger(__name__)


_QUERIES = [
    "climate adaptation", "maize yield", "smallholder", "post-harvest loss",
    "agroforestry", "policy brief", "dataset", "youth employment", "gender",
    "drought", "soil health", "remote sensing", "value chain", "livestock",
    "agribusiness", "irrigation", "food security", "nutrition", "extension",
    "biotechnology", "cassava", "coffee", "carbon markets", "digital agriculture",
    "rural finance", "agroecology", "seed systems", "land use",
]


def seed(events_per_doc: int = 25, distinct_queries: int | None = None) -> dict:
    from apps.core.countries import to_country_name
    from apps.repository.analytics.models import AccessEvent, DownloadEvent, SearchEvent
    from apps.repository.documents.models import Document

    docs = list(Document.objects.filter(status=Document.Status.PUBLISHED))
    if not docs:
        return {"documents": 0, "access_events": 0, "download_events": 0, "search_events": 0}

    now = timezone.now()
    countries = ["UG", "KE", "TZ", "RW", "ET", "ZA", "GH", "NG", "SN", "CM", "MW", "ZW"]
    access_created = 0
    download_created = 0

    # Bulk-create AccessEvent + DownloadEvent rows with explicit timestamps
    # to avoid 1 round-trip per row (heavy volume = ~48k rows).
    access_rows: list[AccessEvent] = []
    download_rows: list[DownloadEvent] = []
    for doc in docs:
        for _ in range(events_per_doc):
            ts = now - timedelta(days=random.randint(0, 365), hours=random.randint(0, 23))
            access_rows.append(AccessEvent(
                document=doc,
                ip_address=f"10.{random.randint(0, 255)}.{random.randint(0, 255)}.{random.randint(1, 254)}",
                country=to_country_name(random.choice(countries)),
                timestamp=ts,
            ))
            access_created += 1
            if random.random() < 0.4:
                download_rows.append(DownloadEvent(
                    document=doc,
                    country=to_country_name(random.choice(countries)),
                    timestamp=ts,
                ))
                download_created += 1
            if len(access_rows) >= 500:
                AccessEvent.objects.bulk_create(access_rows, batch_size=500)
                access_rows = []
            if len(download_rows) >= 500:
                DownloadEvent.objects.bulk_create(download_rows, batch_size=500)
                download_rows = []
    if access_rows:
        AccessEvent.objects.bulk_create(access_rows, batch_size=500)
    if download_rows:
        DownloadEvent.objects.bulk_create(download_rows, batch_size=500)

    queries = _QUERIES if distinct_queries is None else _QUERIES[:max(1, distinct_queries)]
    search_rows: list[SearchEvent] = []
    search_created = 0
    for q in queries:
        for _ in range(random.randint(3, 12)):
            ts = now - timedelta(days=random.randint(0, 365))
            search_rows.append(SearchEvent(
                query=q,
                filters={},
                result_count=random.randint(0, 12),
                timestamp=ts,
            ))
            search_created += 1
    if search_rows:
        SearchEvent.objects.bulk_create(search_rows, batch_size=500)

    return {
        "documents": len(docs),
        "access_events": access_created,
        "download_events": download_created,
        "search_events": search_created,
    }
