"""Import OpenTheory articles into a proof-DAG library and read their checked theorems."""
from std.tempfile import mkdtemp
from std.testing import assert_equal, assert_true
from judgment_shell import Session
from judgment_store import Article, Library
from termbank import Budget

comptime REFL_ART = String(
    "6\nversion\n",
    "\"bool\"\ntypeOp\nnil\nopType\n0\ndef\npop\n",
    "\"->\"\ntypeOp\n0\nref\n0\nref\nnil\ncons\ncons\nopType\n1\ndef\npop\n",
    "\"->\"\ntypeOp\n0\nref\n1\nref\nnil\ncons\ncons\nopType\n2\ndef\npop\n",
    "\"p\"\n0\nref\nvar\n3\ndef\npop\n3\nref\nvarTerm\n4\ndef\npop\n",
    "\"=\"\nconst\n2\nref\nconstTerm\n4\nref\nappTerm\n4\nref\nappTerm\n5\ndef\npop\n",
    "4\nref\nrefl\nnil\n5\nref\nthm\n",
)


def main() raises:
    var dir = mkdtemp()
    var art_path = String(dir, "/refl.art")
    with open(art_path, "w") as f:
        f.write(REFL_ART)

    # Open the article directly as a TheoremSource to inspect its theorems.
    var art = Article.open(art_path)
    assert_equal(len(art.theorems()), 1)
    print("Article theorems:", len(art.theorems()))

    # Publish the article into a library and recheck it.
    var lib_path = String(dir, "/lib")
    var lib = Library.create(lib_path, "none")
    var change = lib.change()
    change.add_article(art_path, "example.refl")
    _ = change.publish()

    var reopened = Library.open(lib_path)
    var budget = Budget(10000000)
    var check = reopened.recheck(budget, workers=1)
    assert_true(check.rows > 0)
    var snap = reopened.profile_snapshot(budget)
    var s = Session.open(snap)
    var imported = s.import_theorem[Library](reopened, reopened.theorems()[0].name)
    assert_true(Bool(imported.imported()))
    print("Imported from library:", reopened.theorems()[0].kind)
