# Standard Library
import os
import re
from pathlib import Path

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

# Project
# Local
from django_deepl_po.utils import (
    BACKUP_FILE_NAME,
    PO_FILE_EXTENSION,
    extract_timestamp_from_filename,
    get_all_languages,
    get_apps_name,
    get_locale_path,
    is_valid_timestamp,
)


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

    help = "Deletes backups. By default removes all backups. Use --keep_today to keep today's backups."
    suppressed_base_arguments = [
        "--verbosity",
        "--settings",
        "--pythonpath",
        "--traceback",
        "--no-color",
        "--force-color",
        "--skip-checks",
        "--version",
    ]

    def add_arguments(self, parser):
        parser.add_argument(
            "--keep_today",
            action="store_true",
            help="Keep backups made today.",
        )

    def handle(self, *args, **kwargs):
        keep_today = kwargs.get("keep_today", False)
        language_to_check = get_all_languages()

        self.stdout.write(
            self.style.SUCCESS("\nChecking backup files for Django apps...\n")
        )

        for app in self.apps_name:
            try:
                locale_path = get_locale_path(app)
                if not Path(locale_path).exists():
                    continue

                for lang in language_to_check:
                    lc_messages_path = os.path.join(locale_path, lang, "LC_MESSAGES")
                    if not os.path.isdir(lc_messages_path):
                        continue

                    for file in os.listdir(lc_messages_path):
                        file = file.strip()
                        backup_file_pattern = (
                            f"^{re.escape(BACKUP_FILE_NAME)}_\\d+"
                            f"{re.escape(PO_FILE_EXTENSION)}$"
                        )
                        if re.fullmatch(backup_file_pattern, file):
                            file_timestamp = extract_timestamp_from_filename(file)
                            file_path = os.path.join(lc_messages_path, file)

                            if not file_timestamp or not is_valid_timestamp(
                                file_timestamp
                            ):
                                continue
                            if keep_today and self._is_today(file_timestamp):
                                continue

                            try:
                                Path(file_path).unlink()
                                self.stdout.write(
                                    self.style.SUCCESS(f"Deleted: {file_path}")
                                )
                            except Exception as e:
                                self.stdout.write(
                                    self.style.ERROR(
                                        f"Failed to delete {file_path}: {e}"
                                    )
                                )
            except Exception as e:
                self.stdout.write(self.style.ERROR(f"Error checking app {app}: {e}"))
                exit(0)

        self.stdout.write(self.style.SUCCESS("Backups processed"))

    def _is_today(self, timestamp_str):
        # Standard Library
        from datetime import datetime

        try:
            ts = int(timestamp_str)
            file_date = datetime.fromtimestamp(ts).date()
            return file_date == datetime.today().date()
        except ValueError:
            return False
