"""Bare four-virtual CCSD action on the finite four-band BIPOLE fixture."""
import json
from itertools import product

import numpy as np

try:
    from .bipole_spatial_mp2 import (CUTOFF, FIXTURE, LIMIT, MESH, PNO_CUTOFF, SCF,
                                     op, pair_spaces, pno_comparison, supercell_operands)
except ImportError:  # direct script invocation
    from bipole_spatial_mp2 import (CUTOFF, FIXTURE, LIMIT, MESH, PNO_CUTOFF, SCF,
                                    op, pair_spaces, pno_comparison, supercell_operands)

from vibeqc import _vibeqc_core as native
from vibeqc import run_pbc_bipole_rhf
from vibeqc.dlpno.translation_driver import run_translation_dlpno_mp2

# Absolute Ha, for normalized BvK integrals and unweighted residuals.
ACTION_TOL = 1e-10
FORBIDDEN_TOL = 1e-12


def witness(record, key, actual, expected):
    error = np.asarray(actual - expected)
    at = np.unravel_index(abs(error).argmax(), error.shape)
    z = error[at]
    if abs(z) >= record.get('abs', 0.):
        record.update(index=[*key, *map(int, at)], real=float(z.real), imag=float(z.imag),
                      abs=float(abs(z)), actual=[float(actual[at].real), float(actual[at].imag)],
                      reference=[float(expected[at].real), float(expected[at].imag)])


def bloch_checks(r, eri):
    """Independent normalized Bloch coefficients in the twelve-AO cell."""
    h = r.terminal_transitions
    cells = np.arange(3) * FIXTURE['lengths'][0]
    phase = np.exp(1j * cells[:, None] * r.kpoints_cart[:, 0]) / np.sqrt(3)
    v = np.einsum('tk,kub->ktub', phase, np.asarray(r.mo_coeffs)[:, :, 2:]).reshape(3, 12, 2)
    # AO axes are independently ordered (a* e | b* f); no native q selection.
    allowed, forbidden, amplitudes = {}, {}, {}
    for k in product(range(3), repeat=4):
        a, e, b, f = k
        cols = ((a+f) % 2, (e+b) % 2, (a+e+b) % 2, (b+f+1) % 2)
        bands = tuple(i+2 for i in cols)
        ref = np.einsum('u,v,x,y,uvxy', v[a, :, cols[0]].conj(), v[e, :, cols[1]],
                        v[b, :, cols[2]].conj(), v[f, :, cols[3]], eri, optimize=True)
        got = h.virtual_transition(*k, bands=bands, max_bytes=h.required_bytes)
        q = (a-e+1) % 3 - 1
        labels = [*k, *bands]
        if (a-e+b-f) % 3:
            if not (abs(got) <= FORBIDDEN_TOL and abs(ref) <= FORBIDDEN_TOL):
                raise AssertionError(('forbidden', labels, got, ref))
            witness(forbidden, labels, np.asarray(got), np.asarray(ref))
        else:
            witness(allowed, labels, np.asarray(got), np.asarray(ref))
            amplitudes[q] = max(amplitudes.get(q, 0.), abs(ref))
    assert allowed['abs'] <= ACTION_TOL and min(amplitudes.values()) > ACTION_TOL
    assert set(amplitudes) == {-1, 0, 1}
    return dict(allowed=allowed, forbidden=forbidden, max_abs_by_transfer=amplitudes)


def isolated_native(eri, t):
    """Feed only Bvv to the actual shared evaluator. All dressing is then zero.

    Signed spectral resolution of the independent pair ERIs is test-only:
    never assume this finite operator is a positive auxiliary Gram.
    """
    n = len(t)
    gram = eri.reshape(n*n, n*n)
    op.near(gram, gram.T, 1e-12)
    ev, u = np.linalg.eigh(gram)
    out = np.zeros_like(t)
    for sign in (-1, 1):
        mask = sign*ev > 0
        if not mask.any():
            continue
        vv = np.ascontiguousarray(np.sqrt(sign*ev[mask])[:, None] * u[:, mask].T)
        p = len(vv)
        zeros = np.zeros_like(t)
        result = native._dlpno_ccsd_pno_evaluate(
            np.zeros((p, 2*n)), np.zeros((p, 4)), vv,
            -np.eye(2), np.zeros((2, n)), np.eye(n), [0, 0, 1], [0, 1, 1],
            [np.eye(n)]*3, [np.ones(n)]*3, [zeros]*3, [zeros, t, zeros],
            [[0, 1]]*3, [np.zeros(n)]*2, True)
        terms = result['doubles_terms'][1]
        out += sign*(terms['virtual_ladder'] - terms['occupied_ladder'])
    return out


def checks(r, prepared, ts, actions):
    s, fock, eri, _, canonical = supercell_operands(r, op.GaussianCell(**FIXTURE))
    build = prepared.pair_build
    spaces = build.spaces
    occ = prepared.occupied_selection.occupied
    _, _, paos = pair_spaces(s, occ, canonical[:, :6], list(range(4)), CUTOFF)
    rows = [dict(bands=ij.tolist(), R=int(R[0]), pno_rank=n, occupations=ev.tolist())
            for ij, R, n, ev in zip(spaces.plan.band_pairs, spaces.plan.displacements,
                                    build.pno_ranks, build.occupations, strict=True)]
    bases, _, projector, _ = pno_comparison(s, fock, eri, occ, paos, rows,
                                            spaces.pair_coefficients, PNO_CUTOFF)
    worst, wrong, factorized = {}, {}, {}
    seen = set()
    count = 0
    for row, (spec, home, t) in enumerate(zip(rows, spaces.pair_coefficients, ts, strict=True)):
        i, j = spec['bands']
        for cell in range(3):
            p, q = 2*cell+i, 2*((cell+spec['R']) % 3)+j
            v = np.roll(home, 4*cell, axis=0)
            for ij, amplitude in [((p, q), t)] + ([((q, p), t.T)] if p != q else []):
                assert ij not in seen
                seen.add(ij)
                op.near(spaces.orient_tensor(*ij, ts), amplitude, 0.)
                basis = bases[ij]
                u = basis.T @ s @ v  # production coordinates -> independent PNO coordinates
                tensor = np.einsum('ua,ve,xb,yf,uvxy->aebf', basis, basis, basis, basis,
                                   eri, optimize=True)
                amp = u @ amplitude @ u.T
                ref = u.T @ np.einsum('aebf,ef->ab', tensor, amp) @ u
                got = spaces.orient_tensor(*ij, actions)
                witness(worst, [row, *ij], got, ref)
                count += got.size
                if p != q:
                    bad = u.T @ np.einsum('afbe,ef->ab', tensor, amp) @ u
                    witness(wrong, [row, *ij], bad, ref)
                if cell == 0 and ij == (p, q):
                    witness(factorized, [row, *ij], got, u.T @ isolated_native(tensor, amp) @ u)
    assert len(seen) == 36 and set(build.pno_ranks) == {2, 3}
    assert worst['abs'] <= ACTION_TOL and factorized['abs'] <= ACTION_TOL
    assert wrong['abs'] > ACTION_TOL
    return dict(rows=rows, components=count, ordered_pairs=len(seen), max_projector=projector,
                action=worst, swapped=wrong, isolated_native=factorized, **bloch_checks(r, eri))


def run():
    system, basis, mesh, options, kw = op.rhf_fixture(3, scf=SCF, **FIXTURE)
    r = run_pbc_bipole_rhf(system, basis, mesh, options, terminal_transition_bytes=LIMIT, **kw)
    h = r.terminal_transitions
    x = run_translation_dlpno_mp2(r, MESH, factor_handle=h, max_factor_bytes=h.required_bytes,
                                  tcut_mkn=CUTOFF, tcut_pno=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
    op.near(x.solution.e_pair_per_cell, -0.0407466307096963, 1e-10)
    spaces = x.pair_build.spaces
    rng = np.random.default_rng(586)
    ts = []
    for (i, j), n in zip(spaces.representative_pairs, spaces.pair_ranks, strict=True):
        t = rng.normal(size=(n, n))*0.125
        ts.append((t+t.T)/2 if i == j else t)
    controls = {}
    other = run_pbc_bipole_rhf(system, basis, mesh, options, terminal_transition_bytes=LIMIT, **kw)
    for name, handle, owner, budget, work, exc, message in [
        ('foreign_handle', other.terminal_transitions, r, h.required_bytes, h.ladder_work_bound,
         ValueError, 'different terminal'),
        ('foreign_preparation', other.terminal_transitions, other, h.required_bytes, h.ladder_work_bound,
         ValueError, 'different source'),
        ('short_bytes', h, r, h.required_bytes-1, h.ladder_work_bound, MemoryError, 'bytes'),
        ('short_work', h, r, h.required_bytes, h.ladder_work_bound-1, ValueError, 'work units'),
    ]:
        try:
            handle.bare_virtual_ladder(owner, x, ts, max_bytes=budget, max_work=work)
        except exc as err:
            assert message in str(err)
            controls[name] = str(err)
        else:
            raise AssertionError(f'{name} admitted')
    actions = h.bare_virtual_ladder(r, x, ts, max_bytes=h.required_bytes, max_work=h.ladder_work_bound)
    return dict(source=h.identity, source_record=h.provenance, build=x.pair_build.identity,
                representative_pairs=spaces.representative_pairs, amplitudes=[t.tolist() for t in ts],
                residuals=[z.tolist() for z in actions], mp2_raw=x.solution.e_pair_per_cell,
                work_bound=h.ladder_work_bound, reserved_bytes=h.required_bytes,
                gates=dict(component=ACTION_TOL, forbidden=FORBIDDEN_TOL),
                controls=controls, **checks(r, x, ts, actions))


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