"""
Management command to show search index statistics.

Usage:
    python manage.py search_stats
"""

import logging

from django.core.management.base import BaseCommand

logger = logging.getLogger(__name__)


class Command(BaseCommand):
    help = "Show search index statistics from Neo4j."

    def handle(self, *args, **options):
        try:
            from neomodel import db
        except Exception as exc:
            self.stderr.write(self.style.ERROR(f"Cannot import neomodel: {exc}"))
            return

        self.stdout.write(self.style.HTTP_INFO("Mnemosyne Search Index Statistics"))
        self.stdout.write("=" * 50)

        # Node counts
        self.stdout.write(self.style.MIGRATE_HEADING("\nNode Counts:"))
        for label in [
            "Library", "Collection", "Item", "Chunk",
            "Concept", "Image", "ImageEmbedding",
        ]:
            try:
                results, _ = db.cypher_query(f"MATCH (n:{label}) RETURN count(n)")
                count = results[0][0] if results else 0
                self.stdout.write(f"  {label:20s} {count:>8,d}")
            except Exception as exc:
                self.stdout.write(f"  {label:20s} ERROR: {exc}")

        # Embedded chunks
        self.stdout.write(self.style.MIGRATE_HEADING("\nEmbedding Coverage:"))
        try:
            results, _ = db.cypher_query(
                "MATCH (c:Chunk) "
                "RETURN count(c) AS total, "
                "       count(CASE WHEN c.embedding IS NOT NULL THEN 1 END) AS embedded"
            )
            total = results[0][0] if results else 0
            embedded = results[0][1] if results else 0
            pct = (embedded / total * 100) if total > 0 else 0
            self.stdout.write(f"  Chunks total:      {total:>8,d}")
            self.stdout.write(f"  Chunks embedded:   {embedded:>8,d} ({pct:.1f}%)")
        except Exception as exc:
            self.stdout.write(f"  Error: {exc}")

        try:
            results, _ = db.cypher_query(
                "MATCH (ie:ImageEmbedding) RETURN count(ie)"
            )
            count = results[0][0] if results else 0
            self.stdout.write(f"  Image embeddings:  {count:>8,d}")
        except Exception:
            pass

        # Indexes
        self.stdout.write(self.style.MIGRATE_HEADING("\nIndexes:"))
        try:
            results, _ = db.cypher_query(
                "SHOW INDEXES YIELD name, type, labelsOrTypes, properties, state "
                "RETURN name, type, labelsOrTypes, properties, state "
                "ORDER BY type, name"
            )
            for row in results:
                name, idx_type, labels, props, state = row
                labels_str = ", ".join(labels) if labels else "?"
                props_str = ", ".join(props) if props else "?"
                state_style = self.style.SUCCESS if state == "ONLINE" else self.style.WARNING
                self.stdout.write(
                    f"  {name:35s} {idx_type:12s} {labels_str}({props_str}) "
                    f"[{state_style(state)}]"
                )
        except Exception as exc:
            self.stdout.write(f"  Error listing indexes: {exc}")

        # Relationship counts
        self.stdout.write(self.style.MIGRATE_HEADING("\nRelationship Counts:"))
        for rel_type in [
            "CONTAINS", "BELONGS_TO", "HAS_CHUNK", "HAS_IMAGE",
            "HAS_EMBEDDING", "MENTIONS", "REFERENCES", "DEPICTS",
            "RELATED_TO", "HAS_NEARBY_IMAGE",
        ]:
            try:
                results, _ = db.cypher_query(
                    f"MATCH ()-[r:{rel_type}]->() RETURN count(r)"
                )
                count = results[0][0] if results else 0
                if count > 0:
                    self.stdout.write(f"  {rel_type:20s} {count:>8,d}")
            except Exception:
                pass

        # System models
        self.stdout.write(self.style.MIGRATE_HEADING("\nSystem Models:"))
        try:
            from llm_manager.models import LLMModel

            for name, getter in [
                ("Embedding", LLMModel.get_system_embedding_model),
                ("Chat", LLMModel.get_system_chat_model),
                ("Reranker", LLMModel.get_system_reranker_model),
                ("Vision", LLMModel.get_system_vision_model),
            ]:
                model = getter()
                if model:
                    self.stdout.write(
                        f"  {name:12s} {self.style.SUCCESS(model.name)} "
                        f"({model.api.name})"
                    )
                else:
                    self.stdout.write(
                        f"  {name:12s} {self.style.WARNING('Not configured')}"
                    )
        except Exception as exc:
            self.stdout.write(f"  Error loading models: {exc}")

        self.stdout.write("")
