"""Independent finite-supercell half term and complete virtual-ladder check.

Build every transported amplitude from its own independent PAO/PNO basis.
The four half-term monomials are TT, T*Z1, ss*Z and ss*Z1. With all doubles
scaled by a and all singles by b, their degrees are a^2, a*b^2, a*b^2, b^4.
The reference never calls the production projection or panel helpers.
"""
import json
from itertools import combinations_with_replacement

import numpy as np

try:
    from . import bipole_virtual_cubic as cubic
    from . import bipole_virtual_disconnected as quadratic
except ImportError:
    import bipole_virtual_cubic as cubic
    import bipole_virtual_disconnected as quadratic

fixture, bare = cubic.fixture, cubic.bare
SINGLES = fixture.SINGLES
TOL = 1e-10  # Absolute Ha, per component, before production is invoked.
NAMES = ('tt', 't_z1', 'ss_z', 'ss_z1')


def oracle(inputs):
    s, eri, virtual, occ, bases, placed, amps = inputs
    rotations = {ij: v.T @ s @ placed[ij] for ij, v in bases.items()}
    pair_ao = {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)])
    refs = {name: {} for name in (*NAMES, 'half', 'six', 'full', 'diagonal', 'offdiagonal')}
    negative = {name: {} for name in ('missing_output_singles', 'missing_z1',
                                     'missing_half', 'double_diagonal', 'missing_reverse_pairs')}
    grouping = {}
    for ij, v in bases.items():
        i, j = ij
        rotation = rotations[ij]
        project = v.T @ s
        sm = project @ d
        kernel_t = np.einsum('uvxy,vy->ux', eri, pair_ao[ij], optimize=True)
        kernel_s = np.einsum('uvxy,v,y->ux', eri, d[:, i], d[:, j], optimize=True)
        z, z1 = occ.T @ kernel_t @ occ, occ.T @ kernel_s @ occ
        terms = [np.zeros((v.shape[1], v.shape[1])) for _ in NAMES]
        diagonal, offdiagonal, unordered, missing_reverse = [np.zeros_like(terms[0]) for _ in range(4)]
        ordered_contributions = {}
        for (m, n), amplitude in pair_ao.items():
            bmn = project @ amplitude @ project.T
            ss = np.outer(sm[:, m], sm[:, n])
            pieces = (.5*z[m, n]*bmn, .5*z1[m, n]*bmn,
                      .5*z[m, n]*ss, .5*z1[m, n]*ss)
            for acc, value in zip(terms, pieces, strict=True):
                acc += value
            contribution = sum(pieces)
            ordered_contributions[m, n] = contribution
            if m == n:
                diagonal += contribution
            else:
                offdiagonal += contribution
            if m <= n:
                missing_reverse += contribution
        # Independent grouping: six diagonals once, fifteen off-diagonal
        # pairs with BOTH ordered contractions (not a scalar orbit weight).
        for m, n in combinations_with_replacement(range(6), 2):
            unordered += ordered_contributions[m, n]
            if m != n:
                unordered += ordered_contributions[n, m]
        half = sum(terms)
        six = (v.T @ kernel_t @ v - v.T @ kernel_t @ occ @ sm.T
               - sm @ occ.T @ kernel_t @ v + v.T @ kernel_s @ v
               - v.T @ kernel_s @ occ @ sm.T - sm @ occ.T @ kernel_s @ v)
        values = (*terms, half, six, six+half, diagonal, offdiagonal)
        for name, value in zip(refs, values, strict=True):
            refs[name][ij] = rotation.T @ value @ rotation
        bare.witness(grouping, ij, rotation.T @ unordered @ rotation, refs['half'][ij])
        for name, wrong in [('missing_output_singles', terms[0]+terms[1]),
                            ('missing_z1', terms[0]+terms[2]), ('missing_half', 2*half),
                            ('double_diagonal', half+diagonal), ('missing_reverse_pairs', missing_reverse)]:
            bare.witness(negative[name], ij, rotation.T @ wrong @ rotation, refs['half'][ij])
    assert len(bases) == 36 and sum(a.size for a in refs['half'].values()) == 174
    assert grouping['abs'] <= TOL
    assert all(w['abs'] > TOL for w in negative.values()), negative
    signals = {}
    for name in (*NAMES, 'diagonal', 'offdiagonal'):
        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=negative, ordered_vs_grouped=grouping, signals=signals,
                      diagonal_count=6, offdiagonal_ordered_count=30,
                      independent_diagonal_ao_singles=d.tolist())


def native_snapshots(inputs):
    """Read adjacent cumulative native snapshots, not the full R2 residual.

    A signed spectral resolution of the AO operator supplies the actual
    shared evaluator. It is reference-only; production never factors ERIs.
    Nonzero K is supplied to expose an incorrect initial/cumulative boundary.
    """
    s, eri, virtual, occ, bases, placed, amps = inputs
    pairs = list(combinations_with_replacement(range(6), 2))
    rotations = {ij: bases[ij].T @ s @ placed[ij] for ij in bases}
    pnos = [virtual.T @ s @ bases[ij] for ij in pairs]
    t2 = [rotations[ij] @ amps[ij] @ rotations[ij].T for ij in pairs]
    t1 = [rotations[m, m] @ SINGLES[m % 2] for m in range(6)]
    ev, eigenvectors = np.linalg.eigh(eri.reshape(144, 144))
    snapshots = {name: {ij: np.zeros_like(t) for ij, t in zip(pairs, t2, strict=True)}
                 for name in ('bare', 'occupied_ladder', 'virtual_ladder')}
    for sign in (-1, 1):
        keep = sign*ev > 0
        ao = (eigenvectors[:, keep]*np.sqrt(sign*ev[keep])).T.reshape(-1, 12, 12)
        factors = [np.ascontiguousarray((left.T @ ao @ right).reshape(len(ao), -1))
                   for left, right in ((occ, virtual), (occ, occ), (virtual, virtual))]
        ov = factors[0].reshape(-1, 6, 6)
        k = [(ov[:, i] @ p).T @ (ov[:, j] @ p)
             for (i, j), p in zip(pairs, pnos, strict=True)]
        result = bare.native._dlpno_ccsd_pno_evaluate(
            *factors, -np.eye(6), np.zeros((6, 6)), np.eye(6),
            [i for i, j in pairs], [j for i, j in pairs], pnos,
            [np.ones(p.shape[1]) for p in pnos], k, t2,
            [list(range(6)) for _ in pairs], t1, True)
        for ij, terms in zip(pairs, result['doubles_terms'], strict=True):
            assert all(name in terms for name in snapshots)
            for name, blocks in snapshots.items():
                blocks[ij] += sign*terms[name]
    ordered = {name: {} for name in snapshots}
    for ij in bases:
        key = tuple(sorted(ij))
        gauge = bases[key].T @ s @ placed[ij]
        for name, blocks in snapshots.items():
            value = blocks[key].T if ij[0] > ij[1] else blocks[key]
            ordered[name][ij] = gauge.T @ value @ gauge
    ordered['increment'] = {ij: ordered['virtual_ladder'][ij]-ordered['occupied_ladder'][ij]
                            for ij in bases}
    return ordered


def compare(actual, reference):
    worst, ranks = {}, {2: {}, 3: {}}
    for ij, expected in reference.items():
        assert actual[ij].shape == expected.shape and np.isfinite(actual[ij]).all()
        bare.witness(worst, ij, actual[ij], expected)
        bare.witness(ranks[len(expected)], ij, actual[ij], expected)
    assert worst['abs'] <= TOL, worst
    return dict(worst=worst, by_rank=ranks)


def run(*, oracle_only=False):
    result, prepared, doubles = fixture.prepare()
    inputs = fixture.reference_inputs(result, prepared, doubles)
    refs, record = oracle(inputs)
    native = native_snapshots(inputs)
    record['native_full'] = compare(native['increment'], refs['full'])
    record['native_isolated_half'] = compare(
        {ij: native['increment'][ij]-refs['six'][ij] for ij in refs['half']}, refs['half'])
    boundaries = {}
    for name in ('bare', 'occupied_ladder', 'virtual_ladder'):
        boundaries[name] = {}
        for ij, value in native[name].items():
            bare.witness(boundaries[name], ij, value, np.zeros_like(value))
    wrong = {}
    for ij in refs['full']:
        bare.witness(wrong, ij, native['virtual_ladder'][ij]-native['bare'][ij], refs['full'][ij])
    assert wrong['abs'] > TOL
    record.update(snapshot_signals=boundaries, wrong_snapshot_boundary=wrong,
                  source=result.terminal_transitions.identity, source_record=result.terminal_transitions.provenance,
                  pair_build=prepared.pair_build.identity, atol=TOL,
                  singles=[a.tolist() for a in SINGLES], doubles=[a.tolist() for a in doubles],
                  pair_ao_domains=[a.tolist() for a in prepared.domain_selection.pair_ao_domains],
                  pair_frames=[a.tolist() for a in prepared.pair_build.spaces.pair_coefficients],
                  representatives=prepared.pair_build.spaces.representative_pairs,
                  ranks=list(prepared.pair_build.spaces.pair_ranks), raw_mp2=prepared.solution.e_pair_per_cell)
    print(json.dumps({k: record[k] for k in ('native_full', 'native_isolated_half', 'negative')}), flush=True)
    if oracle_only:
        return record
    from vibeqc.dlpno.bipole_virtual_half import WORK_BOUND, half_virtual_ladder, resource_census
    from vibeqc.dlpno.bipole_virtual_singles import WORK_BOUND as LINEAR_WORK, linear_virtual_ladder_terms
    from vibeqc.dlpno.bipole_virtual_cubic import WORK_BOUND as CUBIC_WORK, cubic_virtual_ladder
    from vibeqc.dlpno.bipole_virtual_disconnected import (
        WORK_BOUND as QUADRATIC_WORK, disconnected_virtual_ladder)

    h, spaces = result.terminal_transitions, prepared.pair_build.spaces
    limits = dict(max_bytes=h.required_bytes, max_work=WORK_BOUND)
    def action(r, p, singles, **budget):
        return half_virtual_ladder(r, p, doubles, singles, **budget)
    record['refusals'] = quadratic.refusals(result, prepared, action, limits)
    def ordered(values):
        return {ij: spaces.orient_tensor(*ij, values) for ij in refs['half']}
    half = half_virtual_ladder(result, prepared, doubles, SINGLES, **limits)
    record['production'] = {name: compare(ordered(values), refs[name])
                            for name, values in zip((*NAMES, 'half'), half, strict=True)}
    record['polynomial'] = {}
    cases = [('zero_singles', 1., 0.), ('zero_doubles', 0., 1.), ('both_zero', 0., 0.),
             ('scale_doubles', -.7, 1.), ('scale_singles', 1., -.6), ('scale_both', -.7, 1.2)]
    for name, alpha, beta in cases:
        scaled = half_virtual_ladder(result, prepared, [alpha*t for t in doubles],
                                      [beta*t for t in SINGLES], **limits)
        weights = (alpha**2, alpha*beta**2, alpha*beta**2, beta**4)
        checks = {}
        for term, values, weight in zip(NAMES, scaled[:4], weights, strict=True):
            checks[term] = compare(ordered(values), {ij: weight*v for ij, v in refs[term].items()})
            if weight == 0:
                assert all(np.count_nonzero(a) == 0 for a in values)
        expected = {ij: sum(w*refs[k][ij] for k, w in zip(NAMES, weights, strict=True))
                    for ij in refs['half']}
        checks['half'] = compare(ordered(scaled.total), expected)
        record['polynomial'][name] = dict(alpha=alpha, beta=beta, checks=checks)
    record['reversal'] = {}
    for name, values in zip((*NAMES, 'half'), half, strict=True):
        got = ordered(values)
        record['reversal'][name] = compare(got, {ij: got[ij[::-1]].T for ij in got})
    # Retain each accepted contribution unchanged; each uses its own exact
    # source reservation sequentially. There is no fused assembly pass.
    baseline = h.bare_virtual_ladder(result, prepared, doubles, max_bytes=h.required_bytes,
                                     max_work=h.ladder_work_bound)
    mixed = linear_virtual_ladder_terms(result, prepared, doubles, SINGLES,
                                        max_bytes=h.required_bytes, max_work=LINEAR_WORK)
    quad = disconnected_virtual_ladder(result, prepared, SINGLES,
                                        max_bytes=h.required_bytes, max_work=QUADRATIC_WORK)
    cub = cubic_virtual_ladder(result, prepared, SINGLES,
                               max_bytes=h.required_bytes, max_work=CUBIC_WORK)
    six = tuple(a+b+c+d for a, b, c, d in zip(baseline, mixed.total, quad, cub.total, strict=True))
    full = tuple(a+b for a, b in zip(six, half.total, strict=True))
    record['assembly'] = dict(six=compare(ordered(six), refs['six']),
                              full=compare(ordered(full), refs['full']),
                              full_native=compare(ordered(full), native['increment']))
    record.update(ordered_targets=36, components_per_comparison=174, limits=limits,
                  resources=resource_census(),
                  assembly_work=WORK_BOUND+h.ladder_work_bound+LINEAR_WORK+QUADRATIC_WORK+CUBIC_WORK,
                  outputs={name: [a.tolist() for a in values] for name, values in
                           [*zip(NAMES, half[:4], strict=True), ('half', half.total),
                            ('bare', baseline), ('linear_x', mixed.x), ('linear_y', mixed.y),
                            ('quadratic', quad), ('cubic_x', cub.x), ('cubic_y', cub.y),
                            ('six', six), ('full', full)]},
                  coverage='Complete virtual_ladder minus occupied_ladder increment only',
                  next_family='Occupied ladder: existing owner; oooo and ooov actions plus the matching ovov contractions')
    assert all(not a.flags.writeable for leg in half for a in leg)
    return record


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