"""Independent oracle for the PF-002 C3 analytical slice, version 1.

Virtual lab - simulated experiment tooling, analytical model only. It imports
nothing from the checker or guard and shares no scientific helper, parser or
expected value with them. It repeats the frozen inputs itself and reaches each
result another way: derivatives expanded by hand, per-edge trapezoid closed forms
in place of parametrised integration, other constant paths, and Decimal bisection
in place of the closed-form inversion. Agreement checks an implementation of the
same declared equations. It is not physical validation.

Polynomials here are dicts from a sorted tuple of (name, power) pairs to Fraction.
"""

from decimal import Decimal, localcontext
from fractions import Fraction
import math

H_VALUES = (Fraction(-1), Fraction(-1, 10), Fraction(0), Fraction(1, 10), Fraction(1))
C_Q_VALUES = (Fraction(-1), Fraction(0), Fraction(1, 10), Fraction(1), Fraction(2))
GAUGE = ("G*R*s*nu", "s^2*nu", "R^3", "R*s")
RECTANGLE = ((0, 1), ("R1", 1), ("R1", -1), (0, -1))
SQUARE = ((Fraction(1, 2), 1), (1, 1), (1, -1), (Fraction(1, 2), -1))
CARRIERS = (((1, 1), (2, -1)), ((1, 0), (1, 1)),
            ((1, Fraction(1, 2)), (1, Fraction(-1, 2)), (3, 2)))
F_HAT = Decimal("1.0021E-11")
P0 = Decimal("0.62245")
WAVELENGTH = Decimal("1.55E-6")
C = Decimal("299792458")
ELL = Decimal("0.4")
DELTA_S = Decimal("0.5")
F_LOOP = Decimal("7E7")
N_HAT = Decimal("4.826E-3")
BETA = Fraction(338, 1000)
EPSILON = Decimal("1.5E-9")
SIGMA = Decimal("2.3E-9")


def _m(*pairs):
    return tuple(sorted(pairs))


def curvature():
    """A = (0, -G*R*nu, G*R*s), differentiated by hand."""
    return {"F_Rs": {_m(("G", 1), ("nu", 1)): Fraction(-1)},
            "F_Rnu": {_m(("G", 1), ("s", 1)): Fraction(1)},
            "F_snu": {_m(("G", 1), ("R", 1)): Fraction(2)}}


def el_equations(sign=1):
    """dL/dq - d/dt(dL/dqdot) for q = s and R, expanded by hand.

    dL/ds = Cm*thetad - w - 2*w2*s + sign*G*R*nud, and dL/dsd = -sign*G*R*nu,
    whose time derivative is -sign*G*(Rd*nu + R*nud). For R, dL/dR is
    sign*G*(s*nud - nu*sd), and L has no Rd.
    """
    k = Fraction(sign)
    return {"s": {_m(("Cm", 1), ("thetad", 1)): Fraction(1), _m(("w", 1)): Fraction(-1),
                  _m(("s", 1), ("w2", 1)): Fraction(-2),
                  _m(("G", 1), ("R", 1), ("nud", 1)): 2*k,
                  _m(("G", 1), ("Rd", 1), ("nu", 1)): k},
            "R": {_m(("G", 1), ("nud", 1), ("s", 1)): k,
                  _m(("G", 1), ("nu", 1), ("sd", 1)): -k}}


def gauge_terms():
    """For each Lambda, the two halves of its Euler-Lagrange term, by hand.

    For L' = dLambda/dt, dL'/dq and d/dt(dL'/dqdot) must coincide for every q.
    The pairs below are written out per coordinate and compared by the tests.
    """
    return {
        "G*R*s*nu": {"R": ({_m(("G", 1), ("nu", 1), ("sd", 1)): 1, _m(("G", 1), ("nud", 1), ("s", 1)): 1},
                           {_m(("G", 1), ("nu", 1), ("sd", 1)): 1, _m(("G", 1), ("nud", 1), ("s", 1)): 1}),
                     "s": ({_m(("G", 1), ("Rd", 1), ("nu", 1)): 1, _m(("G", 1), ("R", 1), ("nud", 1)): 1},
                           {_m(("G", 1), ("Rd", 1), ("nu", 1)): 1, _m(("G", 1), ("R", 1), ("nud", 1)): 1}),
                     "nu": ({_m(("G", 1), ("Rd", 1), ("s", 1)): 1, _m(("G", 1), ("R", 1), ("sd", 1)): 1},
                            {_m(("G", 1), ("Rd", 1), ("s", 1)): 1, _m(("G", 1), ("R", 1), ("sd", 1)): 1})},
        "s^2*nu": {"s": ({_m(("nu", 1), ("sd", 1)): 2, _m(("nud", 1), ("s", 1)): 2},
                         {_m(("nu", 1), ("sd", 1)): 2, _m(("nud", 1), ("s", 1)): 2}),
                   "nu": ({_m(("s", 1), ("sd", 1)): 2}, {_m(("s", 1), ("sd", 1)): 2})},
        "R^3": {"R": ({_m(("R", 1), ("Rd", 1)): 6}, {_m(("R", 1), ("Rd", 1)): 6})},
        "R*s": {"R": ({_m(("sd", 1),): 1}, {_m(("sd", 1),): 1}),
                "s": ({_m(("Rd", 1),): 1}, {_m(("Rd", 1),): 1})},
    }


def coordinate_output(c):
    """Phases as coefficients of theta and beta*R*nu, transformed by hand."""
    return {"detected": {"theta": Fraction(-1), "bRnu": -c+c},
            "drive_arg": {"arg_in": Fraction(1), "bRnu": -c},
            "difference": {"theta_in": Fraction(1), "theta": Fraction(-1), "bRnu": c-c}}


def _edge_terms(vertices, f, g):
    """Trapezoid closed form, exact for bilinear one-forms: f(x)*dx + g(x)*dy."""
    total = Fraction(0)
    n = len(vertices)
    for i in range(n):
        x0, y0 = vertices[i]
        x1, y1 = vertices[(i+1) % n]
        total += (f(x0, y0)+f(x1, y1))*(x1-x0)/2+(g(x0, y0)+g(x1, y1))*(y1-y0)/2
    return total


def rectangle(r1, reverse=False):
    verts = [(Fraction(r1) if x == "R1" else Fraction(x), Fraction(y)) for x, y in RECTANGLE]
    if reverse:
        verts = verts[::-1]
    out = {"A_Rnu": _edge_terms(verts, lambda r, n: 0, lambda r, n: r),
           "loop_nu_dR": _edge_terms(verts, lambda r, n: n, lambda r, n: 0),
           "loop_nu_dR_plus_2_R_dnu": _edge_terms(verts, lambda r, n: n, lambda r, n: 2*r)}
    for q in C_Q_VALUES:
        out[f"q={q}"] = _edge_terms(verts, lambda r, n, q=q: n-q*n, lambda r, n, q=q: 2*r-q*r)
    return out


def control(reverse=False, degenerate=False):
    verts = [(Fraction(s), Fraction(n)) for s, n in SQUARE]
    if degenerate:
        verts = [(Fraction(1), Fraction(1)), (Fraction(1), Fraction(-1))]
    if reverse:
        verts = verts[::-1]
    return _edge_terms(verts, lambda s, n: -n, lambda s, n: s)


def cross_multiplied(h, a_rnu, b_snu):
    """Coefficient of g0 in J*A + Cm*Phi*B: h*B*A - h*A*B."""
    return h*b_snu*a_rnu-h*a_rnu*b_snu


def constants():
    """Other algebraic paths, in 50-digit Decimal with pi as the binary math.pi."""
    with localcontext() as ctx:
        ctx.prec = 50
        k = 2*Decimal(math.pi)/WAVELENGTH
        alpha = F_HAT*C*k/P0
        return {"alpha_per_metre_per_unit_h": alpha,
                "alpha_vs_k_n_hat_relative": (alpha-k*N_HAT)/(k*N_HAT),
                "Cm_joule_second": P0*ELL*WAVELENGTH/(2*Decimal(math.pi)*C*C),
                "rectangle_Phi_h_radians_per_unit_h": Decimal("2E-6")*F_HAT*C*k/P0,
                "E_min_joules_per_unit_h": F_HAT*ELL*DELTA_S*4,
                "P_min_watts_per_unit_h": F_LOOP*4*DELTA_S*ELL*F_HAT}


def botermann():
    """Linear q from epsilon*(1 - beta^2)/beta^2; exact q by Decimal bisection."""
    with localcontext() as ctx:
        ctx.prec = 50
        b2 = Decimal(BETA.numerator)**2/Decimal(BETA.denominator)**2
        factor = (1-b2)/b2
        target = 1+EPSILON

        def statistic(q):
            gamma2 = 1/(1-b2)
            ratio = 1/(gamma2*(1-(1+q)**2*b2))
            return ratio.sqrt()

        low, high = Decimal(0), Decimal("1E-6")
        for _ in range(200):
            middle = (low+high)/2
            if statistic(middle) < target:
                low = middle
            else:
                high = middle
        return {"q_central": EPSILON*factor, "q_sigma": SIGMA*factor, "q_exact": (low+high)/2}


def static_stress():
    """Uniform E0 along z, B = 0: Poynting is zero and T_zz is eps0*E0^2/2."""
    return {"Poynting": ({}, {}, {}), "T_zz": {_m(("E0", 2), ("eps0", 1)): Fraction(1, 2)}}


def carrier_margins(group):
    """Margins without abs: min(E - p, E + p) per carrier, then for the sums."""
    each = None
    energy = momentum = Fraction(0)
    for e, p in group:
        e, p = Fraction(e), Fraction(p)
        margin = min(e-p, e+p)
        each = margin if each is None or margin < each else each
        energy += e
        momentum += p
    return each, min(energy-momentum, energy+momentum)
