# 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.all_languages = get_all_languages()

    help = (
        "Clean up PO files by removing entries with empty msgid fields. "
        "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. If not provided, cleans all apps.",
        )
        parser.add_argument(
            "--language",
            choices=self.all_languages,
            default=self.all_languages,
            nargs="*",
            help="Specify which language(s) to clean. If not provided, cleans all languages.",
        )

    def handle(self, *args, **kwargs):
        apps_to_clean = kwargs.get("app") or self.apps_name
        langs_to_clean = kwargs.get("language") or get_all_languages()

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

                if not os.path.isdir(locale_path):
                    self.stdout.write(
                        self.style.WARNING(f"Skipping {app}: app directory not found")
                    )
                    continue

                for lang in langs_to_clean:
                    po_file_path = os.path.join(
                        locale_path,
                        lang,
                        "LC_MESSAGES",
                        f"{PO_FILE_NAME}{PO_FILE_EXTENSION}",
                    )
                    if Path(po_file_path).exists():
                        try:
                            po = polib.pofile(po_file_path)
                            entries_to_remove = [e for e in po if e.msgid == ""]
                            if entries_to_remove:
                                for entry in entries_to_remove:
                                    po.remove(entry)
                                po.save(po_file_path)
                                self.stdout.write(
                                    self.style.SUCCESS(
                                        f"Cleaned empty translations in {po_file_path}"
                                    )
                                )
                        except Exception as e:
                            self.stdout.write(
                                self.style.ERROR(f"Error cleaning {po_file_path}: {e}")
                            )
                    else:
                        self.stdout.write(
                            self.style.WARNING(f"PO file not found: {po_file_path}")
                        )

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

        self.stdout.write(self.style.SUCCESS("\nCleaning completed!"))
