"""Independent finite-operator oracle for the fixed-T2 ooov occupied dressings.

Only the two terms linear in diagonal singles are production-qualified here.
The other occupied terms are explicitly accounted for to isolate the native
occupied_ladder-minus-bare snapshot. No production projection helper enters
the dense reference.
"""
import json
from itertools import product
import numpy as np

try:
    from . import bipole_virtual_half as half_case
except ImportError:
    import bipole_virtual_half as half_case

fixture, bare = half_case.fixture, half_case.bare
SINGLES = fixture.SINGLES
TOL = 1e-10  # Absolute Ha per component, fixed before production.
FORBIDDEN = 1e-12


def momentum_checks(result, eri):
    from vibeqc.dlpno.bipole_occupied_singles import occupied_mixed_transition
    h = result.terminal_transitions
    phase = np.exp(1j*np.outer(np.arange(3)*bare.FIXTURE['lengths'][0],
                               result.kpoints_cart[:, 0]))/np.sqrt(3)
    mo = np.einsum('tk,kub->ktub', phase, result.mo_coeffs).reshape(3, 12, 4)
    choices, allowed, forbidden, witnesses = {}, {}, {}, {}
    count = 0
    for k in product(range(3), repeat=4):
        p, q, r, t = k
        ref = np.einsum('uvxy,ua,vb,xc,yd->abcd', eri, mo[p][:, :2].conj(),
                         mo[q][:, :2], mo[r][:, :2].conj(), mo[t][:, 2:], optimize=True)
        if (p-q+r-t) % 3:
            for idx in product(range(2), repeat=4):
                bands = (*idx[:3], 2+idx[3])
                got = occupied_mixed_transition(result, k, bands=bands, max_bytes=h.required_bytes)
                assert got == 0 and abs(ref[idx]) <= FORBIDDEN
                bare.witness(forbidden, (*k, *bands), np.asarray(got), np.asarray(ref[idx]))
                count += 1
        else:
            idx = np.unravel_index(abs(ref).argmax(), ref.shape)
            transfer = (p-q+1) % 3-1
            if transfer not in choices or abs(ref[idx]) > abs(choices[transfer][2]):
                choices[transfer] = k, tuple(map(int, (*idx[:3], 2+idx[3]))), ref[idx]
    for transfer, (k, bands, ref) in choices.items():
        got = occupied_mixed_transition(result, k, bands=bands, max_bytes=h.required_bytes)
        assert abs(ref) > TOL
        bare.witness(allowed, (*k, *bands), np.asarray(got), np.asarray(ref))
        witnesses[transfer] = dict(momenta=k, bands=bands, reference=[float(ref.real), float(ref.imag)])
    assert set(choices) == {-1, 0, 1} and count == 864 and allowed['abs'] <= TOL
    return dict(allowed=allowed, forbidden=forbidden, forbidden_components=count,
                witnesses=witnesses, component_atol=TOL, forbidden_atol=FORBIDDEN)


def oracle(inputs):
    s, eri, virtual, occ, bases, placed, amps = inputs
    rotations = {ij: v.T @ s @ placed[ij] for ij, v in bases.items()}
    ao_pairs = {ij: v @ rotations[ij] @ amps[ij] @ rotations[ij].T @ v.T
                for ij, v in bases.items()}
    d = np.column_stack([bases[m, m] @ rotations[m, m] @ SINGLES[m % 2]
                         for m in range(6)])
    half_refs, _ = half_case.oracle(inputs)
    refs = {k: {} for k in ('x', 'y', 'linear', 'bare_oooo', 'oooo_ss',
                            'cubic_ooov', 'half', 'partial', 'occupied')}
    bad = {k: {} for k in ('early_projection_x', 'early_projection_y',
                           'missing_source_transpose', 'wrong_half_factor')}
    for ij, v in bases.items():
        i, j = ij
        project, u = v.T @ s, rotations[ij]
        def kernels(di, dj):
            left = np.einsum('uvxy,v,y->ux', eri, occ[:, i], dj, optimize=True)
            right = np.einsum('uvxy,v,y->ux', eri, di, occ[:, j], optimize=True)
            return occ.T @ left @ occ, occ.T @ right @ occ
        wx, wy = kernels(d[:, i], d[:, j])
        wrong_x, wrong_y = kernels(v @ project @ d[:, i], v @ project @ d[:, j])
        w0 = occ.T @ np.einsum('uvxy,v,y->ux', eri, occ[:, i], occ[:, j]) @ occ
        sm = project @ d
        terms = [np.zeros((v.shape[1], v.shape[1])) for _ in range(8)]
        x, y, base, quadratic, cubic, ex, ey, reversed_source = terms
        for (m, n), ao in ao_pairs.items():
            bmn = project @ ao @ project.T
            ss = np.outer(sm[:, m], sm[:, n])
            x += wx[m, n]*bmn
            y += wy[m, n]*bmn
            base += w0[m, n]*bmn
            quadratic += w0[m, n]*ss
            cubic += (wx[m, n]+wy[m, n])*ss
            ex += wrong_x[m, n]*bmn
            ey += wrong_y[m, n]*bmn
            wrong_b = project @ (ao.T if m > n else ao) @ project.T
            reversed_source += (wx[m, n]+wy[m, n])*wrong_b
        for name, value in zip(('x', 'y', 'bare_oooo', 'oooo_ss', 'cubic_ooov'),
                               (x, y, base, quadratic, cubic), strict=True):
            refs[name][ij] = u.T @ value @ u
        refs['linear'][ij] = refs['x'][ij]+refs['y'][ij]
        refs['half'][ij] = half_refs['half'][ij]
        refs['partial'][ij] = refs['linear'][ij]+refs['half'][ij]
        refs['occupied'][ij] = sum(refs[k][ij] for k in
                                   ('bare_oooo', 'oooo_ss', 'cubic_ooov', 'partial'))
        for name, wrong, expected in [
                ('early_projection_x', ex, refs['x'][ij]),
                ('early_projection_y', ey, refs['y'][ij]),
                ('missing_source_transpose', reversed_source, refs['linear'][ij]),
                ('wrong_half_factor', .5*(x+y), refs['linear'][ij])]:
            bare.witness(bad[name], ij, u.T @ wrong @ u, expected)
    assert all(w['abs'] > TOL for w in bad.values()), bad
    native = half_case.native_snapshots(inputs)
    increment = {ij: native['occupied_ladder'][ij]-native['bare'][ij] for ij in bases}
    native_checks = dict(complete_oracle=half_case.compare(increment, refs['occupied']),
        isolated_linear=half_case.compare({ij: increment[ij]-sum(refs[k][ij] for k in
            ('bare_oooo', 'oooo_ss', 'cubic_ooov', 'half')) for ij in bases}, refs['linear']))
    boundary = {}
    for ij in bases:
        bare.witness(boundary, ij, native['occupied_ladder'][ij], refs['occupied'][ij])
    assert boundary['abs'] > TOL
    signals = {}
    for name in refs:
        signals[name] = {}
        for ij, value in refs[name].items():
            bare.witness(signals[name], ij, value, np.zeros_like(value))
        assert signals[name]['abs'] > TOL
    return refs, dict(negative=bad, native=native_checks, wrong_snapshot_boundary=boundary,
                      signals=signals, diagonal_ao_singles=d.tolist())


def run(*, oracle_only=False):
    result, prepared, doubles = fixture.prepare()
    inputs = fixture.reference_inputs(result, prepared, doubles)
    refs, record = oracle(inputs)
    spaces = prepared.pair_build.spaces
    record.update(source=result.terminal_transitions.identity,
                  source_record=result.terminal_transitions.provenance,
                  pair_build=prepared.pair_build.identity,
                  singles=[a.tolist() for a in SINGLES], doubles=[a.tolist() for a in doubles],
                  pair_frames=[a.tolist() for a in spaces.pair_coefficients],
                  pair_ao_domains=[a.tolist() for a in prepared.domain_selection.pair_ao_domains],
                  representatives=spaces.representative_pairs, ranks=list(spaces.pair_ranks),
                  raw_mp2=prepared.solution.e_pair_per_cell, atol=TOL,
                  ordered_targets=36, components_per_comparison=174)
    print(json.dumps({k: record[k] for k in ('native', 'negative')}), flush=True)
    if oracle_only:
        return record
    from vibeqc.dlpno.bipole_occupied_singles import (
        WORK_BOUND, linear_occupied_ladder_terms, resource_census)
    from vibeqc.dlpno.bipole_virtual_half import half_virtual_ladder

    h = result.terminal_transitions
    limits = dict(max_bytes=h.required_bytes, max_work=WORK_BOUND)
    def action(r, p, singles, **budget):
        return linear_occupied_ladder_terms(r, p, doubles, singles, **budget)
    record['refusals'] = half_case.quadratic.refusals(result, prepared, action, limits)
    record['ooov_momentum'] = momentum_checks(result, inputs[1])
    actual = action(result, prepared, SINGLES, **limits)
    def compare(parts, reference):
        return {name: half_case.compare({ij: parts.placed(spaces, *ij)[leg] for ij in refs['x']},
                                        reference[name])
                for leg, name in enumerate(('x', 'y', 'linear'))}
    record['production'] = compare(actual, refs)
    record['scaling'] = {}
    cases = [('zero_singles', 1., (0., 0.)), ('zero_doubles', 0., (1., 1.)),
             ('doubles', -.7, (1., 1.)), ('first_single', 1., (-1.7, 1.)),
             ('second_single', 1., (1., .6)), ('both_singles', 1., (-1.7, .6))]
    for name, alpha, beta in cases:
        got = linear_occupied_ladder_terms(result, prepared, [alpha*t for t in doubles],
                    [b*t for b, t in zip(beta, SINGLES, strict=True)], **limits)
        expected = {k: {} for k in ('x', 'y', 'linear')}
        for i, j in refs['x']:
            expected['x'][i, j] = alpha*beta[j % 2]*refs['x'][i, j]
            expected['y'][i, j] = alpha*beta[i % 2]*refs['y'][i, j]
            expected['linear'][i, j] = expected['x'][i, j]+expected['y'][i, j]
        record['scaling'][name] = dict(alpha=alpha, beta=beta, checks=compare(got, expected))
        if name.startswith('zero_'):
            assert all(np.count_nonzero(a) == 0 for leg in got for a in leg)
    reversal, wrong = {}, {}
    for ij in refs['x']:
        x, y, total = actual.placed(spaces, *ij)
        rx, ry, rt = actual.placed(spaces, *ij[::-1])
        for a, b in ((x, ry.T), (y, rx.T), (total, rt.T)):
            bare.witness(reversal, ij, a, b)
        p = spaces.resolve(*ij)
        if p.transposed:
            bare.witness(wrong, ij, actual.x[p.row].T, refs['x'][ij])
    assert reversal['abs'] <= TOL and wrong['abs'] > TOL
    half = half_virtual_ladder(result, prepared, doubles, SINGLES, **limits)
    partial = tuple(a+b for a, b in zip(actual.total, half.total, strict=True))
    record.update(reversal=reversal, missing_reversal_leg_exchange=wrong,
                  half=half_case.compare({ij: spaces.orient_tensor(*ij, half.total) for ij in refs['half']},
                                         refs['half']),
                  partial=half_case.compare({ij: spaces.orient_tensor(*ij, partial) for ij in refs['partial']},
                                            refs['partial']),
                  resources=resource_census(), limits=limits, partial_assembly_work=2*WORK_BOUND,
                  outputs={k: [a.tolist() for a in values] for k, values in
                           [('x', actual.x), ('y', actual.y), ('linear', actual.total),
                            ('half', half.total), ('partial', partial)]},
                  coverage=['fixed-T2 ooov X', 'fixed-T2 ooov Y', 'full half-weighted tau*(Z+Z1)'],
                  remaining=['oooo*T2 with active T1-free owner', 'oooo*ss', 'both cubic ooov*ss dressings'])
    assert all(not a.flags.writeable for leg in actual for a in leg)
    return record


if __name__ == '__main__':
    import sys
    print(json.dumps(run(oracle_only='--oracle-only' in sys.argv)), flush=True)
