"""Per-leg regression for the linear-in-singles, fixed-T2 virtual ladder.

In cpp/src/dlpno_ccsd.cpp, G_P[a,f] = sum_e B_P[a,e] T[e,f] and
H_P[b,e] = sum_f B_P[b,f] T[e,f] (the latter uses T.transpose()).
Thus X[m,a] = sum_ef (a e | m f) T[e,f] and
Y[m,b] = sum_ef (m e | b f) T[e,f]. For p=(i,j), the two updates are
-X.T @ s and -s.T @ Y, with s[m,:] = V_p.T S V_mm t1_m. T is ordered
doubles, not tau: T_ji = T_ij.T. Pair reversal exchanges X and Y as
well as transposing each residual. The bare vvvv action, disconnected
singles product and half-weighted ovov action do not enter either leg.

The oracle transforms the explicit twelve-AO Coulomb tensor in the *placed*
independent PAO/PNO frames before contracting. No band blocks, production
singles transport, exchange symmetrization, orbit weight or cell factor.
"""

import numpy as np

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


def reference_frames(result, prepared):
    s, f, eri, _, canonical = bare.supercell_operands(result, bare.op.GaussianCell(**bare.FIXTURE))
    occ = np.asarray(prepared.occupied_selection.occupied)
    build = prepared.pair_build
    spaces = build.spaces
    _, _, paos = bare.pair_spaces(s, occ, canonical[:, :6], list(range(4)), bare.CUTOFF)
    rows = [dict(bands=bands.tolist(), R=int(R[0]), pno_rank=rank, occupations=ev.tolist())
            for bands, R, rank, ev in zip(spaces.plan.band_pairs, spaces.plan.displacements,
                                          build.pno_ranks, build.occupations, strict=True)]
    bases, _, projector, _ = bare.pno_comparison(s, f, eri, occ, paos, rows,
                                                 spaces.pair_coefficients, bare.PNO_CUTOFF)
    placed = {}
    for row, (spec, home) in enumerate(zip(rows, spaces.pair_coefficients, strict=True)):
        i, j = spec['bands']
        for cell in range(3):
            p, q = cell*2 + i, 2*((cell + spec['R']) % 3) + j
            v = np.roll(home, cell*4, axis=0)
            for ij in {(p, q), (q, p)}:
                assert ij not in placed
                placed[ij] = row, (ij != (p, q)), bases[ij].T @ s @ v
    assert len(placed) == len(bases) == 36
    return s, eri, occ, bases, placed, projector


def dense_legs(eri, occ, v, t, s_m):
    """Real ordered (a e | m f) and (m e | b f), in independent target PNOs."""
    aemf = np.einsum('uvxy,ua,ve,xm,yf->aemf', eri, v, v, occ, v, optimize=True)
    mebf = np.einsum('uvxy,um,ve,xb,yf->mebf', eri, occ, v, v, v, optimize=True)
    return (-np.einsum('aemf,ef,mb->ab', aemf, t, s_m, optimize=True),
            -np.einsum('mebf,ef,ma->ab', mebf, t, s_m, optimize=True))


def compare_legs(frames, singles, doubles, placed_terms):
    """All outputs in representative production frames; singles are home diagonals."""
    s, eri, occ, bases, placed, projector = frames
    singles_ao = np.column_stack([bases[m, m] @ (placed[m, m][2] @ singles[m % 2])
                                  for m in range(6)])
    errors = {name: {} for name in ('X', 'Y', 'sum', 'omitted_transpose')}
    by_rank = {r: {name: {} for name in ('X', 'Y', 'sum')} for r in (2, 3)}
    counts = {2: 0, 3: 0}
    for ij, (row, swapped, u) in placed.items():
        i, j = ij
        v = bases[ij]
        sm = singles_ao.T @ s @ v
        t = doubles[row].T if swapped else doubles[row]
        x, y = dense_legs(eri, occ, v, u @ t @ u.T, sm)
        rx, ry = u.T @ x @ u, u.T @ y @ u
        gx, gy, gs = placed_terms(i, j)
        labels = (row, i, j)
        rank = v.shape[1]
        counts[rank] += rank**2
        for name, got, ref in [('X', gx, rx), ('Y', gy, ry), ('sum', gs, rx+ry)]:
            assert got.shape == ref.shape and np.isfinite(got).all() and np.isfinite(ref).all()
            bare.witness(errors[name], labels, got, ref)
            bare.witness(by_rank[rank][name], labels, got, ref)
        if swapped:
            # Omit the transpose on T_ji, keep placement, projection and integrals fixed.
            wrong = dense_legs(eri, occ, v, u @ t.T @ u.T, sm)
            bare.witness(errors['omitted_transpose'], labels, u.T @ (wrong[0]+wrong[1]) @ u,
                         rx+ry)
    assert sum(counts.values()) == 174 and min(counts.values()) > 0
    for name in ('X', 'Y', 'sum'):
        assert errors[name]['abs'] <= bare.ACTION_TOL, (name, errors[name])
    assert errors['omitted_transpose']['abs'] > bare.ACTION_TOL
    return dict(ordered_pairs=len(placed), per_leg_components=counts,
                projector_error=projector, worst=errors, worst_by_rank=by_rank)


def run():
    from dataclasses import replace
    from functools import partial

    try:
        from . import bipole_virtual_singles as fixture
    except ImportError:
        import bipole_virtual_singles as fixture
    from vibeqc.dlpno.bipole_virtual_singles import (
        WORK_BOUND, linear_virtual_ladder_terms, mixed_transition,
    )

    r, prepared, doubles = fixture.prepare()
    spaces = prepared.pair_build.spaces
    h = r.terminal_transitions
    limits = dict(max_bytes=h.required_bytes, max_work=WORK_BOUND)
    # Use a second live terminal handle, including the explicit mismatched
    # handle/result case, without modifying either live result.
    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)
    controls = {}
    for name, owner, budget, exc, msg in [
        ('foreign_handle', replace(r, terminal_transitions=other.terminal_transitions),
         limits, ValueError, 'different terminal result'),
        ('foreign_preparation', other, limits, ValueError, 'same terminal generation'),
        ('short_bytes', r, dict(limits, max_bytes=h.required_bytes-1), MemoryError, 'bytes'),
        ('short_work', r, dict(limits, max_work=WORK_BOUND-1), ValueError, 'work units'),
    ]:
        try:
            linear_virtual_ladder_terms(owner, prepared, doubles, fixture.SINGLES, **budget)
        except exc as err:
            assert msg in str(err), (name, str(err))
            controls[name] = str(err)
        else:
            raise AssertionError(f'{name} admitted')
    zero = linear_virtual_ladder_terms(r, prepared, doubles, [0*t for t in fixture.SINGLES],
                                       **limits)
    assert all(np.count_nonzero(mat) == 0 for leg in zero for mat in leg)
    frames = reference_frames(r, prepared)
    parts = linear_virtual_ladder_terms(r, prepared, doubles, fixture.SINGLES, **limits)
    checked = compare_legs(frames, fixture.SINGLES, doubles, partial(parts.placed, spaces))
    momentum = fixture.momentum_checks(r, frames[1], mixed_transition)
    return dict(**checked, controls=controls, momentum=momentum, zero_singles_max=0.,
                source=h.identity, source_record=h.provenance, pair_build=prepared.pair_build.identity,
                mp2_per_cell=prepared.solution.e_pair_per_cell, limits=limits,
                mesh=list(bare.MESH), tcut_mkn=bare.CUTOFF, tcut_pno=bare.PNO_CUTOFF, tcut_pairs=0.,
                gates=dict(component=bare.ACTION_TOL, forbidden=bare.FORBIDDEN_TOL),
                ranks=list(spaces.pair_ranks), representatives=spaces.representative_pairs,
                singles=[a.tolist() for a in fixture.SINGLES], doubles=[a.tolist() for a in doubles],
                components={k: [r.tolist() for r in values] for k, values in parts._asdict().items()})


if __name__ == '__main__':
    import json
    print(json.dumps(run()), flush=True)
