"""Publication-12 activation preserves foreign configuration and prior evidence."""
import json
import pytest
from scripts import publish_mask_remaining_round2 as publication


def test_unresolved_atomic_write_is_never_discarded(tmp_path):
    path=tmp_path/'config.json';path.write_text('original')
    temporary=path.with_suffix('.json.round2.tmp');temporary.write_text('unresolved')
    with pytest.raises(ValueError,match='Unresolved atomic'):publication.write(path,dict(version=12))
    assert path.read_text()=='original' and temporary.read_text()=='unresolved'


def test_complete_atomic_json(tmp_path):
    path=tmp_path/'config.json';publication.write(path,dict(version=12,count=51))
    assert json.loads(path.read_text())==dict(version=12,count=51)


@pytest.mark.parametrize('stage,name',[('activate','activation.json'),('finalize','final_acceptance.json')])
def test_prior_acceptance_cannot_be_replaced(tmp_path,monkeypatch,stage,name):
    (tmp_path/name).write_text('preserved evidence');monkeypatch.setattr(publication,'OUT',tmp_path)
    with pytest.raises(ValueError,match='Preserve completed'):getattr(publication,stage)()
    assert (tmp_path/name).read_text()=='preserved evidence'


def test_changed_user_configuration_stops_activation_before_gallery_or_writes(tmp_path,monkeypatch):
    monkeypatch.setattr(publication,'OUT',tmp_path)
    monkeypatch.setattr(publication,'seals',lambda: ({},{},{},{}))
    monkeypatch.setattr(publication,'read',lambda _: {'active_mask_gallery.json':'original'})
    monkeypatch.setattr(publication,'file_inventory',lambda _: {'active_mask_gallery.json':'user changed'})
    monkeypatch.setattr(publication,'Gallery',lambda _: pytest.fail('Must stop before loading gallery'))
    with pytest.raises(ValueError,match='do not overwrite'):publication.activate()
    assert not (tmp_path/'activation.json').exists()
