# Copyright 2024 The Debusine Developers
# See the AUTHORS file at the top-level directory of this distribution
#
# This file is part of Debusine. It is subject to the license terms
# in the LICENSE file found in the top-level directory of this
# distribution. No part of Debusine, including this file, may be copied,
# modified, propagated, or distributed except according to the terms
# contained in the LICENSE file.

"""debusine-admin command to create collections."""

import argparse

from django.core.management import CommandError
from django.db import IntegrityError

from debusine.db.models import Collection, DEFAULT_WORKSPACE_NAME, Workspace
from debusine.server.management.debusine_base_command import DebusineBaseCommand


class Command(DebusineBaseCommand):
    """Command to create a collection."""

    help = "Create a new collection"

    def add_arguments(self, parser):
        """Add CLI arguments for the create_collection command."""
        parser.add_argument("name", help="Name")
        parser.add_argument("category", help="Category")
        parser.add_argument(
            "--workspace", help="Workspace", default=DEFAULT_WORKSPACE_NAME
        )
        parser.add_argument(
            "--data",
            type=argparse.FileType("r"),
            help=(
                "File path (or - for stdin) to read the data for the "
                "collection. YAML format. Defaults to stdin."
            ),
            default="-",
        )

    def handle(self, *args, **options):
        """Create the collection."""
        name = options["name"]
        category = options["category"]
        workspace_name = options["workspace"]
        data = self.parse_yaml_data(options["data"].read()) or {}

        try:
            workspace = Workspace.objects.get(name=workspace_name)
        except Workspace.DoesNotExist:
            raise CommandError(
                f'Workspace "{workspace_name}" not found', returncode=3
            )

        try:
            Collection.objects.create(
                name=name, category=category, workspace=workspace, data=data
            )
        except IntegrityError:
            raise CommandError(
                "A collection with this name and category already exists",
                returncode=3,
            )

        raise SystemExit(0)
