"""
Management command to embed a single Item via the CLI.

Usage:
    python manage.py embed_item <item_uid>
    python manage.py embed_item <item_uid> --sync
"""

import logging

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

logger = logging.getLogger(__name__)


class Command(BaseCommand):
    help = "Run the embedding pipeline for a single Item."

    def add_arguments(self, parser):
        parser.add_argument("item_uid", type=str, help="UID of the Item to embed")
        parser.add_argument(
            "--sync",
            action="store_true",
            help="Run synchronously instead of queueing a Celery task",
        )

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

        # Verify item exists
        try:
            from library.models import Item

            item = Item.nodes.get(uid=item_uid)
        except Exception as exc:
            raise CommandError(f"Item not found: {item_uid} ({exc})")

        self.stdout.write(f"Item: {item.title} (type={item.file_type}, status={item.embedding_status})")

        if sync:
            self.stdout.write("Running embedding pipeline synchronously...")
            from library.services.pipeline import EmbeddingPipeline

            pipeline = EmbeddingPipeline()

            def progress_cb(percent, message):
                self.stdout.write(f"  [{percent:3d}%] {message}")

            try:
                result = pipeline.process_item(item_uid, progress_callback=progress_cb)
                self.stdout.write(
                    self.style.SUCCESS(
                        f"\nCompleted: {result.get('chunks_created', 0)} chunks, "
                        f"{result.get('images_stored', 0)} images, "
                        f"{result.get('concepts_extracted', 0)} concepts"
                    )
                )
            except Exception as exc:
                raise CommandError(f"Embedding failed: {exc}")
        else:
            self.stdout.write("Queueing embedding task...")
            from library.tasks import embed_item

            task = embed_item.delay(item_uid)
            self.stdout.write(
                self.style.SUCCESS(f"Task queued: {task.id}")
            )
