"""Complete finite occupied family against dense and isolated native oracles.

The accepted per-leg cubic oracle supplies independent placed frames, complete
AO integrals and all previously qualified terms. No production projection
helper is used by the reference. All 36 ordered targets / 174 components
use the predeclared 1e-10 Ha gate (forbidden momentum: 1e-12 Ha).
"""
import json
from itertools import product
import numpy as np

try:
    from . import bipole_occupied_cubic as cubic_case
    from . import bipole_ccsd_ladder as band_case
except ImportError:
    import bipole_occupied_cubic as cubic_case
    import bipole_ccsd_ladder as band_case

half_case = cubic_case.half_case
fixture, bare = cubic_case.fixture, cubic_case.bare
SINGLES, TOL = fixture.SINGLES, 1e-10


def oracle(inputs):
    cubic, refs, record = cubic_case.oracle(inputs)
    half, _ = half_case.oracle(inputs)
    refs.update(cubic_x=cubic['x'], cubic_y=cubic['y'], cubic=cubic['cubic'],
                half_tt=half['tt'], earlier_partial=refs['partial'], partial=cubic['partial'])
    refs['t1_free'] = {ij: refs['bare_oooo'][ij]+half['tt'][ij] for ij in half['tt']}
    native = half_case.native_snapshots(inputs)
    increment = {ij: native['occupied_ladder'][ij]-native['bare'][ij] for ij in half['tt']}
    record['complete_native_oracle'] = half_case.compare(increment, refs['occupied'])
    record['isolated_bare'] = half_case.compare({ij: increment[ij]-sum(refs[k][ij]
        for k in ('oooo_ss', 'linear', 'cubic', 'half')) for ij in increment}, refs['bare_oooo'])
    record['isolated_disconnected'] = half_case.compare({ij: increment[ij]-sum(refs[k][ij]
        for k in ('bare_oooo', 'linear', 'cubic', 'half')) for ij in increment}, refs['oooo_ss'])
    negative = {k: {} for k in ('missing_reverse_pairs', 'double_diagonal',
                               'cumulative_occupied', 'virtual_boundary', 'double_half_tt')}
    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)])
    for ij, v in bases.items():
        i, j = ij
        u, sm = rotations[ij], v.T @ s @ d
        w = np.einsum('uvxy,um,v,xn,y->mn', eri, occ, occ[:, i], occ, occ[:, j], optimize=True)
        missing, diagonal = np.zeros((len(sm), len(sm))), np.zeros((len(sm), len(sm)))
        for m, n in product(range(6), repeat=2):
            term = w[m, n]*np.outer(sm[:, m], sm[:, n])
            if m <= n:
                missing += term
            if m == n:
                diagonal += term
        controls = dict(missing_reverse_pairs=u.T @ missing @ u,
                        double_diagonal=refs['oooo_ss'][ij]+u.T @ diagonal @ u,
                        cumulative_occupied=native['occupied_ladder'][ij],
                        virtual_boundary=native['virtual_ladder'][ij]-native['bare'][ij],
                        double_half_tt=refs['occupied'][ij]+half['tt'][ij])
        for name, value in controls.items():
            expected = refs['oooo_ss'][ij] if name in ('missing_reverse_pairs','double_diagonal') else refs['occupied'][ij]
            bare.witness(negative[name], ij, value, expected)
    assert all(w['abs'] > TOL for w in negative.values()), negative
    record['complete_negative_controls'] = negative
    return refs, increment, record


def run():
    from vibeqc.dlpno.bipole_ccsd import (
        oooo_occupied_terms, complete_occupied_ladder, occupied_resource_census)
    from vibeqc.dlpno.bipole_virtual_half import WORK_BOUND

    result, prepared, doubles = fixture.prepare()
    inputs = fixture.reference_inputs(result, prepared, doubles)
    refs, increment, record = oracle(inputs)
    spaces, h = prepared.pair_build.spaces, result.terminal_transitions
    limits = dict(max_bytes=h.required_bytes, max_work=WORK_BOUND)
    def action(r, p, singles, **budget):
        return oooo_occupied_terms(r, p, doubles, singles, **budget)
    record['refusals'] = half_case.quadratic.refusals(result, prepared, action, limits)
    full = complete_occupied_ladder(result, prepared, doubles, SINGLES,
                                    max_bytes=h.required_bytes, max_work=4*WORK_BOUND)
    def ordered(values):
        # An individual mixed leg reverses into the OTHER leg, transposed.
        # Only totals and unmixed terms use the ordinary pair orientation.
        for terms in (full['linear'], full['cubic']):
            for leg in (0, 1):
                if values is terms[leg]:
                    return {ij: terms.placed(spaces, *ij)[leg] for ij in refs['occupied']}
        return {ij: spaces.orient_tensor(*ij, values) for ij in refs['occupied']}
    outputs = dict(bare_oooo=full['oooo']['doubles'], oooo_ss=full['oooo']['singles'],
        x=full['linear'].x, y=full['linear'].y, linear=full['linear'].total,
        cubic_x=full['cubic'].x, cubic_y=full['cubic'].y, cubic=full['cubic'].total,
        half=full['half'].total, half_tt=full['half'].tt, t1_free=full['t1_free'], occupied=full['total'])
    outputs['earlier_partial'] = tuple(a+b for a,b in zip(outputs['linear'], outputs['half'], strict=True))
    outputs['partial'] = tuple(a+b for a,b in zip(outputs['earlier_partial'], outputs['cubic'], strict=True))
    record['production'] = {k: half_case.compare(ordered(v), refs[k]) for k,v in outputs.items()}
    record['production_native'] = half_case.compare(ordered(full['total']), increment)
    print(json.dumps(dict(production=record['production'], native=record['production_native'])), flush=True)
    record['signed_components'] = {k: [dict(target=list(ij), actual=a.tolist(),
        reference=refs[k][ij].tolist(), error=(a-refs[k][ij]).tolist())
        for ij,a in ordered(v).items()] for k,v in outputs.items()}
    record['native_components'] = [dict(target=list(ij), actual=a.tolist(),
        reference=increment[ij].tolist(), error=(a-increment[ij]).tolist())
        for ij,a in ordered(full['total']).items()]
    scaling = {}
    for beta in (0., -1.7, .6):
        got = action(result, prepared, [beta*t for t in SINGLES], **limits)
        scaling[str(beta)] = half_case.compare(ordered(got['singles']),
                                  {ij: beta**2*refs['oooo_ss'][ij] for ij in refs['oooo_ss']})
        half_case.compare(ordered(got['doubles']), refs['bare_oooo'])
        if beta == 0:
            assert all(np.count_nonzero(a)==0 for a in got['singles'])
    zero = oooo_occupied_terms(result, prepared, [np.zeros_like(t) for t in doubles],
                              SINGLES, **limits)
    assert all(np.count_nonzero(a)==0 for a in zero['doubles'])
    half_case.compare(ordered(zero['singles']), refs['oooo_ss'])
    reversal = {}
    for name in ('bare_oooo','oooo_ss','t1_free','occupied'):
        values, witness = ordered(outputs[name]), {}
        for ij,a in values.items():
            bare.witness(witness,ij,a,values[ij[::-1]].T)
        assert witness['abs'] <= TOL
        reversal[name]=witness
    # Admission must reject the full four-action work reservation before reading.
    for name, budget in [('one_work_below', dict(max_bytes=h.required_bytes,max_work=4*WORK_BOUND-1)),
                         ('one_byte_below',dict(max_bytes=h.required_bytes-1,max_work=4*WORK_BOUND))]:
        try:
            complete_occupied_ladder(result,prepared,doubles,SINGLES,**budget)
        except (ValueError,MemoryError) as exc:
            record['refusals']['assembly_'+name]=str(exc)
        else:
            raise AssertionError(name)
    assert len(refs['occupied'])==36 and sum(a.size for a in refs['occupied'].values())==174
    assert all(not a.flags.writeable for values in outputs.values() for a in values
               if values is not outputs['partial'] and values is not outputs['earlier_partial'])
    record.update(source=h.identity, source_record=h.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, scaling=scaling, reversal=reversal,
        resources=occupied_resource_census(), limits=limits,
        outputs={k:[a.tolist() for a in v] for k,v in outputs.items()},
        coverage='Complete occupied_ladder minus bare on the accepted finite fixture',
        next_unqualified='R2 occupied/virtual Fock intermediates and their singles dressings; rings and R1 also remain',
        verdict='PASS')
    return record


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