from pathlib import Path
import importlib

from configtype.jsonconfig import setup_search_paths
from django.test import SimpleTestCase

CONFIG_ROOT = Path(__file__).resolve().parents[3] / "config-smoke"
(CONFIG_ROOT / "ocyan").mkdir(parents=True, exist_ok=True)
(CONFIG_ROOT / "ocyan" / "core.json").write_text(
    '{"settings": {}, "ocyan_plugins": []}\n',
    encoding="utf-8",
)
setup_search_paths(str(CONFIG_ROOT))

SeoPluginConfig = importlib.import_module("ocyan.plugin.seo").SeoPluginConfig
SEO_FILE_BACKEND_SETTINGS = importlib.import_module(
    "ocyan.plugin.seo.entrypoint"
).SEO_FILE_BACKEND_SETTINGS


class SeoPluginConfigTests(SimpleTestCase):
    def test_package_exports_plugin_config_lazily(self):
        self.assertIsNotNone(SeoPluginConfig)
        self.assertEqual(SeoPluginConfig.__name__, "SeoPluginConfig")

    def test_contribute_to_settings_populates_storages_default_backend(self):
        settings = {"USE_TZ": True}

        merged = SeoPluginConfig().contribute_to_settings(settings)

        self.assertIs(merged, settings)
        self.assertEqual(
            merged["STORAGES"]["default"]["BACKEND"], "seo.ville.slugger.SEOStorage"
        )
        self.assertEqual(
            merged["THUMBNAIL_BACKEND"], "seo.ville.sorl.SEOThumbnailBackend"
        )
        self.assertTrue(merged["SEO_VILLE_SLUGGER_ALLOW_COPIES"])

    def test_contribute_to_settings_overrides_existing_default_storage(self):
        settings = {
            "STORAGES": {
                "default": {"BACKEND": "django.core.files.storage.FileSystemStorage"}
            }
        }

        merged = SeoPluginConfig().contribute_to_settings(settings)

        self.assertEqual(
            merged["STORAGES"]["default"]["BACKEND"], "seo.ville.slugger.SEOStorage"
        )

    def test_expected_settings_contract_is_explicit(self):
        self.assertEqual(
            SEO_FILE_BACKEND_SETTINGS,
            {
                "THUMBNAIL_BACKEND": "seo.ville.sorl.SEOThumbnailBackend",
                "THUMBNAIL_STORAGE": "seo.ville.sorl.SEOThumbnailStorage",
                "SEO_VILLE_SLUGGER_ALLOW_COPIES": True,
            },
        )
