"""Publication cannot overwrite changed inputs or mislabel incomplete acceptance."""
import json

import pytest

from scripts import publish_mask_remaining_continue as publication


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


def test_atomic_config_replacement_has_complete_json(tmp_path):
    path=tmp_path/'config.json';value=dict(version=11,count=185)
    publication.write(path,value)
    assert json.loads(path.read_text())==value
    assert not path.with_suffix('.json.remainingcontinue.tmp').exists()


def test_activation_preserves_existing_activation_evidence(tmp_path,monkeypatch):
    (tmp_path/'activation.json').write_text('completed evidence')
    monkeypatch.setattr(publication,'OUT',tmp_path)
    with pytest.raises(ValueError,match='Preserve completed activation'):publication.activate()
    assert (tmp_path/'activation.json').read_text()=='completed evidence'


def test_finalization_cannot_replace_prior_acceptance(tmp_path,monkeypatch):
    (tmp_path/'final_acceptance.json').write_text('original independent evidence')
    monkeypatch.setattr(publication,'OUT',tmp_path)
    with pytest.raises(ValueError,match='Preserve completed final'):publication.finalize()
    assert (tmp_path/'final_acceptance.json').read_text()=='original independent evidence'


def test_activation_stops_before_writing_changed_user_configuration(tmp_path,monkeypatch):
    monkeypatch.setattr(publication,'OUT',tmp_path)
    monkeypatch.setattr(publication,'seals',lambda: ({},{},{},{}))
    monkeypatch.setattr(publication,'read',lambda _: {'active_mask_gallery.json':'expected hash'})
    monkeypatch.setattr(publication,'file_inventory',lambda _: {'active_mask_gallery.json':'new user content'})
    monkeypatch.setattr(publication,'Gallery',lambda _: pytest.fail('Must not get beyond changed configuration'))
    with pytest.raises(ValueError,match='do not overwrite'):publication.activate()
    assert not (tmp_path/'activation.json').exists()
