"""Tests for brand-aware build configuration helpers."""

import json
import sys
from pathlib import Path

BUILD_SCRIPTS_DIR = Path(__file__).resolve().parents[2] / "build" / "scripts"
if str(BUILD_SCRIPTS_DIR) not in sys.path:
    sys.path.insert(0, str(BUILD_SCRIPTS_DIR))

from brand_config import (
    DEFAULT_BRAND_ID,
    collect_local_release_data,
    generate_release_manifest,
    load_brand_config,
    merge_release_manifests,
)


def test_load_agravity_brand_config():
    """Test loading the Agravity brand manifest."""
    brand = load_brand_config("agravity")

    assert brand.brand_id == "agravity"
    assert brand.display_name == "Agravity Bridge"
    assert brand.asset_prefix == "AgravityBridge"
    assert brand.exe_name == "AgravityBridge"
    assert brand.toolbar_icon_home == "resources/icons/home.ico"
    assert brand.toolbar_icon_reload == "resources/icons/reload.ico"
    assert brand.toolbar_icon_open == "resources/icons/open.ico"
    assert brand.toolbar_icon_openwith == "resources/icons/openwith.ico"
    assert brand.windows_installer_name("0.8.4") == "AgravityBridge-0.8.4-win-x64.msi"


def test_generate_release_manifest_for_agravity(tmp_path):
    """Test generating a shared release manifest from local artifacts."""
    project_root = tmp_path
    (project_root / "build" / "brands").mkdir(parents=True)
    (project_root / "build" / "dist" / "windows" / "agravity").mkdir(parents=True)
    (project_root / "build" / "dist" / "macos" / "agravity").mkdir(parents=True)

    source_manifest = Path(__file__).resolve().parents[2] / "build" / "brands" / "agravity.json"
    (project_root / "build" / "brands" / "agravity.json").write_text(
        source_manifest.read_text(encoding="utf-8"),
        encoding="utf-8",
    )

    win_installer = (
        project_root
        / "build"
        / "dist"
        / "windows"
        / "agravity"
        / "AgravityBridge-0.8.4-win-x64.msi"
    )
    win_installer.write_bytes(b"msi")
    (win_installer.parent / f"{win_installer.name}.sha256").write_text("abc", encoding="utf-8")

    mac_installer = (
        project_root
        / "build"
        / "dist"
        / "macos"
        / "agravity"
        / "AgravityBridge-0.8.4-macos-universal.dmg"
    )
    mac_installer.write_bytes(b"dmg")
    (mac_installer.parent / f"{mac_installer.name}.sha256").write_text("def", encoding="utf-8")

    output_path = project_root / "build" / "dist" / "release-manifest.json"
    generate_release_manifest(
        "0.8.4",
        ["agravity"],
        output_path=output_path,
        root=project_root,
    )

    manifest = json.loads(output_path.read_text(encoding="utf-8"))
    assert manifest["version"] == "0.8.4"
    assert (
        manifest["brands"]["agravity"]["windows-x64"]["installer"]
        == "AgravityBridge-0.8.4-win-x64.msi"
    )
    assert (
        manifest["brands"]["agravity"]["macos-universal"]["installer"]
        == "AgravityBridge-0.8.4-macos-universal.dmg"
    )


def test_collect_local_release_data_includes_default_brand(tmp_path):
    """Test discovering local artifacts for the default Windows build."""
    project_root = tmp_path
    installer_dir = project_root / "build" / "dist" / "windows" / DEFAULT_BRAND_ID
    installer_dir.mkdir(parents=True)

    installer = installer_dir / "WebDropBridge-0.8.4-win-x64.msi"
    installer.write_bytes(b"msi")
    checksum = installer_dir / f"{installer.name}.sha256"
    checksum.write_text("abc", encoding="utf-8")

    data = collect_local_release_data("0.8.4", platform="windows", root=project_root)

    assert data["brands"] == [DEFAULT_BRAND_ID]
    assert str(installer) in data["artifacts"]
    assert str(checksum) in data["artifacts"]
    assert (
        data["manifest"]["brands"][DEFAULT_BRAND_ID]["windows-x64"]["installer"] == installer.name
    )


def test_merge_release_manifests_preserves_existing_platforms():
    """Test merging platform-specific manifest entries from separate upload runs."""
    base_manifest = {
        "version": "0.8.4",
        "channel": "stable",
        "brands": {
            "agravity": {
                "windows-x64": {
                    "installer": "AgravityBridge-0.8.4-win-x64.msi",
                    "checksum": "AgravityBridge-0.8.4-win-x64.msi.sha256",
                }
            }
        },
    }
    overlay_manifest = {
        "version": "0.8.4",
        "channel": "stable",
        "brands": {
            "agravity": {
                "macos-universal": {
                    "installer": "AgravityBridge-0.8.4-macos-universal.dmg",
                    "checksum": "AgravityBridge-0.8.4-macos-universal.dmg.sha256",
                }
            }
        },
    }

    merged = merge_release_manifests(base_manifest, overlay_manifest)

    assert (
        merged["brands"]["agravity"]["windows-x64"]["installer"]
        == "AgravityBridge-0.8.4-win-x64.msi"
    )
    assert (
        merged["brands"]["agravity"]["macos-universal"]["installer"]
        == "AgravityBridge-0.8.4-macos-universal.dmg"
    )
