"""
Management command to display embedding pipeline status and statistics.

Usage:
    python manage.py embedding_status
    python manage.py embedding_status --library <uid>
"""

import logging

from django.core.management.base import BaseCommand

logger = logging.getLogger(__name__)


class Command(BaseCommand):
    help = "Display embedding pipeline status and statistics."

    def add_arguments(self, parser):
        parser.add_argument(
            "--library",
            type=str,
            default="",
            help="Filter by library UID",
        )

    def handle(self, *args, **options):
        library_uid = options["library"]

        try:
            from neomodel import db
        except ImportError:
            self.stderr.write(self.style.ERROR("neomodel not available"))
            return

        self.stdout.write(self.style.HTTP_INFO("\n=== Mnemosyne Embedding Pipeline Status ===\n"))

        # System embedding model
        try:
            from llm_manager.models import LLMModel

            embed_model = LLMModel.get_system_embedding_model()
            if embed_model:
                self.stdout.write(
                    f"System Embedding Model: {embed_model.api.name}: {embed_model.name} "
                    f"(dimensions={embed_model.vector_dimensions or '?'})"
                )
            else:
                self.stdout.write(
                    self.style.WARNING("System Embedding Model: NOT CONFIGURED")
                )

            chat_model = LLMModel.get_system_chat_model()
            if chat_model:
                self.stdout.write(f"System Chat Model: {chat_model.api.name}: {chat_model.name}")
            else:
                self.stdout.write(
                    self.style.WARNING("System Chat Model: NOT CONFIGURED (concept extraction disabled)")
                )
        except Exception as exc:
            self.stdout.write(self.style.ERROR(f"Could not query LLM models: {exc}"))

        self.stdout.write("")

        # Item status counts
        try:
            statuses = ["pending", "processing", "completed", "failed"]
            self.stdout.write("Item Embedding Status:")

            for status in statuses:
                if library_uid:
                    query = (
                        "MATCH (l:Library {uid: $lib_uid})-[:CONTAINS]->(c:Collection)"
                        "-[:CONTAINS]->(i:Item {embedding_status: $status}) "
                        "RETURN count(i)"
                    )
                    results, _ = db.cypher_query(
                        query, {"lib_uid": library_uid, "status": status}
                    )
                else:
                    query = (
                        "MATCH (i:Item {embedding_status: $status}) RETURN count(i)"
                    )
                    results, _ = db.cypher_query(query, {"status": status})

                count = results[0][0] if results else 0
                style = {
                    "completed": self.style.SUCCESS,
                    "failed": self.style.ERROR,
                    "processing": self.style.WARNING,
                    "pending": self.style.NOTICE,
                }.get(status, str)
                self.stdout.write(f"  {status:12s}: {style(str(count))}")
        except Exception as exc:
            self.stdout.write(self.style.ERROR(f"Could not query items: {exc}"))

        self.stdout.write("")

        # Node counts
        try:
            node_types = [
                ("Library", "Library"),
                ("Collection", "Collection"),
                ("Item", "Item"),
                ("Chunk", "Chunk"),
                ("Concept", "Concept"),
                ("Image", "Image"),
                ("ImageEmbedding", "ImageEmbedding"),
            ]
            self.stdout.write("Graph Node Counts:")
            for label, display in node_types:
                results, _ = db.cypher_query(f"MATCH (n:{label}) RETURN count(n)")
                count = results[0][0] if results else 0
                self.stdout.write(f"  {display:20s}: {count}")
        except Exception as exc:
            self.stdout.write(self.style.ERROR(f"Could not query nodes: {exc}"))

        # Chunks with embeddings
        try:
            results, _ = db.cypher_query(
                "MATCH (c:Chunk) WHERE c.embedding IS NOT NULL RETURN count(c)"
            )
            embedded = results[0][0] if results else 0
            results, _ = db.cypher_query("MATCH (c:Chunk) RETURN count(c)")
            total = results[0][0] if results else 0
            self.stdout.write(
                f"\nChunks with embeddings: {embedded}/{total}"
            )
        except Exception:
            pass

        self.stdout.write("")
