"""Ideal iterative Shor simulation and a reversible lookup circuit for N=299."""
import argparse
import json
from collections import Counter
from fractions import Fraction
from math import gcd
from pathlib import Path

import numpy as np

N, BASE, SHOTS, SEED = 299, 2, 256, 1936
WIDTH = N.bit_length()
PRECISION = (N*N-1).bit_length()
ROOT = Path(__file__).resolve().parent


def simulate_phases(n, base, bits, shots, seed):
    # Each row is one trajectory. The control is measured and reset after every bit.
    rng = np.random.default_rng(seed)
    residues = np.arange(1 << n.bit_length())
    work = np.zeros((shots, len(residues)), dtype=complex)
    work[:, 1] = 1
    outcomes = np.zeros(shots, dtype=int)
    for step in range(bits):
        power = pow(base, 1 << (bits-1-step), n)
        inverse = pow(power, -1, n)
        permuted = work[:, np.where(residues < n, residues*inverse % n, residues)]
        rotation = np.exp(-2j*np.pi*outcomes / (1 << (step+1)))
        rotated = rotation[:, None] * permuted
        plus = (work + rotated) / 2
        p_zero = (abs(plus)**2).sum(axis=1)
        one = rng.random(shots) >= np.clip(p_zero, 0, 1)
        work = np.where(one[:, None], (work-rotated)/2, plus)
        work /= np.linalg.norm(work, axis=1)[:, None]
        outcomes += one.astype(int) << step
    return outcomes


def decode(y):
    phase = Fraction(int(y), 1 << PRECISION)
    candidate = phase.limit_denominator(N-1).denominator
    if candidate % 2 or pow(BASE, candidate, N) != 1:
        return None
    half = pow(BASE, candidate//2, N)
    factors = sorted([gcd(half-1, N), gcd(half+1, N)])
    if factors[0] > 1 and factors[0]*factors[1] == N:
        return {"denominator":candidate, "half_power_mod_N":half, "factors":factors}
    return None


def simulate():
    check = simulate_phases(15, 2, 4, 256, SEED)
    assert set(check) == {0, 4, 8, 12}
    samples = simulate_phases(N, BASE, PRECISION, SHOTS, SEED)
    counts = Counter(map(int, samples))
    decoded = {y:result for y in counts if (result := decode(y)) is not None}
    record = {"N":N, "base":BASE, "phase_bits":PRECISION, "work_bits":WIDTH,
              "shots":SHOTS, "seed":SEED, "counts_decimal":dict(sorted(counts.items())),
              "verified_factor_shots":sum(counts[y] for y in decoded), "decoded":decoded}
    (ROOT/"Shor299-simulator.json").write_text(json.dumps(record, indent=2))
    print(record["verified_factor_shots"], next(iter(decoded.items())), "of", SHOTS)


def lookup(qc, k, control, work, target, scratch):
    # Reversibly XOR f(x) into target if control is set. Descend a binary
    # prefix tree and share the prefix flags between neighboring table entries.
    # Relative phases of each compute/uncompute pair cancel on every input.
    def visit(depth, prefix, enabled):
        if depth == WIDTH:
            value = (k*prefix) % N if prefix < N else prefix
            for b in range(WIDTH):
                if (value >> b) & 1:
                    qc.cx(enabled, target[b])
            return
        bit = work[WIDTH-1-depth]
        flag = scratch[depth]
        for value in (0, 1):
            if value == 0:
                qc.x(bit)
            qc.rccx(enabled, bit, flag)
            visit(depth+1, 2*prefix+value, flag)
            qc.rccx(enabled, bit, flag)
            if value == 0:
                qc.x(bit)
    visit(0, 0, control)


def polynomial_lookup(qc, k, control, work, target, scratch):
    # Positive-polarity Boolean expansion of the entire same reversible table.
    # Each prefix AND is computed once and reused by all its descendants.
    indices = np.arange(1 << WIDTH)
    values = np.where(indices < N, (indices*k) % N, indices)
    coeff = values.copy()
    for i in range(WIDTH):
        mask = indices[(indices & (1 << i)) != 0]
        coeff[mask] ^= coeff[mask ^ (1 << i)]
    check = coeff.copy()
    for i in range(WIDTH):
        mask = indices[(indices & (1 << i)) != 0]
        check[mask] ^= check[mask ^ (1 << i)]
    assert np.array_equal(check, values) and coeff[0] == 0

    def visit(mask, start, enabled, depth):
        for i in range(start, WIDTH):
            new_mask = mask | (1 << i)
            value = int(coeff[new_mask])
            if i == WIDTH-1 and not value:
                continue
            flag = scratch[depth]
            qc.rccx(enabled, work[i], flag)
            for j in range(WIDTH):
                if (value >> j) & 1:
                    qc.cx(flag, target[j])
            visit(new_mask, i+1, flag, depth+1)
            qc.rccx(enabled, work[i], flag)

    visit(0, 0, control, 0)


def hardware_circuit(table=lookup):
    from qiskit import QuantumCircuit
    from qiskit.circuit.library import QFTGate
    q = QuantumCircuit(PRECISION+3*WIDTH, PRECISION)
    work, target, scratch = [list(range(PRECISION+j*WIDTH, PRECISION+(j+1)*WIDTH)) for j in range(3)]
    q.x(work[0])
    q.h(range(PRECISION))
    for bit in range(PRECISION):
        k = pow(BASE, 1 << bit, N)
        if k == 1:
            continue
        table(q, k, bit, work, target, scratch)
        for x, y in zip(work, target):
            q.cswap(bit, x, y)
        table(q, pow(k, -1, N), bit, work, target, scratch)
    q.append(QFTGate(PRECISION).inverse(), range(PRECISION))
    q.measure(range(PRECISION), range(PRECISION))
    return q


def size():
    from qiskit import transpile
    q = hardware_circuit()
    native = transpile(q, basis_gates=["rz","sx","x","cz"], optimization_level=1, seed_transpiler=SEED)
    record = {"logical_width_including_scratch":q.num_qubits, "phase_bits":PRECISION,
              "counts_before_decomposition":dict(q.count_ops()),
              "basis_counts_all_to_all":dict(native.count_ops()),
              "two_qubit_depth_all_to_all":native.depth(lambda op:len(op.qubits)==2),
              "connectivity":"all-to-all, no device routing"}
    (ROOT/"Shor299-circuit-size.json").write_text(json.dumps(record, indent=2))
    print(record)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("action", choices=["simulate","size"])
    args = parser.parse_args()
    (simulate if args.action == "simulate" else size)()
