#!/usr/bin/env python3
"""Deterministic QArena qrom rank-factor lookup generator; no dependencies.

Provenance: all Python in this file is original to this research workspace.
Unary iteration: Babbush et al., arXiv:1805.03662 (paper's arXiv record lists
arXiv non-exclusive distribution license; no article text or code is copied).
Symmetry normalization: mathematical recipe published at https://qarena.ai/b/qrom.
QArena's bundle does not declare a source-code license; no bundle source or
contestant artifact is copied into this file. Inputs are official instance data.
GF(2) ANF factorization, CNOT conjugation and reversible prefix pebbling are
implemented here directly. Every artifact is reversible X/CX/CCX, so it also
works unchanged on the corresponding -mx instance. No random seed is used.

Example: python3 -I solve_rank.py INSTANCE.json OUTPUT.json --low-bits 3
"""
import argparse
import json
from pathlib import Path

def normalization(a, b):
    n = a // 2
    ws = list(range(a + b, a + b + n - 1))
    ops = [["CX", i, n + i] for i in range(n)]
    # For t = msb(w), normalize u_i by u_t*w_i for i<t. All other
    # t branches are disabled by their explicit higher-zero controls.
    for t in range(1, n):
        higher = list(range(n + t + 1, 2 * n))
        ops += [["X", d] for d in higher]
        controls = [t, n + t] + higher
        comp = [["CCX", controls[0], controls[1], ws[0]]]
        for k, c in enumerate(controls[2:], 1):
            comp.append(["CCX", ws[k - 1], c, ws[k]])
        ops += comp
        q = ws[len(controls) - 2]
        ops += [["CCX", q, n + i, i] for i in range(t)]
        ops += comp[::-1]
        ops += [["X", d] for d in higher]
    return ops

def normalized_table(data, a):
    n = a // 2
    size = 1 << n
    ans = []
    for w in range(size):
        t = w.bit_length() - 1
        for u in range(size):
            u0 = u & ~(1 << t) if w else u
            ans.append(data[u0 + size * (u0 ^ w)])
    return ans

def synthesize(I, k, low_wires=None, u_order="high"):
    a, b = I["address_bits"], I["output_bits"]
    n = a // 2
    data = normalized_table(I["data"], a)
    norm = normalization(a, b)
    ops = list(norm)
    low = sorted(low_wires) if low_wires is not None else list(range(k))
    if len(low) != k or len(set(low)) != k or any(not 0 <= w < a for w in low):
        raise ValueError("invalid low-wire subset")
    u_sequence = list(range(n - 1, -1, -1)) if u_order == "high" else list(range(n))
    high = [w for w in list(range(a - 1, n - 1, -1)) + u_sequence if w not in low]
    monowire = {1 << j: w for j, w in enumerate(low)}
    build = []
    wsnext = a + b
    for m in range(1, 1 << k):
        if m.bit_count() == 1:
            continue
        x = m & -m
        monowire[m] = wsnext
        build.append(["CCX", monowire[m ^ x], monowire[x], wsnext])
        wsnext += 1
    ops += build

    def word(control, value):
        for j in range(b):
            if value >> j & 1:
                ops.append(["X", a + j] if control is None else ["CX", control, a + j])

    def ccword(c1, c2, value):
        if not value:
            return
        j = (value & -value).bit_length() - 1
        target = a + j
        fanout = [["CX", target, a + h] for h in range(b) if h != j and value >> h & 1]
        ops.extend(fanout)
        ops.append(["CCX", c1, c2, target])
        ops.extend(fanout[::-1])

    def leaf(values, control):
        coef = values[:]
        for bit in range(k):
            for m in range(1 << k):
                if m >> bit & 1:
                    coef[m] ^= coef[m ^ (1 << bit)]
        word(control, coef[0])
        basis = []
        pivots = {}
        representations = []
        for j in range(b):
            v = sum((1 << m) for m in range(1, 1 << k) if coef[m] >> j & 1)
            rep = 0
            for p, idx in pivots.items():
                if v >> p & 1:
                    v ^= basis[idx]
                    rep ^= 1 << idx
            if v:
                idx = len(basis)
                pivots[v.bit_length() - 1] = idx
                basis.append(v)
                rep ^= 1 << idx
            representations.append(rep)
        for idx, v in enumerate(basis):
            mons = [m for m in range(1, 1 << k) if v >> m & 1]
            target = monowire[mons[0]]
            parity = [["CX", monowire[m], target] for m in mons[1:]]
            outmask = sum(1 << j for j in range(b) if representations[j] >> idx & 1)
            ops.extend(parity)
            if control is None:
                word(target, outmask)
            else:
                ccword(control, target, outmask)
            ops.extend(parity[::-1])

    def recurse(values, var, control, depth, first_info=None):
        first = values[0]
        if all(v == first for v in values):
            word(control, first)
            return
        if not var:
            leaf(values, control)
            return
        d = var[0]
        position = sorted(var + low).index(d)
        zero = [v for x, v in enumerate(values) if not (x >> position & 1)]
        one = [v for x, v in enumerate(values) if x >> position & 1]
        tail = var[1:]
        if zero == one:
            recurse(zero, tail, control, depth, first_info)
            return
        if control is None:
            ops.append(["X", d])
            recurse(zero, tail, d, depth, first_info)
            ops.append(["X", d])
            recurse(one, tail, d, depth, first_info)
        else:
            q = wsnext + depth
            restore = []
            if q >= a + b + I["ancillas_max"]:
                # Reversible pebbling: temporarily erase the earliest stored
                # prefix, whose parent is an address wire. Its descendants
                # remain valid values. Reuse this clean wire for the deepest
                # prefix and recreate the ancestor before walking back up.
                if q != a + b + I["ancillas_max"] or first_info is None:
                    raise ValueError("more than one excess prefix wire")
                parent, bit, negative = first_info
                q = wsnext
                if q == control:
                    raise ValueError("cannot erase the current control")
                restore = ([["X", bit]] if negative else [])
                restore += [["CCX", parent, bit, q]]
                restore += ([["X", bit]] if negative else [])
                ops.extend(restore)
            ops.extend([["X", d], ["CCX", control, d, q], ["X", d]])
            next_info = (control, d, True) if depth == 0 else first_info
            recurse(zero, tail, q, depth + 1, next_info)
            ops.append(["CX", control, q])
            next_info = (control, d, False) if depth == 0 else first_info
            recurse(one, tail, q, depth + 1, next_info)
            ops.append(["CCX", control, d, q])
            ops.extend(restore[::-1])

    recurse(data, high, None, 0)
    ops += build[::-1]
    ops += norm[::-1]
    used = max(g for op in ops for g in op[1:])
    return {"ancillas": max(0, used - a - b + 1), "ops": ops}

def main():
    p = argparse.ArgumentParser()
    p.add_argument("instance")
    p.add_argument("output")
    p.add_argument("--low-bits", type=int, required=True)
    p.add_argument("--low-wires", help="comma-separated wire indices; default 0..k-1")
    p.add_argument("--u-order", choices=["low", "high"], default="high")
    args = p.parse_args()
    I = json.loads(Path(args.instance).read_text())
    wires = [int(x) for x in args.low_wires.split(",")] if args.low_wires else None
    art = synthesize(I, args.low_bits, wires, args.u_order)
    if art["ancillas"] > I["ancillas_max"]:
        raise SystemExit(f"workspace {art['ancillas']} exceeds cap {I['ancillas_max']}")
    if len(art["ops"]) > I["gates_max"]:
        raise SystemExit(f"gate count {len(art['ops'])} exceeds cap {I['gates_max']}")
    Path(args.output).write_text(json.dumps(art, separators=(",", ":")))
    print(json.dumps({"toffoli": sum(o[0] == "CCX" for o in art["ops"]),
                      "gates": len(art["ops"]), "ancillas": art["ancillas"]}))

if __name__ == "__main__":
    main()
