"""``tomledit.set_rotation_last_in_file`` — the surgical rotation.last stamp (SPEC-P5 §1).

Only the entry's ``rotation.last`` changes; every neighbouring line stays byte-identical
so the git diff is minimal + reviewable. Handles inserting ``last`` where absent and
updating it where present, for both the inline and multi-line rotation forms.
"""

from __future__ import annotations

from mgf.secrets.tomledit import entry_span, set_rotation_last_in_file


def test_inserts_last_into_inline_rotation_without_it(tmp_path) -> None:
    p = tmp_path / "SECRETS.toml"
    p.write_text(
        '[a]\nkind = "api-token"\n'
        'rotation = { class = "token", staged = true }\n'
        'state = "active"\n\n'
        '[b]\nrotation = { class = "x", staged = false }\n',
        encoding="utf-8",
    )
    assert set_rotation_last_in_file(p, "a", "2026-07-22") is True
    text = p.read_text(encoding="utf-8")
    assert 'rotation = { class = "token", staged = true, last = "2026-07-22" }' in text
    # b untouched; a's neighbours intact.
    assert 'rotation = { class = "x", staged = false }\n' in text
    assert 'kind = "api-token"' in text and 'state = "active"' in text


def test_updates_existing_last_in_place(tmp_path) -> None:
    p = tmp_path / "SECRETS.toml"
    p.write_text(
        '[a]\nrotation = { class = "static-key", staged = true, last = "2026-07-12" }\n',
        encoding="utf-8",
    )
    assert set_rotation_last_in_file(p, "a", "2026-07-22") is True
    text = p.read_text(encoding="utf-8")
    assert 'last = "2026-07-22"' in text and "2026-07-12" not in text
    assert 'class = "static-key"' in text and "staged = true" in text


def test_only_the_named_entry_is_stamped(tmp_path) -> None:
    p = tmp_path / "SECRETS.toml"
    p.write_text(
        '[a]\nrotation = { class = "t", staged = true }\n\n'
        '[b]\nrotation = { class = "t", staged = true }\n',
        encoding="utf-8",
    )
    set_rotation_last_in_file(p, "b", "2026-07-22")
    text = p.read_text(encoding="utf-8")
    assert text.count('last = "2026-07-22"') == 1
    # a is the first entry and must be unstamped.
    lines = text.splitlines()
    span = entry_span(lines, "a")
    a_block = "\n".join(lines[span[0] : span[1]])
    assert "last" not in a_block


def test_unknown_entry_returns_false(tmp_path) -> None:
    p = tmp_path / "SECRETS.toml"
    p.write_text('[a]\nrotation = { class = "t", staged = true }\n', encoding="utf-8")
    assert set_rotation_last_in_file(p, "nope", "2026-07-22") is False
