from __future__ import annotations

import json

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

from core.memory.pipeline import suggest_memories_from_recent_messages


class Command(BaseCommand):
    help = "Suggest proposed MemoryItem rows from recent inbound message text."

    def add_arguments(self, parser):
        parser.add_argument("--user-id", required=True)
        parser.add_argument("--limit-messages", type=int, default=300)
        parser.add_argument("--max-items", type=int, default=30)
        parser.add_argument("--json", action="store_true", default=False)

    def handle(self, *args, **options):
        user_id_raw = str(options.get("user_id") or "").strip()
        if not user_id_raw:
            raise CommandError("--user-id is required")
        limit_messages = max(1, int(options.get("limit_messages") or 300))
        max_items = max(1, int(options.get("max_items") or 30))
        as_json = bool(options.get("json"))

        result = suggest_memories_from_recent_messages(
            user_id=int(user_id_raw),
            limit_messages=limit_messages,
            max_items=max_items,
        )
        payload = {
            "user_id": int(user_id_raw),
            "limit_messages": limit_messages,
            "max_items": max_items,
            "result": result,
        }
        if as_json:
            self.stdout.write(json.dumps(payload, indent=2, sort_keys=True))
            return
        self.stdout.write(
            "memory-suggest-from-messages "
            f"user={payload['user_id']} "
            f"scanned={int(result.get('scanned') or 0)} "
            f"queued={int(result.get('queued') or 0)}"
        )
