"""
Management command to load default library type configurations.

Idempotent — safe to re-run. Creates Library nodes with default content-type
configurations if they don't already exist. Does NOT overwrite existing
libraries that have been customized.
"""

import logging

from django.core.management.base import BaseCommand

from library.content_types import LIBRARY_TYPE_DEFAULTS

logger = logging.getLogger(__name__)


class Command(BaseCommand):
    help = (
        "Load default library type configurations into Neo4j. "
        "Creates one Library node per type with default chunking, embedding, "
        "reranker, and LLM context settings. Safe to re-run."
    )

    def add_arguments(self, parser):
        parser.add_argument(
            "--force",
            action="store_true",
            help="Update existing libraries with default configurations (overwrites customizations)",
        )

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

        try:
            from library.models import Library
        except Exception as e:
            self.stderr.write(
                self.style.ERROR(f"Cannot import library models: {e}")
            )
            return

        created_count = 0
        updated_count = 0
        skipped_count = 0

        for library_type, config in LIBRARY_TYPE_DEFAULTS.items():
            display_name = library_type.capitalize()
            default_name = f"Default {display_name} Library"

            # Check if a library of this type already exists
            existing = Library.nodes.filter(library_type=library_type)

            if existing:
                if force:
                    lib = existing[0]
                    lib.chunking_config = config["chunking_config"]
                    lib.embedding_instruction = config["embedding_instruction"]
                    lib.reranker_instruction = config["reranker_instruction"]
                    lib.llm_context_prompt = config["llm_context_prompt"]
                    lib.save()
                    updated_count += 1
                    self.stdout.write(
                        self.style.WARNING(f"Updated: {lib.name} ({library_type})")
                    )
                else:
                    skipped_count += 1
                    self.stdout.write(
                        self.style.NOTICE(
                            f"Skipped: {existing[0].name} ({library_type}) — already exists"
                        )
                    )
            else:
                lib = Library(
                    name=default_name,
                    library_type=library_type,
                    description=f"Default {display_name.lower()} library",
                    chunking_config=config["chunking_config"],
                    embedding_instruction=config["embedding_instruction"],
                    reranker_instruction=config["reranker_instruction"],
                    llm_context_prompt=config["llm_context_prompt"],
                )
                lib.save()
                created_count += 1
                self.stdout.write(
                    self.style.SUCCESS(f"Created: {default_name} ({library_type})")
                )

        self.stdout.write(
            self.style.SUCCESS(
                f"\nDone. Created: {created_count}, "
                f"Updated: {updated_count}, Skipped: {skipped_count}"
            )
        )
