# Copyright © 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.

"""Decorate 'test' command."""

import sys
from pathlib import Path
from typing import Any, override

from django.conf import settings
from django.core.management import CommandParser
from django.core.management.commands import test

from debusine.django.django_utils import cleanup_temp_directory


class Command(test.Command):
    """Decorate 'test' command."""

    @override
    def add_arguments(self, parser: CommandParser) -> None:
        """Register new --keepdata option, similar to --keepdb."""
        super().add_arguments(parser)
        parser.add_argument(
            "--keepdata",
            action="store_true",
            help="Preserves the test data directory between runs.",
        )

    @override
    def handle(self, *args: Any, **kwargs: Any) -> None:
        """Clean-up or keep temporary test directories hierarchy."""
        try:
            super().handle(*args, **kwargs)
        finally:
            data_path = Path(settings.DEBUSINE_DATA_PATH)
            if kwargs["keepdata"]:
                if kwargs["verbosity"] >= 1:
                    sys.stderr.write(
                        f"Preserving test data directory "
                        f"{str(data_path)!r}...\n"
                    )
            else:
                cleanup_temp_directory()
