from django.core.management import BaseCommand, CommandError

from basicknowledge.models import BasicKnowledge
from books.models import Module
from core.convert_page_translation import (
    AlreadyTranslatedException,
    PageDoesNotExistException,
    convert_page_to_translation,
)

EN = "en"
FR = "fr"


class Command(BaseCommand):
    """
    usage: `python manage.py migrate_translation  --model module --slug slug --original original_slug --language 'en'`
    """

    def add_arguments(self, parser):
        parser.add_argument("--slug", type=str, required=True)
        parser.add_argument("--original", type=str, required=True)
        parser.add_argument("--language", type=str, choices=[EN, FR], default=EN)
        parser.add_argument(
            "--model", type=str, choices=["instrument", "module"], default="instrument"
        )

    def handle(self, *_, **options):
        slug = options.get("slug")
        original_slug = options.get("original")
        language_code = options.get("language")
        model = options.get("model")

        if model == "instrument":
            page_model = BasicKnowledge
        elif model == "module":
            page_model = Module
        else:
            raise CommandError(f"Unknown model: {model}")

        try:
            result = convert_page_to_translation(
                page_model,
                slug=slug,
                original_slug=original_slug,
                language_code=language_code,
            )
            self.stdout.write(result)
        except PageDoesNotExistException as e:
            raise CommandError(f"{page_model} does not exist: {e}")
        except AlreadyTranslatedException:
            raise CommandError(
                f"Pages {model} {slug} and {original_slug} already are translations of each other"
            )
