"""Evaluate Scalar expressions, decide branch-cut guards, and refute missing conditions."""
from fractions import Fraction

from judgment import (
    Budget, ExactPoint, ExactValue, FilterConfig, FilterVerdict, GuardDecision, InfiniteClass,
    NumericValue, ProfileLevel, ScalarAtom, build_scalar, decide, evaluate, refute, session,
)


def main():
    budget = Budget(20_000_000)
    profile = build_scalar(budget, ProfileLevel.FOUNDATION)
    s = session(profile, ["x"], work=200_000_000)
    x = s.import_symbol("x")
    zero = profile.constant(s, "zero")
    one = profile.constant(s, "one")
    plus = profile.constant(s, "plus")
    times = profile.constant(s, "times")
    neg = profile.constant(s, "neg")
    inv = profile.constant(s, "inv")
    finite = profile.constant(s, "finite")

    # Compare (x^2 - 1) / (x - 1) with x + 1 at x = 1.
    x_minus_one = plus(x, neg(one))
    lhs = times(plus(times(x, x), neg(one)), inv(x_minus_one))
    rhs = plus(x, one)
    at_one = ExactPoint([(x, ExactValue(1))])
    lhs_val = evaluate(s, profile, lhs, at_one)
    rhs_val = evaluate(s, profile, rhs, at_one)
    assert lhs_val.kind == NumericValue.INFINITE
    assert lhs_val.infinite.kind == InfiniteClass.INDETERMINATE
    assert rhs_val.kind == NumericValue.BALL
    ball = rhs_val.ball
    assert abs(ball.real_mid - Fraction(2)) <= ball.real_rad
    print("At x = 1: lhs is Indeterminate, rhs encloses 2")

    # Decide guard atoms at exact points (nonzero and principal-strip unwound checks).
    nonzero_atom = ScalarAtom(ScalarAtom.NONZERO, [x])
    unwound_atom = ScalarAtom(ScalarAtom.UNWOUND, [x])
    at_one_nz = decide(s, profile, nonzero_atom, ExactPoint([(x, ExactValue(1))]))
    at_zero_nz = decide(s, profile, nonzero_atom, ExactPoint([(x, ExactValue(0))]))
    at_strip = decide(s, profile, unwound_atom, ExactPoint([(x, ExactValue(0, 1))]))
    outside_strip = decide(s, profile, unwound_atom, ExactPoint([(x, ExactValue(0, 4))]))
    assert at_one_nz == GuardDecision.HOLDS and at_zero_nz == GuardDecision.FAILS
    assert at_strip == GuardDecision.HOLDS and outside_strip == GuardDecision.FAILS
    print("Guards: nonzero(1) HOLDS, nonzero(0) FAILS | unwound(i) HOLDS, unwound(4i) FAILS")

    # Refute the missing-guard conjecture under finite(x) alone; pass with x - 1 != 0.
    config = FilterConfig(random_points=16)
    missing_guard = refute(s, profile, lhs, rhs, finite(x), [x], config)
    assert missing_guard.kind == FilterVerdict.REFUTED
    witness = missing_guard.witness.assignment[0][1]
    assert witness.re == Fraction(1) and witness.im == Fraction(0)
    print("Under finite(x) alone: REFUTED at x = 1")

    full_guard = finite(x) & ~(x_minus_one == zero)
    guarded = refute(s, profile, lhs, rhs, full_guard, [x], config)
    assert guarded.kind == FilterVerdict.PASSED
    assert guarded.points > 0
    print("Under finite(x) and x - 1 != 0: PASSED (testing evidence, not a proof)")


if __name__ == "__main__":
    main()
