"""Seed AI assistant conversation history across the demo user pool.

Creates Conversation + Message + ToolCall rows. Tool calls reference real
Document / GrantCall IDs via ``surfaced_object_ids`` so the surfaced-result
links resolve.
"""

from __future__ import annotations

import random
from datetime import timedelta

from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from django.utils import timezone

from apps.core.assistant.models import Conversation, Message, ToolCall
from apps.core.seeders.volumes import RECORD_COUNTS

User = get_user_model()

USER_PROMPTS = [
    "Summarise the climate adaptation policy briefs published in 2024.",
    "Which grant calls are open for women researchers in agribusiness?",
    "Find me datasets on maize yields across East Africa.",
    "What's the disbursement status for award #A-2024-15?",
    "Show recent SME-Hub graduates from the SP4 showcase cohort.",
    "Compare publication output between alumni in Ghana and Kenya.",
    "Walk me through how to submit a grant application.",
    "Are there any pending KYC steps on my profile?",
    "Summarise this month's M&EL indicator variances.",
    "Suggest a course on grant writing for early-career researchers.",
]
ASSISTANT_REPLIES = [
    "Here's a summary of the policy briefs from 2024 along with key recommendations.",
    "There are five open grant calls matching that filter — I've pinned the top three.",
    "I found two harmonised datasets and one country-level survey. Want full details?",
    "Award #A-2024-15 has two pending disbursements; the most recent was approved yesterday.",
    "Eight SP4 alumni qualify; here are their pitch decks and current investor introductions.",
    "Ghana and Kenya have similar publication volume (≈42 vs 47 papers/year). Citations diverge.",
    "Start in the Grants section, choose an open call, then complete the eligibility checklist.",
    "Your profile is fully verified. No KYC actions required at this time.",
    "Six AR-series indicators are amber and one is red. The red one is AR010 — let me explain.",
    "I'd recommend the Grant Writing Essentials course — it has a high completion rate.",
]
TOOL_NAMES = ["search_documents", "lookup_grant", "summarise_award", "list_courses", "fetch_indicator"]


def _real_object_ids() -> dict[str, list[str]]:
    """Snapshot real Document and GrantCall IDs to use as surfaced_object_ids."""
    out: dict[str, list[str]] = {"document": [], "grant_call": []}
    try:
        from apps.repository.documents.models import Document
        out["document"] = [str(pk) for pk in Document.objects.values_list("pk", flat=True)[:50]]
    except Exception:  # noqa: BLE001
        pass
    try:
        from apps.rims.grants.models import GrantCall
        out["grant_call"] = [str(pk) for pk in GrantCall.objects.values_list("pk", flat=True)[:25]]
    except Exception:  # noqa: BLE001
        pass
    return out


class Command(BaseCommand):
    help = "Seed assistant Conversation / Message / ToolCall history."

    def add_arguments(self, parser):
        parser.add_argument(
            "--volume",
            choices=("minimal", "demo", "heavy"),
            default="demo",
        )

    def handle(self, *args, **opts):
        tier = opts["volume"]
        counts = RECORD_COUNTS[tier]
        target = counts["conversations"]
        msgs_per = counts["messages_per_conv"]
        random.seed(2026)

        users = list(User.objects.filter(is_active=True).order_by("?")[:max(target // 3, 1)])
        if not users:
            self.stdout.write(self.style.WARNING("No users — cannot seed assistant."))
            return

        object_pool = _real_object_ids()

        created_convs = 0
        created_msgs = 0
        created_tools = 0
        now = timezone.now()

        for i in range(target):
            owner = random.choice(users)
            title = random.choice(USER_PROMPTS).rsplit("?", 1)[0][:80]
            existing = Conversation.objects.filter(user=owner, title=title).first()
            if existing:
                conv = existing
            else:
                conv = Conversation.objects.create(user=owner, title=title)
                created_convs += 1

            # Backdate the conversation.
            Conversation.objects.filter(pk=conv.pk).update(
                created_at=now - timedelta(days=random.randint(0, 60)),
            )

            existing_msgs = Message.objects.filter(conversation=conv).count()
            for j in range(existing_msgs, msgs_per + random.randint(-1, 3)):
                role = Message.Role.USER if j % 2 == 0 else Message.Role.ASSISTANT
                content = (
                    random.choice(USER_PROMPTS)
                    if role == Message.Role.USER
                    else random.choice(ASSISTANT_REPLIES)
                )
                msg = Message.objects.create(
                    conversation=conv,
                    role=role,
                    content=content,
                )
                created_msgs += 1

                if role == Message.Role.ASSISTANT and random.random() < 0.35:
                    tool_name = random.choice(TOOL_NAMES)
                    if tool_name == "search_documents":
                        ids = random.sample(object_pool["document"], k=min(3, len(object_pool["document"]))) if object_pool["document"] else []
                    elif tool_name in ("lookup_grant", "summarise_award"):
                        ids = random.sample(object_pool["grant_call"], k=min(2, len(object_pool["grant_call"]))) if object_pool["grant_call"] else []
                    else:
                        ids = []
                    ToolCall.objects.create(
                        message=msg,
                        name=tool_name,
                        arguments={"q": content[:120]},
                        result_preview=f"{tool_name} returned {len(ids)} items.",
                        surfaced_object_ids=ids,
                    )
                    created_tools += 1

        self.stdout.write(self.style.SUCCESS(
            f"Assistant: conversations={created_convs} messages={created_msgs} "
            f"tool_calls={created_tools} (tier={tier})"
        ))
