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

import sys
from pathlib import Path
from tempfile import TemporaryDirectory

from judgment import Article, Budget, Library, Session, arrow, exists, forall, implies, lambda_


def main():
    with TemporaryDirectory() as directory:
        path = sys.argv[1] if len(sys.argv) > 1 else str(Path(directory) / "cantor.art")

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

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

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

        x = p.bound_var("x", a)
        g = p.bound_var("g", pred_t)
        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.
        h_surj = p.intro("h_surj")
        h_ex = p.use(h_surj, terms=[diag])
        w, hw = p.obtain(h_ex, "w")

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

        # Step 2: derive f(w)(w) -> False.
        nfw_claim = p.have("nfw", implies(fw, s.false_()))
        h_fw = nfw_claim.intro("h_fw")
        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]))
        nfw = nfw_claim.fact()

        # Step 3: derive f(w)(w) from fw_eq and nfw, reaching False.
        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()]))

        theorem = p.finish()
        assert len(theorem.axioms()) == 0
        assert 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")
        article = Article.open(path, profile="classical")
        proved = [entry for entry in article.theorems() if entry.kind == "theorem"]
        assert len(proved) == 1
        print("Exported OpenTheory v6 theorems:", len(proved))


if __name__ == "__main__":
    main()
