"""Tests for runtime branding template management."""

from pathlib import Path

import pytest

from webdrop_bridge.config import Config, ConfigurationError
from webdrop_bridge.core.branding_manager import BrandingManager


def test_builtin_brandings_are_available(tmp_path):
    """Built-in default and Agravity templates should always be available."""
    manager = BrandingManager(base_dir=tmp_path)

    brandings = manager.list_templates()
    template_ids = [template.template_id for template in brandings]

    assert "default" in template_ids
    assert "agravity" in template_ids


def test_active_branding_persists_across_manager_instances(tmp_path):
    """Selected active branding should persist on disk."""
    manager = BrandingManager(base_dir=tmp_path)
    manager.set_active_branding_id("agravity")

    reloaded_manager = BrandingManager(base_dir=tmp_path)

    assert reloaded_manager.get_active_branding_id() == "agravity"


def test_apply_branding_updates_cosmetic_fields_only(tmp_path):
    """Applying a branding template should not overwrite setup-specific values."""
    allowed_root = tmp_path / "allowed"
    allowed_root.mkdir()

    config = Config(
        app_name="WebDrop Bridge",
        app_version="1.0.0",
        log_level="INFO",
        log_file=None,
        allowed_roots=[allowed_root],
        allowed_urls=["example.com"],
        webapp_url="http://localhost:8080",
        window_width=1024,
        window_height=768,
        enable_logging=True,
        active_branding_id="agravity",
    )

    manager = BrandingManager(base_dir=tmp_path)
    manager.apply_to_config(config)

    assert config.active_branding_id == "agravity"
    assert config.app_name == "Agravity Bridge"
    assert config.webapp_url == "http://localhost:8080"
    assert config.allowed_roots == [allowed_root]
    assert config.toolbar_icon_home.endswith("home.ico")


def test_config_from_env_uses_persisted_active_branding(tmp_path, monkeypatch):
    """Config loading should apply the persisted active branding automatically."""
    branding_dir = tmp_path / "branding-state"
    manager = BrandingManager(base_dir=branding_dir)
    manager.set_active_branding_id("agravity")

    monkeypatch.setenv("WEBDROP_BRANDING_DIR", str(branding_dir))

    root = tmp_path / "root"
    root.mkdir()
    env_file = tmp_path / ".env"
    env_file.write_text(f"ALLOWED_ROOTS={root}\n", encoding="utf-8")

    config = Config.from_env(str(env_file))

    assert config.active_branding_id == "agravity"
    assert config.app_name == "Agravity Bridge"
    assert config.get_config_path().name == "config.json"


def test_switching_back_to_default_restores_default_branding(tmp_path):
    """Switching from a custom branding back to default should restore the default name."""
    manager = BrandingManager(base_dir=tmp_path)
    config = Config(
        app_name="WebDrop Bridge",
        app_version="1.0.0",
        log_level="INFO",
        log_file=None,
        allowed_roots=[],
        allowed_urls=[],
        webapp_url="http://localhost:8080",
        enable_logging=True,
        active_branding_id="agravity",
    )

    manager.apply_to_config(config)
    assert config.app_name == "Agravity Bridge"

    config.active_branding_id = "default"
    manager.apply_to_config(config)

    assert config.app_name == "WebDrop Bridge"
    assert config.branding_display_name == "Default"


def test_delete_custom_branding_removes_it(tmp_path):
    """Custom brandings should be removable while built-ins stay protected."""
    manager = BrandingManager(base_dir=tmp_path)
    template = manager.build_template(template_id="Customer B", display_name="Customer B")
    manager.save_template(template)

    assert manager.has_template("customer_b")

    manager.delete_template("customer_b")

    assert not manager.has_template("customer_b")


def test_build_template_preserves_app_and_window_titles(tmp_path):
    """Custom brandings should keep their editable app and window title values."""
    manager = BrandingManager(base_dir=tmp_path)

    template = manager.build_template(
        template_id="Customer C",
        display_name="Customer C",
        app_name="Customer Bridge",
        window_title="Customer Bridge Desktop",
    )

    assert template.app_name == "Customer Bridge"
    assert template.window_title == "Customer Bridge Desktop"


def test_invalid_logo_file_is_rejected(tmp_path):
    """Non-existent logo files should not be accepted for saved brandings."""
    manager = BrandingManager(base_dir=tmp_path)

    with pytest.raises(ConfigurationError):
        manager.build_template(
            template_id="customer_c",
            display_name="Customer C",
            logo_path=str(tmp_path / "missing-logo.png"),
        )


def test_exported_branding_can_be_imported_for_another_user(tmp_path):
    """Exported brandings should be shareable and importable by another user."""
    source_logo = tmp_path / "shared-logo.png"
    source_logo.write_bytes(b"fake-png-data")

    source_manager = BrandingManager(base_dir=tmp_path / "source")
    template = source_manager.build_template(
        template_id="Customer D",
        display_name="Customer D",
        app_name="Customer Bridge",
        window_title="Customer Window",
        logo_path=str(source_logo),
    )
    source_manager.save_template(template)

    export_path = tmp_path / "export" / "customer_d.json"
    source_manager.export_template("customer_d", export_path)

    target_manager = BrandingManager(base_dir=tmp_path / "target")
    imported = target_manager.import_template(export_path)

    assert imported.template_id == "customer_d"
    assert imported.display_name == "Customer D"
    assert imported.app_name == "Customer Bridge"
    assert imported.window_title == "Customer Window"
    assert Path(imported.logo_path).exists()
    assert target_manager.has_template("customer_d")
