#!/usr/bin/env python3
"""N07 — 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 7 ===')
    print('Scorecard (verbatim): δ CP (°) −2π/√5 ≡ 199.003 theory 199.003 experiment 212 +26 −36 deviation −6.13% · d = −0.36 Derived-conditional —')
    negative = -2.0*math.pi/math.sqrt(5.0)
    positive = math.degrees(negative) % 360.0
    print("phase_radians = " + shown(negative))
    print("negative_degree_representative = " + shown(math.degrees(negative)))
    print("positive_degree_representative = " + shown(positive))
    print("theory_at_cell_precision = " + shown(positive,3))
    compare("full_formula_deg", positive, "212", "36", "26")
    compare("printed_cell_deg", "199.003", "212", "36", "26")
    print()


if __name__ == "__main__":
    main()
