#!/usr/bin/env python3
"""N12 — arithmetic from D1287 supplied sources.
No network, external packages, fitting operations or shared runtime files.
Printed source cells and unrounded arithmetic are distinct outputs.
"""

import math
from decimal import Decimal, ROUND_HALF_UP, getcontext
from fractions import Fraction

getcontext().prec = 40
PHI = (1.0 + math.sqrt(5.0)) / 2.0


def shown(value, places=9, signed=False):
    """Decimal half-up display; never use display-rounded inputs implicitly."""
    value = Decimal(str(value))
    rounded = value.quantize(Decimal(1).scaleb(-places), rounding=ROUND_HALF_UP)
    return format(rounded, ("+" if signed else "") + "." + str(places) + "f")


def compare(label, theory, reference, lower=None, upper=None):
    """Naive central-value arithmetic, not a likelihood or theory-error model.

    The asymmetric denominator points from the comparator toward the theory:
    lower error below the central value; upper error above it. Any different
    printed convention is audited separately, rather than silently substituted.
    """
    theory, reference = Decimal(str(theory)), Decimal(str(reference))
    if reference == 0:
        raise ValueError("A relative deviation needs a nonzero reference.")
    offset = theory - reference
    percent = 100 * offset / reference
    print(label + ".theory = " + shown(theory))
    print(label + ".reference = " + shown(reference))
    print(label + ".signed_percent = " + shown(percent, signed=True)
          + "%; rounded = " + shown(percent, 2, True) + "%")
    if lower is None or upper is None:
        print(label + ".d = NOT AVAILABLE (no uncertainty supplied for this comparison variable)")
        return
    side = "lower" if offset < 0 else "upper"
    uncertainty = Decimal(str(lower if offset < 0 else upper))
    if uncertainty <= 0:
        raise ValueError("The selected comparator uncertainty must be positive.")
    distance = offset / uncertainty
    print(label + ".uncertainty_used = " + str(uncertainty) + " (" + side + ")")
    print(label + ".d = " + shown(distance, signed=True)
          + "; rounded = " + shown(distance, 2, True))

def main():
    print('=== row 12a ===')
    print('Scorecard (verbatim): δ CKM (°) vs global fit arctan√(3G 7 ) theory 68.13 experiment 66.12 ± 1.43 deviation +3.04% · d = +1.41 Coincidence-class —')
    g7 = PHI+5.0*PHI**(-5)
    phase = math.degrees(math.atan(math.sqrt(3.0*g7)))
    print("G7 = " + shown(g7,12))
    print("theory_at_cell_precision_deg = " + shown(phase,2))
    compare("full_formula_global_deg", phase, "66.12", "1.43", "1.43")
    compare("printed_cell_global_deg", "68.13", "66.12", "1.43", "1.43")
    print()
    print('=== row 12b ===')
    print('Scorecard (verbatim): δ CKM (°) vs direct γ arctan√(3G 7 ) theory 68.13 experiment 66.4 +2.7 −2.8 deviation +2.60% · d = +0.64 Coincidence-class —')
    phase = math.degrees(math.atan(math.sqrt(3.0*(PHI+5.0*PHI**(-5)))))
    print("theory_at_cell_precision_deg = " + shown(phase,2))
    compare("full_formula_direct_deg", phase, "66.4", "2.8", "2.7")
    compare("printed_cell_direct_deg", "68.13", "66.4", "2.8", "2.7")
    print("alternate_lower_error_d = " + shown((phase-66.4)/2.8,9,True)
          + "; rounded = " + shown((phase-66.4)/2.8,2,True))
    print()
    print('=== row 12c ===')
    print('Scorecard (verbatim): δ CKM (°) — bare-φ control (no G 7 correction) arctan√(3φ) theory 65.59 experiment 66.12 ± 1.43 (global) / 66.4 +2.7 −2.8 (direct) deviation −0.80% · d = −0.37 / −0.30 Control (printed beside 12a/b) not scored — the uncorrected argument sits closer than G 7 on both comparators; 28 of 64 sibling corrections land within 1σ, so the numeral’s agreement carries no significance (Paper 3, Rev32.2)')
    phase = math.degrees(math.atan(math.sqrt(3.0*PHI)))
    print("theory_at_cell_precision_deg = " + shown(phase,2))
    compare("full_control_global_deg", phase, "66.12", "1.43", "1.43")
    compare("printed_control_global_deg", "65.59", "66.12", "1.43", "1.43")
    compare("full_control_direct_deg", phase, "66.4", "2.8", "2.7")
    compare("printed_control_direct_deg", "65.59", "66.4", "2.8", "2.7")
    print("alternate_upper_error_d = " + shown((phase-66.4)/2.7,9,True)
          + "; rounded = " + shown((phase-66.4)/2.7,2,True))
    print("source_census = 28 of 64 siblings within 1 sigma; reported, not rerun")
    print()


if __name__ == "__main__":
    main()
