from __future__ import annotations

from django.core.management.base import BaseCommand


class Command(BaseCommand):
    help = "Seed the Repository module with sample collections, documents, and analytics events."

    def add_arguments(self, parser):
        parser.add_argument(
            "--documents",
            type=int,
            default=None,
            help="Number of sample documents to generate. Defaults from --volume.",
        )
        parser.add_argument(
            "--events",
            type=int,
            default=None,
            help="Analytics events per published document. Defaults from --volume.",
        )
        parser.add_argument(
            "--volume",
            choices=("minimal", "demo", "heavy"),
            default="demo",
            help="Per-tier defaults — overridden by explicit --documents/--events.",
        )

    def handle(self, *args, **options):
        from apps.core.seeders.volumes import RECORD_COUNTS
        from apps.repository.analytics.seeders.analytics_seeder import seed as seed_analytics
        from apps.repository.documents.models import Document
        from apps.repository.documents.seeders.documents_seeder import seed as seed_documents
        from apps.repository.search.indexes import update_search_vector

        tier_counts = RECORD_COUNTS[options["volume"]]
        documents = options["documents"] if options["documents"] is not None else tier_counts["documents"]
        events = options["events"] if options["events"] is not None else tier_counts["events_per_doc"]
        search_queries = tier_counts["search_queries"]

        summary_docs = seed_documents(count=documents)
        summary_analytics = seed_analytics(events_per_doc=events, distinct_queries=search_queries)

        # Build FTS search_vectors synchronously — guarantees seeded documents
        # are immediately searchable without needing a running Celery worker.
        indexed = 0
        for doc_id in Document.objects.values_list("id", flat=True):
            if update_search_vector(doc_id):
                indexed += 1

        self.stdout.write(self.style.SUCCESS(f"Documents: {summary_docs}"))
        self.stdout.write(self.style.SUCCESS(f"Analytics: {summary_analytics}"))
        self.stdout.write(self.style.SUCCESS(f"Search index built: {indexed} documents"))
