"""Exact Spin(10) trace and conditional planar BFSS thermodynamic correction."""
from collections import Counter, defaultdict
from fractions import Fraction as F
from functools import cache
from itertools import combinations, combinations_with_replacement, product
import json
import math
from pathlib import Path


# Weight coordinates are twice their orthonormal-basis components. Spinors
# then use integer tuples as well. The first component carries the SO(2) charge.
def add(left, right):
    return tuple(x + y for x, y in zip(left, right))


def field_characters():
    zero = (0,) * 5
    vector = [tuple(2*sign if i == j else 0 for i in range(5))
              for j in range(5) for sign in (-1, 1)]
    singlet = Counter({zero: 1})
    spinors = list(product((-1, 1), repeat=5))
    positive = Counter(w for w in spinors if math.prod(w) == 1)
    negative = Counter(w for w in spinors if math.prod(w) == -1)
    symmetric = Counter(add(u, v) for u, v in combinations_with_replacement(vector, 2))
    vector_spinor = Counter(add(v, w) for v in vector for w in positive)
    return {
        "54": symmetric - singlet,
        "120": Counter(add(add(u, v), w) for u, v, w in combinations(vector, 3)),
        "45": Counter(add(u, v) for u, v in combinations(vector, 2)),
        "1": singlet,
        "16+": positive,
        "144+": vector_spinor - negative,  # gamma contraction has opposite chirality
    }


@cache
def weyl_denominator():
    """Expand product(1-e^(-alpha)) for the positive D4 roots e_i ± e_j."""
    terms = Counter({(0, 0, 0, 0): 1})
    for i, j in combinations(range(4), 2):
        for sign in (-1, 1):
            shift = tuple(-2 if k == i else -2*sign if k == j else 0 for k in range(4))
            shifted = {add(w, shift): coefficient for w, coefficient in terms.items()}
            terms.subtract(shifted)
            terms = Counter({w: v for w, v in terms.items() if v})
    return terms


def casimir(weight):
    """C=(lambda,lambda+2 rho), rho=(r−1,r−2,...,0) for Spin(2r)."""
    rank = len(weight)
    return sum(F(w, 2)*(F(w, 2) + 2*(rank - i - 1)) for i, w in enumerate(weight))


def dimension(weight):
    rho = list(range(len(weight) - 1, -1, -1))
    shifted = [F(w, 2) + r for w, r in zip(weight, rho)]
    result = math.prod((shifted[i]**2 - shifted[j]**2) / (rho[i]**2 - rho[j]**2)
                       for i, j in combinations(range(len(weight)), 2))
    if result.denominator != 1:
        raise ArithmeticError("Non-integral representation dimension")
    return int(result)


def branch(character):
    """Restrict Spin(10) to SO(2) charges and Spin(8) highest weights."""
    by_charge = defaultdict(Counter)
    for (charge, *weight), count in character.items():
        by_charge[charge][tuple(weight)] += count
    for charge, weights in sorted(by_charge.items()):
        recovered = 0
        for w in sorted(weights):
            if not (w[0] >= w[1] >= w[2] >= abs(w[3])):
                continue
            # In the dominant chamber, character times Weyl denominator leaves
            # precisely the highest weights and their irrep multiplicities.
            multiplicity = sum(sign * weights[tuple(x - y for x, y in zip(w, shift))]
                               for shift, sign in weyl_denominator().items())
            if multiplicity < 0:
                raise ArithmeticError("Negative irrep multiplicity")
            if multiplicity:
                states = multiplicity * dimension(w)
                recovered += states
                yield F(charge, 2), w, states
        if recovered != weights.total():
            raise ArithmeticError("Charge-sector dimension mismatch")


def trace_rows(data):
    characters = field_characters()
    coeff = {k: F(v) for k, v in data["operator"].items()}
    rows = []
    for field in data["representations"]:
        name = field["representation"]
        character = characters[name]
        highest = max(character)  # lexicographic maximum on an irreducible D5 character
        if dimension(highest) != character.total() or character.total() != int(name.rstrip("+")):
            raise ArithmeticError("Parent dimension mismatch")
        for charge, weight, states in branch(character):
            e = (coeff["chargeSquared"]*charge**2 + coeff["casimir8"]*casimir(weight)
                 + coeff["casimir10"]*casimir(highest))
            a2 = (coeff["chargeInA"]*charge)**2
            rows.append((name, field["sign"]*states, e, a2))
    return rows


def invariant_terms(rows, power, multiplier):
    values = defaultdict(F)
    for name, signed_states, e, a2 in rows:
        values[name] += signed_states * (e - a2)**power * (e - multiplier*a2)
    return dict(values)


def thermal_conversion(q, data):
    # sqrt(g) from the eight angular directions, times e^(-2phi), times (4.8).
    radial = (4*F(data["eightSphereMetricPower"]) - 2*F(data["dilatonRadialPower"])
              + data["invariantRadialPower"])
    if radial >= -1:
        raise ArithmeticError("The exterior radial integral diverges")
    integral_factor = -1 / (radial + 1)
    horizon_power = data["horizonPrefactorPower"] + radial + 1
    t_power = horizon_power / F(data["temperatureHorizonPower"])
    energy_factor = 1 - t_power  # E=F−T dF/dT at fixed N, lambda
    # Integrate the local action on the leading D0 background. The Euclidean
    # free-energy shift carries a minus sign. The dimensionless physical
    # temperature is d0^(1/3) times the geometric inverse period.
    two_pi_power = data["gravityTwoPiPower"] + data["dilatonTwoPiPower"]
    sphere_over_pi4 = F(32, 105)  # Vol(S^8)/pi^4
    free_prefactor = -q * integral_factor * sphere_over_pi4 / (data["actionDivisor"] * 2**two_pi_power)
    d0_power = 2 + F(1, 3) - t_power/3  # e^(-2phi), period, and r0(T)
    pi_power = 4 - two_pi_power + t_power + 5*d0_power
    # After removing pi^pi_power zeta(3), a fifth power is rational.
    if (5*d0_power).denominator != 1 or (5*t_power).denominator != 1:
        raise ArithmeticError("Expected pure fifth roots after integration")
    temp_factor = F(data["temperatureTimesPiFactor"])
    fifth = ((energy_factor*free_prefactor)**5 * data["d0OverPi5"]**int(5*d0_power)
             / temp_factor**int(5*t_power))
    # Apéry's rapidly convergent sum; the first omitted term bounds its tail.
    zeta3 = 2.5 * math.fsum((-1)**(k - 1) / (k**3 * math.comb(2*k, k)) for k in range(1, 33))
    energy = math.copysign(abs(float(fifth))**0.2, fifth) * math.pi**float(pi_power) * zeta3
    result = {"radialIntegrandPower": str(radial), "horizonPower": str(horizon_power),
              "temperaturePower": str(t_power), "energyFromFreeFactor": str(energy_factor),
              "piPower": str(pi_power), "normalizedEnergyFifthPower": str(fifth),
              "freeEnergyCoefficient": round(energy / float(energy_factor), 12),
              "energyCoefficient": round(energy, 12)}
    return result, fifth, pi_power


def run(data):
    rows = trace_rows(data)
    factor = data["invariant"]
    contributions = invariant_terms(rows, factor["firstFactorPower"], factor["lastASquaredMultiplier"])
    q = sum(contributions.values())
    lower = []
    for degree in range(4):
        for p in range(degree + 1):
            k = degree - p
            value = sum(states*e**p*a2**k for _, states, e, a2 in rows)
            lower.append({"ePower": p, "aSquaredPower": k, "supertrace": str(value)})
    thermal, fifth, pi_power = thermal_conversion(q, data["thermodynamics"])

    # Published values first enter here, after all six traces and the thermal integral.
    paper = data["printedComparison"]
    term_match = {k: str(v) for k, v in contributions.items()} == paper["terms"]
    q_match = q == F(paper["Q"])
    radical = math.prod(F(int(base))**power for base, power in paper["energyRadicalFifthPowers"].items())
    printed_fifth = F(paper["energyPrefactor"])**5 * radical
    thermal["exactEquation49Match"] = fifth == printed_fifth and pi_power == F(paper["piPower"])
    terms = []
    for rep in data["representations"]:
        name = rep["representation"]
        terms.append({"representation": name, "sign": rep["sign"], "dimension": int(name.rstrip("+")),
                      "signedTrace": str(contributions[name])})
    reversed_count = sum(-n if label == "144+" else n for label, n, _, _ in rows)
    wrong_q = sum(invariant_terms(rows, factor["firstFactorPower"], 1).values())
    passed = (term_match and q_match and all(m["supertrace"] == "0" for m in lower)
              and thermal["exactEquation49Match"] and reversed_count != 0 and wrong_q != q)
    return {"source": data["source"], "status": "passed" if passed else "failed", "terms": terms,
            "Q": str(q), "matchesPrintedTerms": term_match, "matchesPrintedQ": q_match,
            "lowerMoments": lower, "thermodynamics": thermal,
            "controls": {"signedDimensionWith144SignFlipped": reversed_count,
                         "QWithLastMultiplierOne": str(wrong_q)}}


if __name__ == "__main__":
    result = run(json.loads(Path(__file__).with_name("inputs.json").read_text(encoding="utf-8")))
    print(json.dumps(result, ensure_ascii=False, indent=2))
    raise SystemExit(0 if result["status"] == "passed" else 1)
