"""Signed AO and native checks of singles_integrals minus doubles_fme."""
from itertools import combinations_with_replacement

import numpy as np

try:
    from . import bipole_r1_fock as prior
except ImportError:  # Direct script invocation
    import bipole_r1_fock as prior

fixture, bare = prior.fixture, prior.bare
SINGLES, TOL = prior.SINGLES, 1e-10
FULL = tuple(range(6))
GATE_IMAG = 1e-12


def oracle(inputs, singles=SINGLES, *, neighborhoods=None, absent=(), wrong_order=False):
    """Dense AO chemists' integrals, independently rebuilt PNO frames."""
    s, eri, _, o, bases, placed, _ = inputs
    c = {n: bases[n,n] @ (bases[n,n].T @ s @ placed[n,n]) for n in FULL if n not in absent}
    out = {name: {} for name in ('direct', 'exchange', 'increment')}
    for i, target in c.items():
        neighbors = FULL if neighborhoods is None else neighborhoods[i]
        density = sum((np.outer(o[:,n], c[n] @ singles[n % 2]) for n in neighbors if n in c),
                      np.zeros_like(s))
        j = 2 * np.einsum('uvxy,uv,x,ya->a', eri, density, o[:,i], target, optimize=True)
        # (ni|af); the deliberately incorrect control substitutes (na|if).
        if wrong_order:
            k = -np.einsum('uvxy,uy,va,x->a', eri, density, target, o[:,i], optimize=True)
        else:
            k = -np.einsum('uvxy,uy,v,xa->a', eri, density, o[:,i], target, optimize=True)
        out['direct'][i], out['exchange'][i], out['increment'][i] = j, k, j + k
    return out


def worst(actual, reference):
    return max((dict(i=i, a=a, signed_error=float(x-y))
                for i in reference for a, (x,y) in enumerate(zip(actual[i], reference[i], strict=True))),
               key=lambda item: abs(item['signed_error']))


def negative_controls(inputs, refs):
    total = refs['increment']
    wrong = oracle(inputs, wrong_order=True)['increment']
    negative = dict(omitted_exchange=worst(refs['direct'], total),
                    wrong_exchange_order=worst(wrong, total))
    assert all(abs(row['signed_error']) > TOL for row in negative.values()), negative
    return negative


def native_difference(inputs, fock, singles=SINGLES, *, neighborhoods=None, missing_pairs=()):
    """Subtract the actual adjacent snapshots in each signed spectral sector."""
    s, eri, v, o, bases, placed, amps = inputs
    pairs = [ij for ij in combinations_with_replacement(FULL, 2) if ij not in missing_pairs]
    rot = {ij: bases[ij].T @ s @ placed[ij] for ij in pairs}
    pnos = [v.T @ s @ bases[ij] for ij in pairs]
    ts = [rot[ij] @ amps[ij] @ rot[ij].T for ij in pairs]
    t1 = [rot[i,i] @ singles[i % 2] if (i,i) in rot else np.empty(0) for i in FULL]
    out = {i: np.zeros_like(t) for i,t in enumerate(t1) if t.size}
    ev, u = np.linalg.eigh(eri.reshape(144,144))
    for sign in (-1,1,0):
        keep = sign*ev > 0
        if sign and not keep.any():
            continue
        ao = ((u[:,keep]*np.sqrt(sign*ev[keep])).T.reshape(-1,12,12)
              if sign else np.zeros((1,12,12)))
        blocks = [np.ascontiguousarray((l.T @ ao @ r).reshape(len(ao),-1))
                  for l,r in ((o,v),(o,o),(v,v))]
        f = np.zeros_like(fock) if sign else fock
        got = bare.native._dlpno_ccsd_pno_evaluate(
            *blocks, o.T@f@o, o.T@f@v, v.T@f@v, [i for i,j in pairs], [j for i,j in pairs],
            pnos, [np.full(p.shape[1],7.) for p in pnos], [np.zeros_like(t) for t in ts], ts,
            [list(neighborhoods[i] if neighborhoods and i==j else FULL) for i,j in pairs], t1, True)
        for i in out:
            terms = got['singles_terms'][i]
            delta = np.ravel(terms['singles_integrals']) - np.ravel(terms['doubles_fme'])
            out[i] += (sign or 1) * (rot[i,i].T @ delta)
    return out


def comparison(actual, reference):
    """All twelve signed errors plus their largest component."""
    record = prior.comparison(actual, reference)
    record['worst'] = worst(actual, reference)
    return record


def sparse_control(inputs, fock, tiles):
    """Nonuniform L_00, no [22] and no [01]; [11] still contributes to R_0."""
    from vibeqc.dlpno.bipole_r1_singles_integrals import _contract

    neighbors = ((0,1,2,3,5), *(FULL for _ in FULL[1:]))
    t1 = tuple(None if n==2 else SINGLES[n % 2] for n in FULL)
    got = _contract(tiles, t1, neighbors)
    ref = oracle(inputs, neighborhoods=neighbors, absent=(2,))
    native = native_difference(inputs, fock, neighborhoods=neighbors, missing_pairs=((0,1),(2,2)))
    assert all(values[2] is None for values in got.values()) and 2 not in native
    checks = {name: worst(values, ref[name]) for name,values in got.items()}
    checks['native'] = worst(native, ref['increment'])
    assert all(abs(row['signed_error']) <= TOL for row in checks.values()), checks
    other = list(neighbors)
    other[0] = (0,2,3,5)  # Incorrectly require [01] in addition to [11].
    negative = {name: worst(wrong['increment'], {0: ref['increment'][0]}) for name,wrong in (
        ('outside_target_neighborhood', oracle(inputs, absent=(2,))),
        ('included_missing_diagonal', oracle(inputs, neighborhoods=neighbors)),
        ('required_off_diagonal', oracle(inputs, neighborhoods=other, absent=(2,))))}
    assert all(abs(row['signed_error']) > TOL for row in negative.values()), negative
    return dict(L00=neighbors[0], absent_pairs=((0,1),(2,2)), worst=checks, negative=negative)


def run():
    from unittest.mock import patch
    from vibeqc.dlpno import bipole_r1_singles_integrals as action

    result, prepared, ts = fixture.prepare()
    h = result.terminal_transitions
    inputs = fixture.reference_inputs(result, prepared, ts)
    _, fock, *_ = bare.supercell_operands(result, bare.op.GaussianCell(**bare.FIXTURE))
    refs = oracle(inputs)
    native = native_difference(inputs, fock)
    assert sum(a.size for a in native.values()) == 12
    z = prepared.pair_build.spaces
    record = dict(atol=TOL, imaginary_atol=GATE_IMAG, source=h.identity, source_record=h.provenance,
                  build=prepared.pair_build.identity, ranks=list(z.pair_ranks),
                  pair_frames=[a.tolist() for a in z.pair_coefficients],
                  singles=[t.tolist() for t in SINGLES], doubles=[t.tolist() for t in ts],
                  raw_mp2=prepared.solution.e_pair_per_cell, negative=negative_controls(inputs, refs),
                  native_oracle=comparison(native, refs['increment']))
    limits = dict(max_bytes=h.required_bytes, max_work=action.WORK_BOUND)
    record['refusals'] = prior.fock_case.half_case.quadratic.refusals(
        result, prepared, action.singles_integral_terms, limits)
    # Observe the genuine leased stream; saving these amplitude-independent
    # tiles is diagnostic only, for the restricted-neighborhood comparison.
    census, imaginary, saved = [], [], []
    elements, real, mixed = type(h)._elements, action._real, action._mixed_tiles

    def count(handle, *args):
        from contextlib import closing
        domains = set()
        count = 0
        with closing(elements(handle, *args)) as stream:
            for item in stream:
                domains.add(item[0])
                count += 1
                yield item
        census.append(dict(domains=len(domains), elements=count))

    def observe(a):
        imaginary.append(float(np.max(abs(a.imag))))
        return real(a)

    def capture(*args):
        tiles = mixed(*args)
        saved.append(tiles)
        return tiles

    with patch.object(type(h), '_elements', count), patch.object(action, '_real', observe), \
            patch.object(action, '_mixed_tiles', capture):
        got = action.singles_integral_terms(result, prepared, SINGLES, **limits)
    assert census == [dict(domains=256, elements=6912)]
    assert len(imaginary)==2 and max(imaginary)<=GATE_IMAG
    record['imaginary_max'] = dict(zip(('nf_ia','ni_af'), imaginary, strict=True))
    record['resources'] = dict(action.resource_census(), observed_passes=census)
    record['production_oracle'] = {k: comparison(v, refs[k]) for k,v in got.items()}
    record['production_native'] = comparison(got['increment'], native)
    record['sparse'] = sparse_control(inputs, fock, saved.pop())
    record['scaling'] = {}
    for alpha,beta in ((0.,1.), (-1.7,1.), (1.,-2.)):
        singles = [alpha*t for t in SINGLES]
        # T2 is deliberately absent from the public action signature. Vary
        # it in the actual native evaluation, where it affects both snapshots.
        data = (*inputs[:-1], {ij: beta*t for ij,t in inputs[-1].items()})
        actual = action.singles_integral_terms(result, prepared, singles, **limits)
        want = {k: {i: alpha*v for i,v in values.items()} for k,values in refs.items()}
        if alpha==0:
            assert all(np.count_nonzero(a)==0 for values in actual.values() for a in values)
        if alpha==1:
            assert all(np.array_equal(a,b) for k in got for a,b in zip(got[k],actual[k],strict=True))
        record['scaling'][f'{alpha},{beta}'] = dict(
            pieces={k: comparison(v,want[k]) for k,v in actual.items()},
            native=comparison(actual['increment'], native_difference(data,fock,singles)))
    return record


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