"""Publish theorems into a proof-DAG library and verify deterministic versions and conflict checks."""
from std.tempfile import mkdtemp
from std.testing import assert_equal, assert_true
from judgment_shell import Session
from judgment_store import Library
from termbank import Budget


def main() raises:
    var budget = Budget(10000000)
    var path = String(mkdtemp(), "/lib")
    var lib = Library.create(path, "none")

    # Author two checked theorems over the library's profile snapshot and export them.
    var s = Session.open(lib.profile_snapshot(budget))
    var t_fact = s.prove_step("basics.truth", s.truth(s.base()))
    var t_step = s.truth(s.base())
    var both_fact = s.prove_step("pairs.both", s.and_intro(t_step, t_step))

    var first_change = lib.change()
    first_change.add(s.export(t_fact, "basics.truth"))
    first_change.add(s.export(both_fact, "pairs.both"))
    var first = first_change.publish()
    print("Published version 1 with", len(Library.open(path).theorems()), "theorems")

    # Publication is deterministic: the same exports yield the same version identity.
    var twin_path = String(mkdtemp(), "/twin")
    var twin = Library.create(twin_path, "none")
    var twin_change = twin.change()
    twin_change.add(s.export(t_fact, "basics.truth"))
    twin_change.add(s.export(both_fact, "pairs.both"))
    var same = twin_change.publish()
    print("Same exports, same version:", same == first)

    # A stale change built on the initial version is refused with CONFLICT.
    var stale = lib.change()
    stale.add(s.export(t_fact, "basics.extra"))
    var kind = String("accepted")
    try:
        _ = stale.publish()
    except error:
        kind = String(error.kind)
    assert_equal(kind, "CONFLICT")
    print("Publishing from a stale base:", kind)

    # Rebasing onto CURRENT succeeds and advances CURRENT.
    stale.rebase()
    var second = stale.publish()
    var current: String
    with open(String(path, "/CURRENT"), "r") as f:
        current = f.read()
    assert_true(not (second == first))
    print("CURRENT names version 2:", current == String(second, "\n"))
