#!/usr/bin/env python3
"""Exact QArena energy SOS generator, original implementation, no dependencies.

Elementary debug and four-neighbor-star identities are derived in this workspace.
The translated half-coupling local certificate is data from QArena's official
verifier bundle example, version f227edeb93d1, not another contestant's artifact.
Mathematical provenance: https://qarena.ai/b/energy . The official bundle has no
explicit source-code license; its baseline construction is supplied for reuse.
No third-party source code is copied. No floating-point optimization is used.

Example (from qarena/):
 python3 -I solvers/energy/solve_energy.py j1j2-10x10-11of20 results/energy/star.json
The official bundled example is required for ranked cells; pass --example PATH
if it is stored elsewhere. No random seed or external package is needed.
"""
import argparse
import collections
import hashlib
import itertools
import json
from pathlib import Path

def square(terms, weight=1):
    return {"weight": format(weight, "x"),
            "terms": [[p, format(c, "x"), "0"] for p, c in sorted(terms.items()) if c]}

def axis_triangle(a):
    return {"III": 1, a + a + "I": 1, a + "I" + a: 1, "I" + a + a: 1}

def debug_certificate(instance):
    if instance == "dimer2":
        # sum_a (a0+a1)^2 /8 = h01/4 + 3I/4.
        return {"bound_ticks": -36000, "den": "8",
                "squares": [square({a + "I": 1, "I" + a: 1}) for a in "XYZ"]}
    if instance == "triangle3":
        # B_a = I+a0a1+a0a2+a1a2, B_a^2=4B_a.
        # sum_a B_a^2 /16 = h_triangle/4 + 3I/4.
        return {"bound_ticks": -24000, "den": "10",
                "squares": [square(axis_triangle(a)) for a in "XYZ"]}
    if instance == "chain3":
        # C=I-X0X2-Y0Y2-Z0Z2 is 4 times the end-pair singlet
        # projector. B_X*C=C*B_X=0, so (B_X+C)^2=B_X^2+C^2.
        # The sum below adds the end-pair singlet projector to the
        # triangle identity, cancelling its unwanted h02/4 bond.
        return {"bound_ticks": -32000, "den": "10",
                "squares": [square({"III": 2, "XXI": 1, "IXX": 1, "YIY": -1, "ZIZ": -1}),
                            square(axis_triangle("Y")), square(axis_triangle("Z"))]}
    raise ValueError("only dimer2, triangle3, chain3 supported")

def pair(n, u, v, axis):
    p = ["I"] * n; p[u] = p[v] = axis
    return "".join(p)

def template_from_example(path):
    example = json.loads(Path(path).read_text())
    factors = example["squares"][:10]
    sites = sorted({i for s in factors for t in s["terms"] for i, c in enumerate(t[0]) if c != "I"})
    assert sites == [0, 1, 10, 11, 12, 21, 22]
    return int(example["den"], 16), [(int(s["weight"], 16),
                [(tuple((i % 10, i // 10, p[i]) for i in sites if p[i] != "I"), re, im)
                 for p, re, im in s["terms"]]) for s in factors]

def ranked_certificate(instance, example):
    L = 8 if instance == "j1j2-8x8-half" else 10
    n = L * L
    extra = instance.endswith("11of20")
    den0, factors = template_from_example(example)
    assert den0 == 17280
    den = 86400 if extra else den0
    scale = den // den0
    factors_out = []
    q = lambda x, y: x % L + L * (y % L)
    for y in range(L):
        for x in range(L):
            for weight, terms in factors:
                out = []
                for sites, re, im in terms:
                    pauli = ["I"] * n
                    for dx, dy, axis in sites:
                        pauli[q(x + dx, y + dy)] = axis
                    out.append(["".join(pauli), re, im])
                factors_out.append({"weight": format(scale * weight, "x"), "terms": sorted(out)})
    if extra:
        # K=central Pauli vector dot sum of its four diagonal neighbors.
        # H_star+3I/2 = (K+6I)^2/40 + sum_outer_pairs C_uv^2/80,
        # C_uv=I-XuXv-YuYv-ZuZv. Summing all stars counts each
        # diagonal bond twice; multiply by delta_J2/2=1/40.
        # Therefore the extra diagonal Hamiltonian is >=-3n/80,
        # improving the old -3n/40 remainder bound by a factor two.
        assert den % 3200 == 0
        for y in range(L):
            for x in range(L):
                c = q(x, y)
                neighbors = [q(x + dx, y + dy) for dx, dy in ((1, 1), (1, -1), (-1, 1), (-1, -1))]
                K = {"I" * n: 6}
                for u in neighbors:
                    for axis in "XYZ":
                        K[pair(n, c, u, axis)] = 1
                factors_out.append(square(K, den // 1600))
                for u, v in itertools.combinations(neighbors, 2):
                    C = {"I" * n: 1, **{pair(n, u, v, axis): -1 for axis in "XYZ"}}
                    factors_out.append(square(C, den // 3200))
    # Repeated identical positive squares are combined exactly.
    merged = collections.OrderedDict()
    for factor in factors_out:
        key = tuple(tuple(t) for t in factor["terms"])
        merged[key] = merged.get(key, 0) + int(factor["weight"], 16)
    factors_out = [{"weight": format(w, "x"), "terms": [list(t) for t in terms]} for terms, w in merged.items()]
    return {"bound_ticks": -63600 if extra else -60000, "den": format(den, "x"), "squares": factors_out}

def main():
    p = argparse.ArgumentParser()
    p.add_argument("instance", choices=["dimer2", "triangle3", "chain3", "j1j2-8x8-half", "j1j2-10x10-half", "j1j2-10x10-11of20"])
    p.add_argument("output")
    p.add_argument("--example", default=str(Path(__file__).resolve().parents[2] / "bundles/energy/qarena-energy/example/j1j2-10x10-half.json"))
    a = p.parse_args()
    if a.instance in ("dimer2", "triangle3", "chain3"):
        art = debug_certificate(a.instance)
    else:
        expected = "963073fff439dc7630a76211a3876e6dbf7a81104b4b31709c0438f7c6804d98"
        if hashlib.sha256(Path(a.example).read_bytes()).hexdigest() != expected:
            raise ValueError("official example hash differs from the audited bundle")
        art = ranked_certificate(a.instance, a.example)
    Path(a.output).write_text(json.dumps(art, separators=(",", ":")))
    sizes = [len(s["terms"]) for s in art["squares"]]
    print(json.dumps({"bound_ticks": art["bound_ticks"], "products": sum(s*s for s in sizes), "terms": sum(sizes), "squares": len(sizes)}))


if __name__ == "__main__":
    main()
