"""Fixed-T2, linear-T1 virtual ladder on the finite four-band BIPOLE fixture."""
import json
from itertools import combinations_with_replacement, product

import numpy as np

try:
    from . import bipole_bare_ladder as bare
except ImportError:  # Direct script invocation
    import bipole_bare_ladder as bare

# In the two home diagonal PNO frames; translate each vector without a phase.
SINGLES = (np.array([.143, -.081]), np.array([-.097, .169]))
TOL, FORBIDDEN = bare.ACTION_TOL, bare.FORBIDDEN_TOL


def prepare():
    system, basis, mesh, options, kw = bare.op.rhf_fixture(3, scf=bare.SCF, **bare.FIXTURE)
    r = bare.run_pbc_bipole_rhf(system, basis, mesh, options,
                                terminal_transition_bytes=bare.LIMIT, **kw)
    h = r.terminal_transitions
    x = bare.run_translation_dlpno_mp2(
        r, bare.MESH, factor_handle=h, max_factor_bytes=h.required_bytes,
        tcut_mkn=bare.CUTOFF, tcut_pno=bare.PNO_CUTOFF, pno_norm='mp2',
        tcut_pairs=0., n_frozen=0, conv_tol_energy=1e-13, conv_tol_residual=1e-12)
    assert x.solution.converged
    bare.op.near(x.solution.e_pair_per_cell, -.0407466307096963, TOL)
    z = x.pair_build.spaces
    rng = np.random.default_rng(586)
    ts = []
    for (i, j), n in zip(z.representative_pairs, z.pair_ranks, strict=True):
        a = rng.normal(size=(n, n))*.125
        ts.append((a+a.T)/2 if i == j else a)
    return r, x, ts


def reference_inputs(r, x, ts):
    s, f, eri, _, c = bare.supercell_operands(r, bare.op.GaussianCell(**bare.FIXTURE))
    z = x.pair_build.spaces
    o = np.asarray(x.occupied_selection.occupied)
    _, _, pao = bare.pair_spaces(s, o, c[:, :6], list(range(4)), bare.CUTOFF)
    rows = [dict(bands=ij.tolist(), R=int(R[0]), pno_rank=n, occupations=ev.tolist())
            for ij, R, n, ev in zip(z.plan.band_pairs, z.plan.displacements,
                                    x.pair_build.pno_ranks, x.pair_build.occupations, strict=True)]
    bases, _, _, _ = bare.pno_comparison(s, f, eri, o, pao, rows, z.pair_coefficients,
                                         bare.PNO_CUTOFF)
    # Independently translate the seven home frames and transpose reversed doubles.
    placed, amps = {}, {}
    for row, home, t in zip(rows, z.pair_coefficients, ts, strict=True):
        i, j = row['bands']
        for cell in range(3):
            ij = (2*cell+i, 2*((cell+row['R']) % 3)+j)
            placed[ij] = placed[ij[::-1]] = np.roll(home, 4*cell, axis=0)
            amps[ij], amps[ij[::-1]] = t, t.T
    assert len(amps) == 36
    return s, eri, c[:, 6:], o, bases, placed, amps


def native_snapshots(eri, o, virtual, s, pairs, bases, t, singles):
    """All three integral classes, in a signed spectral resolution of the AO ERI."""
    ev, u = np.linalg.eigh(eri.reshape(144, 144))
    frames = [virtual.T @ s @ bases[ij] for ij in pairs]
    result = [{ij: np.zeros_like(t[ij]) for ij in pairs} for _ in range(2)]
    for sign in (-1, 1):
        keep = sign*ev > 0
        if not keep.any():
            continue
        ao = (u[:, keep]*np.sqrt(sign*ev[keep])).T.reshape(-1, 12, 12)
        factors = [np.ascontiguousarray((left.T @ ao @ right).reshape(len(ao), -1))
                   for left, right in ((o, virtual), (o, o), (virtual, virtual))]
        for scale, blocks in enumerate(result):
            native = bare.native._dlpno_ccsd_pno_evaluate(
                *factors, -np.eye(6), np.zeros((6, 6)), np.eye(6),
                [i for i, j in pairs], [j for i, j in pairs], frames,
                [np.ones(v.shape[1]) for v in frames], [np.zeros_like(t[ij]) for ij in pairs],
                [t[ij] for ij in pairs], [list(range(6)) for _ in pairs],
                [scale*a for a in singles], True)
            for ij, terms in zip(pairs, native['doubles_terms'], strict=True):
                blocks[ij] += sign*(terms['virtual_ladder'] - terms['occupied_ladder'])
    return result


def oracle(s, eri, virtual, o, bases, placed, amps):
    """Expand the entire shared virtual block by degree in the singles at fixed T2."""
    rotations = {ij: v.T @ s @ placed[ij] for ij, v in bases.items()}
    t = {ij: u @ amps[ij] @ u.T for ij, u in rotations.items()}
    singles = [rotations[m, m] @ SINGLES[m % 2] for m in range(6)]
    # Input singles and their disconnected product live in the diagonal spaces,
    # not in the target PNOs. Only the output legs are projected into the target.
    d = np.column_stack([bases[m, m] @ singles[m] for m in range(6)])
    pair_t = {ij: v @ t[ij] @ v.T for ij, v in bases.items()}
    pairs = list(combinations_with_replacement(range(6), 2))
    zero, one = native_snapshots(eri, o, virtual, s, pairs, bases, t, singles)
    refs, bares = {}, {}
    record = {k: {} for k in ('native_zero', 'native_difference', 'signal', 'wrong_leg',
                               'tau_vvvv', 'tau_mixed', 'half_ovov_change')}
    for ij, v in bases.items():
        i, j = ij
        proj = v.T @ s
        sm = proj @ d
        def fold(amplitude):
            # Independent four-centre contraction; ERI in (u v | x y) order.
            return np.einsum('uvxy,vy->ux', eri, amplitude)
        def mixed(kernel):
            return -v.T @ kernel @ o @ sm.T - sm @ o.T @ kernel @ v
        g = fold(pair_t[ij])
        g1 = fold(np.outer(d[:, i], d[:, j]))
        base = v.T @ g @ v
        linear = mixed(g)
        disconnected = v.T @ g1 @ v
        cubic = mixed(g1)
        ovov0, ovov_change = np.zeros_like(base), np.zeros_like(base)
        z, z1 = o.T @ g @ o, o.T @ g1 @ o
        for (m, n), amp in pair_t.items():
            tp = proj @ amp @ proj.T
            ss = np.outer(sm[:, m], sm[:, n])
            ovov0 += .5*z[m, n]*tp
            ovov_change += .5*(z[m, n]*ss + z1[m, n]*(tp+ss))
        u = rotations[ij]
        refs[ij] = u.T @ linear @ u
        bares[ij] = u.T @ base @ u
        for name, value in [('signal', linear), ('tau_vvvv', disconnected),
                            ('tau_mixed', cubic), ('half_ovov_change', ovov_change)]:
            bare.witness(record[name], ij, u.T @ value @ u, np.zeros_like(value))
        bare.witness(record['wrong_leg'], ij, u.T @ mixed(g.T) @ u, refs[ij])
        if ij in zero:
            bare.witness(record['native_zero'], ij, zero[ij], base + ovov0)
            bare.witness(record['native_difference'], ij, one[ij]-zero[ij],
                         linear + disconnected + cubic + ovov_change)
    assert all(record[k]['abs'] <= TOL for k in ('native_zero', 'native_difference'))
    assert all(record[k]['abs'] > TOL for k in ('signal', 'wrong_leg', 'tau_vvvv',
                                                 'tau_mixed', 'half_ovov_change'))
    assert sum(a.size for a in refs.values()) == 174
    return refs, bares, record


def momentum_checks(r, eri, reader):
    """Ordered (m* e | b* f) in normalized supercell Bloch columns."""
    phase = np.exp(1j*np.outer(np.arange(3)*bare.FIXTURE['lengths'][0],
                               r.kpoints_cart[:, 0])) / np.sqrt(3)
    mo = np.einsum('tk,kub->ktub', phase, r.mo_coeffs).reshape(3, 12, 4)
    allowed, forbidden, strengths = {}, {}, {}
    for k in product(range(3), repeat=4):
        m, e, b, f = k
        bands = ((m+f) % 2, 2+(e+b) % 2, 2+(e+m+b) % 2, 2+(b+f+1) % 2)
        ref = np.einsum('u,v,x,y,uvxy', mo[m, :, bands[0]].conj(), mo[e, :, bands[1]],
                        mo[b, :, bands[2]].conj(), mo[f, :, bands[3]], eri, optimize=True)
        got = reader(r, k, bands=bands, max_bytes=r.terminal_transitions.required_bytes)
        if (m-e+b-f) % 3:
            assert got == 0 and abs(ref) <= FORBIDDEN
            bare.witness(forbidden, [*k, *bands], np.asarray(got), np.asarray(ref))
        else:
            q = (m-e+1) % 3 - 1
            strengths[q] = max(strengths.get(q, 0.), abs(ref))
            bare.witness(allowed, [*k, *bands], np.asarray(got), np.asarray(ref))
    assert set(strengths) == {-1, 0, 1} and min(strengths.values()) > TOL
    assert allowed['abs'] <= TOL
    return dict(allowed=allowed, forbidden=forbidden, max_abs_by_signed_transfer=strengths)


def check_actions(x, refs, bares, increments, zeros, baseline):
    spaces = x.pair_build.spaces
    errors = {k: {} for k in ('increment', 'zero_plus_bare', 'dressed_minus_bare')}
    for ij, ref in refs.items():
        inc = spaces.orient_tensor(*ij, increments)
        zero = spaces.orient_tensor(*ij, zeros)
        undressed = spaces.orient_tensor(*ij, baseline)
        assert np.count_nonzero(zero) == 0
        bare.witness(errors['increment'], ij, inc, ref)
        bare.witness(errors['zero_plus_bare'], ij, undressed+zero, bares[ij])
        bare.witness(errors['dressed_minus_bare'], ij, (undressed+inc)-bares[ij], ref)
    assert all(v['abs'] <= TOL for v in errors.values())
    return errors


def controls(r, x, ts, action, limits):
    from copy import copy
    from dataclasses import replace
    system, basis, mesh, options, kw = bare.op.rhf_fixture(3, scf=bare.SCF, **bare.FIXTURE)
    other = bare.run_pbc_bipole_rhf(system, basis, mesh, options,
                                    terminal_transition_bytes=bare.LIMIT, **kw)
    # Same shape and projector, different coordinate frame: reverse one column.
    altered = copy(x.pair_build.spaces)
    frames = list(altered.pair_coefficients)
    frames[0] = frames[0].copy()
    frames[0][:, 0] *= -1
    altered.pair_coefficients = tuple(frames)
    bad = replace(x, pair_build=replace(x.pair_build, spaces=altered))
    result = {}
    for label, owner, prepared, budget, exc, message in [
        ('foreign_generation', other, x, limits, ValueError, 'generation'),
        ('changed_frame', r, bad, limits, ValueError, 'frame'),
        ('short_bytes', r, x, dict(limits, max_bytes=limits['max_bytes']-1), MemoryError, 'bytes'),
        ('short_work', r, x, dict(limits, max_work=limits['max_work']-1), ValueError, 'work units'),
    ]:
        try:
            action(owner, prepared, ts, SINGLES, **budget)
        except exc as err:
            assert message in str(err)
            result[label] = str(err)
        else:
            raise AssertionError(f'{label} admitted')
    return result


def run(*, oracle_only=False):
    r, x, ts = prepare()
    args = reference_inputs(r, x, ts)
    refs, bares, record = oracle(*args)
    print(json.dumps(dict(oracle=record, atol=TOL, forbidden_atol=FORBIDDEN)), flush=True)
    if oracle_only:
        return record

    from vibeqc.dlpno.bipole_virtual_singles import (
        WORK_BOUND, linear_virtual_ladder, mixed_transition)
    h = r.terminal_transitions
    limits = dict(max_bytes=h.required_bytes, max_work=WORK_BOUND)
    refusals = controls(r, x, ts, linear_virtual_ladder, limits)
    inc = linear_virtual_ladder(r, x, ts, SINGLES, **limits)
    zero = linear_virtual_ladder(r, x, ts, [np.zeros_like(a) for a in SINGLES], **limits)
    baseline = h.bare_virtual_ladder(r, x, ts, max_bytes=h.required_bytes,
                                     max_work=h.ladder_work_bound)
    ijab = (3, 1, 1, 1)
    measured = x.pair_build.spaces.orient_tensor(*ijab[:2], inc)[ijab[2:]]
    return dict(witness=dict(ijab=ijab, independent=refs[ijab[:2]][ijab[2:]], production=measured),
                source=h.identity, source_record=h.provenance, build=x.pair_build.identity,
                mp2_per_cell=x.solution.e_pair_per_cell, singles=[a.tolist() for a in SINGLES],
                doubles=[a.tolist() for a in ts], increments=[a.tolist() for a in inc],
                representatives=x.pair_build.spaces.representative_pairs,
                baseline=[a.tolist() for a in baseline], ordered_pairs=len(refs),
                components=sum(a.size for a in refs.values()), gates=dict(component=TOL,
                forbidden=FORBIDDEN), oracle=record, limits=limits, refusals=refusals,
                momentum=momentum_checks(r, args[1], mixed_transition),
                **check_actions(x, refs, bares, inc, zero, baseline))


if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--oracle-only', action='store_true')
    print(json.dumps(run(oracle_only=parser.parse_args().oracle_only)), flush=True)
