from __future__ import annotations

import json

from django.core.management.base import BaseCommand, CommandError

from core.memory.search_backend import get_memory_search_backend


class Command(BaseCommand):
    help = "Run a query against configured memory search backend."

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

    def handle(self, *args, **options):
        user_id_raw = str(options.get("user_id") or "").strip()
        query = str(options.get("query") or "").strip()
        conversation_id = str(options.get("conversation_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 20))
        as_json = bool(options.get("json"))

        if not user_id_raw:
            raise CommandError("--user-id is required")
        if not query:
            raise CommandError("--query is required")

        backend = get_memory_search_backend()
        hits = backend.search(
            user_id=int(user_id_raw),
            query=query,
            conversation_id=conversation_id,
            limit=limit,
            include_statuses=statuses,
        )
        payload = {
            "backend": getattr(backend, "name", "unknown"),
            "query": query,
            "user_id": int(user_id_raw),
            "conversation_id": conversation_id,
            "statuses": statuses,
            "count": len(hits),
            "hits": [
                {
                    "memory_id": item.memory_id,
                    "score": item.score,
                    "summary": item.summary,
                    "payload": item.payload,
                }
                for item in hits
            ],
        }
        if as_json:
            self.stdout.write(json.dumps(payload, indent=2, sort_keys=True))
            return
        self.stdout.write(
            f"memory-search-query backend={payload['backend']} count={payload['count']} query={query!r}"
        )
        for row in payload["hits"]:
            self.stdout.write(
                f"- id={row['memory_id']} score={row['score']:.2f} summary={row['summary'][:120]}"
            )
