#!/usr/bin/env python3
"""Construct a temporary-AND ladder and Gidney--Jones six-T CCCZ.

Sources: C. Gidney, arXiv:1709.06648; C. Gidney and N. C. Jones,
arXiv:2106.11513 (CC BY 4.0). Original implementation of the published
construction; QArena's official example was used to cross-check conventions.
No contestant artifact is used. See README.md for provenance and derivation.
"""
import argparse
import json
from pathlib import Path


def temporary_and(a, b, t):
    return [['H', t], ['CX', a, t], ['T', t], ['CX', b, t],
            ['TDG', t], ['CX', a, t], ['T', t], ['CX', b, t],
            ['TDG', t], ['H', t], ['SDG', t]]


def cccz(a, b, c, d, t, rec, optimized=True):
    if optimized:
        # Exact search over the 64 T/TDG assignments of the published
        # parity network yields signs (+,-,+,+,-,+). Both CZ corrections
        # then fire on outcome 1, and the final SDG is unnecessary.
        return [['H', t], ['T', t], ['CX', b, t], ['TDG', t],
                ['CX', a, t], ['T', t], ['CX', b, t], ['CX', d, t],
                ['T', t], ['CX', c, t], ['TDG', t], ['CX', d, t],
                ['T', t], ['CX', c, t], ['MX', t],
                ['IF', [rec], 1, ['CZ', a, b]],
                ['IF', [rec], 1, ['CZ', c, d]]]
    return [['H', t], ['CX', a, t], ['T', t], ['CX', b, t],
            ['TDG', t], ['CX', a, t], ['T', t], ['CX', b, t],
            ['CX', d, t], ['TDG', t], ['CX', c, t], ['T', t],
            ['CX', d, t], ['TDG', t], ['CX', c, t], ['H', t],
            ['S', t], ['MX', t], ['IF', [rec], 0, ['CZ', a, b]],
            ['IF', [rec], 1, ['CZ', c, d]]]


def simplify(ops):
    """Remove CX into a freshly prepared |+>, and fuse H S before MX.

    For each outcome, <r_X| S H is proportional to <r_X| SDG with
    an outcome-dependent global phase. Thus both instruments have the same
    data map up to branch scalars, and the same outcome labeling.
    """
    out = []
    for op in ops:
        if op[0] == 'CX' and out and out[-1] == ['H', op[2]]:
            # All generated H here prepare a fresh zero workspace. This is
            # a construction-specific rewrite, not a generic circuit rule.
            continue
        out.append(op)
    i = 0
    while i + 2 < len(out):
        if (out[i][0] == 'H' and out[i+1] == ['S', out[i][1]]
                and out[i+2] == ['MX', out[i][1]]):
            out[i:i+2] = [['SDG', out[i][1]]]
        i += 1
    return out


def construct(n, optimized=True, ancillas=None):
    if not 3 <= n <= 7:
        raise ValueError('n must be in [3,7]')
    if n == 6 and ancillas == 2:
        # Erase the first intermediate AND, reuse that workspace for CCCZ,
        # then recompute it to erase the remaining triple-AND. The first
        # and last CZ(0,1) feedbacks commute with everything between them
        # and combine into one parity-conditioned CZ.
        ops = temporary_and(0, 1, 6) + temporary_and(6, 2, 7)
        ops += [['MX', 6], ['RZ', 6]]
        ops += cccz(7, 3, 4, 5, 6, 1, optimized)
        ops += [['MX', 7], ['RZ', 6]]
        ops += temporary_and(0, 1, 6)
        ops += [['IF', [2], 1, ['CZ', 6, 2]], ['MX', 6],
                ['IF', [0, 3], 1, ['CZ', 0, 1]]]
        return {'ancillas': 2, 'ops': simplify(ops) if optimized else ops}
    if ancillas is not None and ancillas != max(1, n-3):
        raise ValueError('This ancilla limit is not implemented yet')
    if n == 3:
        ops = temporary_and(0, 1, n)
        ops += [['CZ', n, 2], ['MX', n], ['IF', [0], 1, ['CZ', 0, 1]]]
        ancillas = 1
    else:
        ancillas = n - 3
        ops, stack = [], []
        current = 0
        for j in range(n-4):
            t = n+j
            ops += temporary_and(current, j+1, t)
            stack.append((current, j+1, t))
            current = t
        ops += cccz(current, n-3, n-2, n-1, n+ancillas-1, 0, optimized)
        for rec, (a,b,t) in enumerate(reversed(stack), 1):
            ops += [['MX', t], ['IF', [rec], 1, ['CZ', a, b]]]
    return {'ancillas': ancillas, 'ops': simplify(ops) if optimized else ops}


def main():
    p = argparse.ArgumentParser()
    p.add_argument('n', type=int)
    p.add_argument('output', type=Path)
    p.add_argument('--baseline', action='store_true')
    p.add_argument('--ancillas', type=int)
    a = p.parse_args()
    art = construct(a.n, not a.baseline, a.ancillas)
    a.output.parent.mkdir(parents=True, exist_ok=True)
    a.output.write_text(json.dumps(art, separators=(',', ':'))+'\n')
    print(json.dumps({'output': str(a.output), 'gates': len(art['ops']),
                      't': sum(g[0] in ('T','TDG') for g in art['ops'])}))


if __name__ == '__main__':
    main()
