# Standard Library
import os
from pathlib import Path

# Django
from django.core.management.base import BaseCommand

# Third party
import polib

# Project
# Local
from django_deepl_po.utils import (
    PO_FILE_EXTENSION,
    PO_FILE_NAME,
    get_all_languages,
    get_apps_name,
    get_locale_path,
)


class Command(BaseCommand):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.apps_name = get_apps_name()
        self.languages = get_all_languages()

    help = (
        "Delete obsolete translations from PO files. "
        "Operates on specified Django apps and languages."
    )

    def add_arguments(self, parser):
        parser.add_argument(
            "--app",
            choices=self.apps_name,
            default=self.apps_name,
            nargs="*",
            help="Specify which app(s) to clean. Defaults to all apps.",
        )
        parser.add_argument(
            "--language",
            choices=self.languages,
            default=self.languages,
            nargs="*",
            help="Specify which language(s) to clean. Defaults to all languages.",
        )

    def handle(self, *args, **kwargs):
        apps_to_check = kwargs.get("app", self.apps_name)
        languages_to_check = kwargs.get("language", self.languages)

        self.stdout.write(
            self.style.SUCCESS("\nStarting to delete obsolete translations...\n")
        )

        for app in apps_to_check:
            try:
                locale_path = get_locale_path(app)

                if not Path(locale_path).exists():
                    self.stdout.write(
                        self.style.WARNING(f"No locale folder found for app: {app}")
                    )
                    continue

                for lang in languages_to_check:
                    po_file_path = os.path.join(
                        locale_path,
                        lang,
                        "LC_MESSAGES",
                        f"{PO_FILE_NAME}{PO_FILE_EXTENSION}",
                    )

                    if not Path(po_file_path).exists():
                        self.stdout.write(
                            self.style.WARNING(
                                f"PO file not found for '{lang}' in app '{app}'"
                            )
                        )
                        continue

                    po_file = polib.pofile(po_file_path)
                    obsolete_entries = po_file.obsolete_entries()

                    if not obsolete_entries:
                        continue

                    count = len(obsolete_entries)
                    for entry in obsolete_entries:
                        po_file.remove(entry)

                    po_file.save()
                    self.stdout.write(
                        self.style.SUCCESS(
                            f"Deleted {count} obsolete translation(s) "
                            f"from {app} ({lang})"
                        )
                    )

            except Exception as e:
                self.stdout.write(self.style.ERROR(f"Error processing app {app}: {e}"))

        self.stdout.write(
            self.style.SUCCESS("\nObsolete translation deletion completed!\n")
        )
