"""Prove Cantor's theorem in pure HOL and export an OpenTheory v6 article."""

from std.sys import argv
from std.tempfile import mkdtemp
from std.testing import assert_equal
from judgment import Session, arrow, exists, forall, implies, lambda_
from judgment_store import Article, Library
from termbank import Budget


def main() raises:
    var directory = mkdtemp()
    var args = argv()
    var path = String(args[1]) if len(args) > 1 else String(directory, "/cantor.art")

    var budget = Budget(50_000_000)
    var lib = Library.create(String(directory, "/classical"), "classical")
    var s = Session.open(lib.profile_snapshot(budget))

    # Cantor's theorem: no f : A -> (A -> Prop) is surjective onto A -> Prop.
    var p = s.theorem("cantor")
    var a = p.type_var("A")
    var pred_t = arrow(a, s.prop_type())
    var f = p.var("f", arrow(a, pred_t))

    # Diagonal predicate D(y) := (f(y)(y) -> False).
    var y = p.bound_var("y", a)
    var diag = lambda_(y, implies(f(y)(y), s.false_()))

    var x = p.bound_var("x", a)
    var g = p.bound_var("g", pred_t)
    var surj = forall(g, exists(x, f(x) == g))
    p.goal(implies(surj, s.false_()))

    # Assume f is surjective; instantiate at diag and obtain w with f(w) = diag.
    var h_surj = p.intro("h_surj")
    var h_ex = p.use(h_surj, terms=[diag])
    var obtained = p.obtain(h_ex, "w")
    var w = obtained[0]
    var hw = obtained[1]

    # Step 1: f(w)(w) = (f(w)(w) -> False) by rewriting f(w) -> diag and beta-reduction.
    var fw = f(w)(w)
    var eq_claim = p.have("fw_eq", fw == implies(fw, s.false_()))
    _ = eq_claim.lhs().at(f(w)).rw(hw)
    eq_claim.rfl()
    var fw_eq = eq_claim.fact()

    # Step 2: derive f(w)(w) -> False.
    var nfw_claim = p.have("nfw", implies(fw, s.false_()))
    var h_fw = nfw_claim.intro("h_fw")
    var imp_claim = nfw_claim.have("fw_imp", implies(fw, s.false_()))
    _ = imp_claim.focus().rw(fw_eq, reverse=True)
    imp_claim.exact(h_fw)
    nfw_claim.exact(nfw_claim.use(imp_claim.fact(), using=[h_fw]))
    var nfw = nfw_claim.fact()

    # Step 3: derive f(w)(w) from fw_eq and nfw, reaching False.
    var fw_claim = p.have("fw_holds", fw)
    _ = fw_claim.focus().rw(fw_eq)
    fw_claim.exact(nfw)
    p.exact(p.use(nfw, using=[fw_claim.fact()]))

    var theorem = p.finish()
    assert_equal(len(theorem.axioms()), 0)
    assert_equal(len(theorem.admissions()), 0)
    print("Proved:", theorem)
    print("Axioms:", len(theorem.axioms()), "| Admissions:", len(theorem.admissions()))

    # Export as an OpenTheory v6 article (with checked read-back).
    Article.write(path, [s.export(theorem, "logic.cantor")], budget, profile="classical")
    var article = Article.open(path, profile="classical")
    var proved_count = 0
    for entry in article.theorems():
        if entry.kind == "theorem":
            proved_count += 1
    assert_equal(proved_count, 1)
    print("Exported OpenTheory v6 theorems:", proved_count)
