"""Strict completion aggregate cannot report missing/failed/wrong-root success."""
from types import SimpleNamespace

import pytest

from pallet import mask_model_improvement_strict as strict


def complete():
    return {k: dict(state='verified_completed_1000_updates', root_version=v, actual_optimizer_updates=1000)
            for k,v in strict.EXPECTED.items()}


def test_only_all_seven_valid_exact_roots_can_complete():
    assert strict.all_completed(complete())
    assert not strict.all_completed({})
    result=complete(); del result['B1']
    assert not strict.all_completed(result)
    result=complete(); result['B0']['root_version']='v3'
    assert not strict.all_completed(result)
    result=complete(); result['A0']['actual_optimizer_updates']=999
    assert not strict.all_completed(result)
    for state in ('partial_or_not_started_not_complete','failed_not_complete','invalid_evidence_not_complete'):
        result=complete(); result['B1']['state']=state
        assert not strict.all_completed(result)


def test_failed_old_B0_root_cannot_substitute_new_B0():
    with pytest.raises(ValueError, match='Wrong evidence root'):
        strict.assert_root('B0', strict.V3)
    strict.assert_root('B0', strict.V4)


def test_storage_guard_aggregates_failed_and_current_versions(tmp_path, monkeypatch):
    roots=[]
    for n in range(4):
        p=tmp_path/f'v{n+1}';p.mkdir();(p/'evidence').write_bytes(b'x'*8);roots.append(p)
    monkeypatch.setattr(strict.shutil,'disk_usage',lambda _:SimpleNamespace(free=100))
    with pytest.raises(ValueError,match='GLOBAL'):
        strict.global_budget(roots,limit=25,reserve=10)
    assert strict.global_budget(roots,limit=40,reserve=10)['all_versions_bytes']==32
    with pytest.raises(ValueError,match='reserve'):
        strict.global_budget(roots,limit=40,reserve=101)
