from __future__ import annotations

import json

from django.core.management.base import BaseCommand

from core.memory.search_backend import get_memory_search_backend


class Command(BaseCommand):
    help = "Reindex MemoryItem rows into the configured memory search backend."

    def add_arguments(self, parser):
        parser.add_argument("--user-id", default="")
        parser.add_argument("--statuses", default="active")
        parser.add_argument("--limit", type=int, default=2000)
        parser.add_argument("--json", action="store_true", default=False)

    def handle(self, *args, **options):
        user_id_raw = str(options.get("user_id") or "").strip()
        statuses = tuple(
            item.strip().lower()
            for item in str(options.get("statuses") or "active").split(",")
            if item.strip()
        )
        limit = max(1, int(options.get("limit") or 2000))
        as_json = bool(options.get("json"))

        backend = get_memory_search_backend()
        result = backend.reindex(
            user_id=int(user_id_raw) if user_id_raw else None,
            include_statuses=statuses,
            limit=limit,
        )
        payload = {
            "backend": getattr(backend, "name", "unknown"),
            "user_id": user_id_raw,
            "statuses": statuses,
            "limit": limit,
            "result": result,
        }
        if as_json:
            self.stdout.write(json.dumps(payload, indent=2, sort_keys=True))
            return
        self.stdout.write(
            f"memory-search-reindex backend={payload['backend']} "
            f"user={user_id_raw or '-'} statuses={','.join(statuses) or '-'} "
            f"scanned={int(result.get('scanned') or 0)} indexed={int(result.get('indexed') or 0)}"
        )
