"""Independent dense-supercell oracle for both cubic occupied ooov terms.

The dense reference uses independent placed PAO/PNO frames and AO metric
projections, never the production action or its projection/panel helpers.
"""
import json
from itertools import product

import numpy as np

try:
    from . import bipole_occupied_singles as linear_case
except ImportError:
    import bipole_occupied_singles as linear_case

half_case = linear_case.half_case
fixture, bare = linear_case.fixture, linear_case.bare
SINGLES = fixture.SINGLES
TOL = 1e-10  # Absolute Ha per component, declared before production.


def oracle(inputs):
    s, eri, virtual, occ, bases, placed, amps = inputs
    rotations = {ij: v.T @ s @ placed[ij] for ij, v in bases.items()}
    d = np.column_stack([bases[m, m] @ rotations[m, m] @ SINGLES[m % 2]
                         for m in range(6)])
    previous, previous_record = linear_case.oracle(inputs)
    refs = {name: {} for name in ('x', 'y', 'cubic', 'partial')}
    negative = {name: {} for name in ('early_projection_x', 'early_projection_y',
                                     'wrong_output_transpose', 'wrong_half')}
    distinct = {}
    for ij, v in bases.items():
        i, j = ij
        u, project = rotations[ij], v.T @ s
        sm = project @ d
        # Direct dense AO contractions and all 36 ordered occupied indices.
        wx = np.einsum('uvxy,um,v,xn,y->mn', eri, occ, occ[:, i], occ, d[:, j],
                       optimize=True)
        wy = np.einsum('uvxy,um,v,xn,y->mn', eri, occ, d[:, i], occ, occ[:, j],
                       optimize=True)
        wrong_x = np.einsum('uvxy,um,v,xn,y->mn', eri, occ, occ[:, i], occ,
                            v @ project @ d[:, j], optimize=True)
        wrong_y = np.einsum('uvxy,um,v,xn,y->mn', eri, occ,
                            v @ project @ d[:, i], occ, occ[:, j], optimize=True)
        x, y, ex, ey, transpose = [np.zeros((v.shape[1],)*2) for _ in range(5)]
        for m, n in product(range(6), repeat=2):
            ss = np.outer(sm[:, m], sm[:, n])
            x += wx[m, n]*ss
            y += wy[m, n]*ss
            ex += wrong_x[m, n]*ss
            ey += wrong_y[m, n]*ss
            transpose += wx[m, n]*ss.T
        refs['x'][ij], refs['y'][ij] = u.T @ x @ u, u.T @ y @ u
        refs['cubic'][ij] = refs['x'][ij]+refs['y'][ij]
        refs['partial'][ij] = refs['cubic'][ij]+previous['partial'][ij]
        bare.witness(distinct, ij, refs['x'][ij], refs['y'][ij])
        for name, wrong, expected in (
                ('early_projection_x', ex, refs['x'][ij]),
                ('early_projection_y', ey, refs['y'][ij]),
                ('wrong_output_transpose', transpose, refs['x'][ij]),
                ('wrong_half', .5*(x+y), refs['cubic'][ij])):
            bare.witness(negative[name], ij, u.T @ wrong @ u, expected)
    assert distinct['abs'] > TOL
    assert all(w['abs'] > TOL for w in negative.values()), negative
    assert len(bases) == 36 and sum(a.size for a in refs['cubic'].values()) == 174
    native = half_case.native_snapshots(inputs)
    isolated = {ij: native['occupied_ladder'][ij]-native['bare'][ij]
                -sum(previous[k][ij] for k in ('bare_oooo', 'oooo_ss', 'linear', 'half'))
                for ij in bases}
    signals = {}
    for name, values in refs.items():
        signals[name] = {}
        for ij, value in values.items():
            bare.witness(signals[name], ij, value, np.zeros_like(value))
        assert signals[name]['abs'] > TOL
    return refs, previous, dict(
        negative=negative, distinct_legs=distinct, signals=signals,
        native_isolated_cubic=half_case.compare(isolated, refs['cubic']),
        native_isolated_x=half_case.compare(
            {ij: isolated[ij]-refs['y'][ij] for ij in bases}, refs['x']),
        native_isolated_y=half_case.compare(
            {ij: isolated[ij]-refs['x'][ij] for ij in bases}, refs['y']),
        prior_cubic_sum=half_case.compare(refs['cubic'], previous['cubic_ooov']),
        previous_native=previous_record['native'],
        wrong_snapshot_boundary=previous_record['wrong_snapshot_boundary'],
        diagonal_ao_singles=d.tolist())


def run(*, oracle_only=False):
    result, prepared, doubles = fixture.prepare()
    inputs = fixture.reference_inputs(result, prepared, doubles)
    refs, previous, 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_isolated_cubic', 'negative', 'distinct_legs')}),
          flush=True)
    if oracle_only:
        return record
    from vibeqc.dlpno.bipole_occupied_cubic import (
        WORK_BOUND, cubic_occupied_ladder_terms, resource_census)
    from vibeqc.dlpno.bipole_occupied_singles import linear_occupied_ladder_terms
    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)
    record['refusals'] = half_case.quadratic.refusals(
        result, prepared, cubic_occupied_ladder_terms, limits)
    actual = cubic_occupied_ladder_terms(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', 'cubic'))}

    record['production'] = compare(actual, refs)
    record['signed_components'] = {
        name: [dict(target=list(ij), actual=actual.placed(spaces, *ij)[leg].tolist(),
                    reference=refs[name][ij].tolist(),
                    error=(actual.placed(spaces, *ij)[leg]-refs[name][ij]).tolist())
               for ij in refs['x']]
        for leg, name in enumerate(('x', 'y', 'cubic'))}
    record['scaling'] = {}
    for beta in (0., -1.7, .6):
        scaled = cubic_occupied_ladder_terms(result, prepared, [beta*t for t in SINGLES], **limits)
        expected = {k: {ij: beta**3*v for ij, v in refs[k].items()} for k in ('x', 'y', 'cubic')}
        record['scaling'][str(beta)] = compare(scaled, expected)
        if beta == 0:
            assert all(np.count_nonzero(a) == 0 for leg in scaled 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
    # Separate actions, individually reserved, with no change to the earlier
    # provider/actions. Compare earlier outputs to the accepted receipt too.
    linear = linear_occupied_ladder_terms(result, prepared, doubles, SINGLES, **limits)
    half = half_virtual_ladder(result, prepared, doubles, SINGLES, **limits)
    earlier = tuple(a+b for a, b in zip(linear.total, half.total, strict=True))
    partial = tuple(a+b for a, b in zip(earlier, actual.total, strict=True))
    def ordered(values):
        return {ij: spaces.orient_tensor(*ij, values) for ij in refs['x']}
    record['signed_components']['partial'] = [
        dict(target=list(ij), actual=value.tolist(), reference=refs['partial'][ij].tolist(),
             error=(value-refs['partial'][ij]).tolist()) for ij, value in ordered(partial).items()]
    record.update(
        reversal=reversal, missing_reversal_leg_exchange=wrong,
        earlier_linear={name: half_case.compare(
            {ij: linear.placed(spaces, *ij)[leg] for ij in refs['x']}, previous[name])
            for leg, name in enumerate(('x', 'y', 'linear'))},
        earlier_half=half_case.compare(ordered(half.total), previous['half']),
        earlier_partial=half_case.compare(ordered(earlier), previous['partial']),
        partial=half_case.compare(ordered(partial), refs['partial']),
        resources=resource_census(), limits=limits, partial_assembly_work=3*WORK_BOUND,
        outputs={k: [a.tolist() for a in values] for k, values in
                 [('cubic_x', actual.x), ('cubic_y', actual.y), ('cubic', actual.total),
                  ('x', linear.x), ('y', linear.y), ('linear', linear.total),
                  ('half', half.total), ('earlier_partial', earlier), ('partial', partial)]},
        coverage=['cubic ooov X', 'cubic ooov Y', 'fixed-T2 ooov X', 'fixed-T2 ooov Y',
                  'full half-weighted tau*(Z+Z1)'],
        remaining=['oooo*T2 with active T1-free owner', 'oooo*ss'])
    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)
