"""Tests for CCL backend install (ADR-0023 D10/D11)."""
from __future__ import annotations

from kernbench.ccl.install import (
    linear_rank_to_pe,
    load_ccl_config,
    resolve_algorithm_config,
)
from kernbench.sim_engine.engine import GraphEngine
from kernbench.topology.builder import resolve_topology


def _engine():
    topo = resolve_topology("topology.yaml").topology_obj
    return GraphEngine(topo, enable_data=True), topo


def test_load_ccl_config():
    cfg = load_ccl_config()
    assert "defaults" in cfg
    assert "algorithms" in cfg


def test_resolve_algorithm_config_default():
    cfg = load_ccl_config()
    merged = resolve_algorithm_config(cfg)
    assert merged["algorithm"] == cfg["defaults"]["algorithm"]
    assert "world_size" not in merged or merged["world_size"] >= 1


def test_linear_rank_to_pe():
    engine, topo = _engine()
    spec = topo.spec
    assert linear_rank_to_pe(0, spec) == (0, 0, 0)
    assert linear_rank_to_pe(7, spec) == (0, 0, 7)
    pes_per_sip = (
        spec["sip"]["cube_mesh"]["w"] * spec["sip"]["cube_mesh"]["h"]
        * spec["cube"]["pe_layout"]["pe_per_corner"]
        * len(spec["cube"]["pe_layout"]["corners"])
    )
    sips = spec["system"]["sips"]["count"]
    total = sips * pes_per_sip
    assert total >= 8
