from pathlib import Path
import pytest
from categorizer import CategoryRecord, FixtureClass, Speed
from batcher import Batch, plan

def _rec(name: str, fc: FixtureClass, bg: str = "core") -> CategoryRecord:
 return CategoryRecord(
  filename=name,
  fixture_class=fc,
  subsystems=[bg] if bg else [],
  speed=Speed.MEDIUM,
  batch_group=bg,
 )

def test_plan_groups_unit_by_batch_group() -> None:
 records = [
  _rec("test_a.py", FixtureClass.UNIT, "core"),
  _rec("test_b.py", FixtureClass.UNIT, "gui"),
  _rec("test_c.py", FixtureClass.UNIT, "core"),
 ]
 batches = plan(records)
 unit_batches = [b for b in batches if b.tier == "1"]
 labels = {b.label for b in unit_batches}
 assert "tier-1-unit-core" in labels
 assert "tier-1-unit-gui" in labels

def test_plan_live_gui_tier_is_one_batch() -> None:
 records = [
  _rec("test_a_sim.py", FixtureClass.LIVE_GUI, "gui"),
  _rec("test_b_sim.py", FixtureClass.LIVE_GUI, "core"),
  _rec("test_c_sim.py", FixtureClass.LIVE_GUI, "mma"),
 ]
 batches = plan(records)
 live_batches = [b for b in batches if b.tier == "3"]
 assert len(live_batches) == 1
 assert len(live_batches[0].files) == 3

def test_plan_opt_in_skipped_without_flag() -> None:
 records = [
  _rec("test_clean_install.py", FixtureClass.OPT_IN),
  _rec("test_docker_build.py", FixtureClass.OPT_IN),
 ]
 batches = plan(records, include_opt_in=False)
 opt_batches = [b for b in batches if b.tier == "0"]
 assert all(b.skip_reason for b in opt_batches)

def test_plan_is_deterministic() -> None:
 records = [
  _rec("test_a.py", FixtureClass.UNIT, "core"),
  _rec("test_b.py", FixtureClass.UNIT, "gui"),
 ]
 a = plan(records)
 b = plan(records)
 assert [(x.tier, x.label, len(x.files)) for x in a] == [(y.tier, y.label, len(y.files)) for y in b]

def test_plan_xdist_only_for_tier_1() -> None:
 records = [_rec("test_a.py", FixtureClass.UNIT, "core")]
 batches = plan(records, xdist=True)
 unit = next(b for b in batches if b.tier == "1")
 assert "-n" in unit.pytest_args
 assert "auto" in unit.pytest_args
 mock_records = [_rec("test_a.py", FixtureClass.MOCK_APP, "core")]
 batches2 = plan(mock_records, xdist=True)
 mock = next(b for b in batches2 if b.tier == "2")
 assert "-n" not in mock.pytest_args
