import importlib
import sys
from pathlib import Path

from django import setup
from django.contrib.staticfiles.management.commands.collectstatic import Command
from hatchling.builders.hooks.plugin.interface import BuildHookInterface


class DjangoCollectstaticBuildHook(BuildHookInterface):
    PLUGIN_NAME = "django-collectstatic"

    def initialize(self, version, build_data):
        from django.conf import settings

        sys.path.insert(0, str(Path(self.root) / "src"))
        project_settings = importlib.import_module(self.config["settings"])

        settings.configure(
            INSTALLED_APPS=project_settings.INSTALLED_APPS,
            STATIC_ROOT=self.config.get("output-directory", "static"),
            STATIC_URL=project_settings.STATIC_URL,
        )
        setup()
        collectstatic_command = Command()
        collectstatic_command.handle(
            interactive=False,
            verbosity=1,
            link=False,
            clear=False,
            dry_run=False,
            ignore_patterns=[],
            use_default_ignore_patterns=True,
            post_process=True,
        )
