"""Independent mixed-diagonal singles-product virtual-ladder qualification.

The oracle forms d_i = V_ii (V_ii.T S C_ii) t_i in the independently built
finite-supercell diagonal spaces, then D_ij = d_i d_j.T. Only after applying
the explicit AO ERI to D are the output legs projected into the target pair.
No production projection helper or terminal panel enters this derivation.
"""
import json
from itertools import combinations_with_replacement

import numpy as np

try:
    from . import bipole_virtual_singles as fixture
    from . import bipole_ovvv_regression as legs
except ImportError:
    import bipole_virtual_singles as fixture
    import bipole_ovvv_regression as legs

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


def oracle(frames, singles, doubles):
    s, eri, occ, bases, placed, projector = frames
    d = np.column_stack([bases[m, m] @ placed[m, m][2] @ singles[m % 2]
                         for m in range(6)])
    refs = {k: {} for k in ('disconnected', 'bare', 'x', 'y', 'assembly')}
    controls = {k: {} for k in ('signal', 'early_target_projection', 'missing_transpose')}
    for ij, (row, reversed_pair, rotation) in placed.items():
        i, j = ij
        v = bases[ij]
        # d_i and d_j are distinct full AO vectors even when ranks coincide.
        product = np.outer(d[:, i], d[:, j])
        kernel = np.einsum('uvxy,vy->ux', eri, product, optimize=True)
        value = rotation.T @ (v.T @ kernel @ v) @ rotation
        refs['disconnected'][ij] = value
        bare.witness(controls['signal'], (row, i, j), value, np.zeros_like(value))
        # Deliberately wrong: truncate each input to the target PNO frame.
        wrong_d = v @ (v.T @ s @ d[:, [i, j]])
        wrong_kernel = np.einsum('uvxy,v,y->ux', eri, wrong_d[:, 0], wrong_d[:, 1])
        wrong = rotation.T @ v.T @ wrong_kernel @ v @ rotation
        bare.witness(controls['early_target_projection'], (row, i, j), wrong, value)
        if reversed_pair:
            bare.witness(controls['missing_transpose'], (row, i, j), value.T, value)
        t = doubles[row].T if reversed_pair else doubles[row]
        t = rotation @ t @ rotation.T
        base_kernel = np.einsum('uvxy,vy->ux', eri, v @ t @ v.T, optimize=True)
        x, y = legs.dense_legs(eri, occ, v, t, d.T @ s @ v)
        for name, a in (('bare', v.T @ base_kernel @ v), ('x', x), ('y', y)):
            refs[name][ij] = rotation.T @ a @ rotation
        refs['assembly'][ij] = sum(refs[k][ij] for k in ('bare', 'x', 'y', 'disconnected'))
    assert len(placed) == 36 and sum(a.size for a in refs['disconnected'].values()) == 174
    assert all(w['abs'] > TOL for w in controls.values()), controls
    assert len(set(v.shape[1] for v in bases.values())) == 2
    return refs, dict(controls=controls, projector_error=projector,
                      diagonal_ao_singles=d.tolist(), component_atol=TOL)


def native_disconnected(frames, singles):
    """Isolate u_i.T u_j in the actual shared native virtual block.

    Only Bvv is supplied and T2=0: X,Y,Z,Z1 and all mixed dressings vanish.
    Signed spectral resolution is test-only, with no positive-Gram assumption.
    """
    s, eri, occ, bases, placed, _ = frames
    # An S-orthonormal full virtual basis spanning all diagonal/target PNOs.
    ev, u = np.linalg.eigh(s)
    root = (u * np.sqrt(ev)) @ u.T
    invroot = (u / np.sqrt(ev)) @ u.T
    _, vectors = np.linalg.eigh(np.eye(12) - (root @ occ) @ (root @ occ).T)
    virtual = invroot @ vectors[:, -6:]
    vv = np.einsum('uvxy,ua,ve,xb,yf->aebf', eri, virtual, virtual,
                   virtual, virtual, optimize=True).reshape(36, 36)
    weights, vectors = np.linalg.eigh(vv)
    pairs = list(combinations_with_replacement(range(6), 2))
    pnos = [virtual.T @ s @ bases[ij] for ij in pairs]
    ts = [np.zeros((v.shape[1], v.shape[1])) for v in pnos]
    t1 = [placed[m, m][2] @ singles[m % 2] for m in range(6)]
    out = {ij: np.zeros_like(t) for ij, t in zip(pairs, ts, strict=True)}
    for sign in (-1, 1):
        keep = sign * weights > 0
        bvv = np.ascontiguousarray((vectors[:, keep] * np.sqrt(sign*weights[keep])).T)
        naux = len(bvv)
        result = bare.native._dlpno_ccsd_pno_evaluate(
            np.zeros((naux, 36)), np.zeros((naux, 36)), bvv,
            -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(v.shape[1]) for v in pnos], ts, ts,
            [list(range(6)) for _ in pairs], t1, True)
        for ij, terms in zip(pairs, result['doubles_terms'], strict=True):
            out[ij] += sign * (terms['virtual_ladder'] - terms['occupied_ladder'])
    answer = {}
    for ij, (_, reverse, rotation) in placed.items():
        key = tuple(sorted(ij))
        ordered = out[key]
        if ij[0] > ij[1]:
            ordered = ordered.T
        gauge = bases[key].T @ s @ bases[ij] @ rotation
        answer[ij] = gauge.T @ ordered @ gauge
    return answer


def compare(actual, reference, placed):
    worst = {}
    ranks = {2: {}, 3: {}}
    for ij, ref in reference.items():
        row = placed[ij][0]
        bare.witness(worst, (row, *ij), actual[ij], ref)
        bare.witness(ranks[len(ref)], (row, *ij), actual[ij], ref)
    assert worst['abs'] <= TOL, worst
    return dict(worst=worst, by_rank=ranks)


def refusals(r, prepared, action, limits):
    from copy import copy
    from dataclasses import replace

    h = r.terminal_transitions
    bad_spaces = copy(prepared.pair_build.spaces)
    coefficients = list(bad_spaces.pair_coefficients)
    coefficients[0] = coefficients[0].copy()
    coefficients[0][:, 0] *= -1
    bad_spaces.pair_coefficients = tuple(coefficients)
    bad = replace(prepared, pair_build=replace(prepared.pair_build, spaces=bad_spaces))
    records = {}

    def refuse(name, result, pair_build, singles, budget, error, text):
        try:
            action(result, pair_build, singles, **budget)
        except error as exc:
            assert text in str(exc), (name, str(exc))
            records[name] = str(exc)
        else:
            raise AssertionError(f'{name} admitted')

    refuse('wrong_diagonal_frame', r, bad, SINGLES, limits, ValueError, 'frame')
    refuse('one_byte_below', r, prepared, SINGLES,
           dict(limits, max_bytes=limits['max_bytes']-1), MemoryError, 'bytes')
    refuse('one_work_below', r, prepared, SINGLES,
           dict(limits, max_work=limits['max_work']-1), ValueError, 'work units')
    refuse('complex_singles', r, prepared, [a.astype(complex) for a in SINGLES],
           limits, ValueError, 'real diagonal')
    refuse('wrong_input_rank', r, prepared, [np.zeros(3), SINGLES[1]],
           limits, ValueError, 'real diagonal')
    # Change and restore this test-owned result, so its genuine handle sees
    # a stale state (not just the easier different-result identity refusal).
    energy = r.energy
    try:
        object.__setattr__(r, 'energy', energy + .01)
        refuse('stale_terminal_state', r, prepared, SINGLES, limits, ValueError, 'state changed')
    finally:
        object.__setattr__(r, 'energy', energy)
    system, basis, mesh, options, kw = bare.op.rhf_fixture(3, scf=bare.SCF, **bare.FIXTURE)
    other = bare.run_pbc_bipole_rhf(system, basis, mesh, options,
                                    terminal_transition_bytes=bare.LIMIT, **kw)
    refuse('foreign_generation', other, prepared, SINGLES, limits, ValueError, 'generation')
    refuse('foreign_handle', replace(r, terminal_transitions=other.terminal_transitions),
           prepared, SINGLES, limits, ValueError, 'different terminal result')
    h._validate(r, limits['max_bytes'])
    return records


def run(*, oracle_only=False):
    r, prepared, doubles = fixture.prepare()
    frames = legs.reference_frames(r, prepared)
    refs, record = oracle(frames, SINGLES, doubles)
    record['native'] = compare(native_disconnected(frames, SINGLES),
                               refs['disconnected'], frames[4])
    record.update(source=r.terminal_transitions.identity,
                  pair_build=prepared.pair_build.identity,
                  singles=[a.tolist() for a in SINGLES], doubles=[a.tolist() for a in doubles],
                  input_frames=[frames[3][m, m].tolist() for m in range(6)],
                  input_frame_rotations=[frames[4][m, m][2].tolist() for m in range(6)],
                  home_diagonal_frames=[prepared.pair_build.spaces.coefficients(i, i).tolist()
                                        for i in range(2)],
                  pair_ao_domains=[a.tolist() for a in prepared.domain_selection.pair_ao_domains])
    print(json.dumps(record), flush=True)
    if oracle_only:
        return record
    from vibeqc.dlpno.bipole_virtual_disconnected import (
        WORK_BOUND, disconnected_virtual_ladder, resource_census)
    from vibeqc.dlpno.bipole_virtual_singles import WORK_BOUND as LINEAR_WORK
    from vibeqc.dlpno.bipole_virtual_singles import linear_virtual_ladder_terms

    h, spaces = r.terminal_transitions, prepared.pair_build.spaces
    limits = dict(max_bytes=h.required_bytes, max_work=WORK_BOUND)
    record['refusals'] = refusals(r, prepared, disconnected_virtual_ladder, limits)
    zeros = disconnected_virtual_ladder(r, prepared, [0*a for a in SINGLES], **limits)
    assert all(np.count_nonzero(a) == 0 for a in zeros)
    actual = disconnected_virtual_ladder(r, prepared, SINGLES, **limits)
    ordered = {ij: spaces.orient_tensor(*ij, actual) for ij in frames[4]}
    record['production'] = compare(ordered, refs['disconnected'], frames[4])
    scaling = {}
    for label, scales in [('first', (-1.7, 1.)), ('second', (1., .6)), ('both', (-1.7, .6))]:
        value = disconnected_virtual_ladder(r, prepared,
                    [a*c for a, c in zip(SINGLES, scales, strict=True)], **limits)
        expected = {ij: ref*scales[ij[0] % 2]*scales[ij[1] % 2]
                    for ij, ref in refs['disconnected'].items()}
        scaling[label] = compare({ij: spaces.orient_tensor(*ij, value) for ij in frames[4]},
                                 expected, frames[4])
    record['scaling'] = scaling
    reversal = {}
    for (i, j), a in ordered.items():
        bare.witness(reversal, (i, j), a, ordered[j, i].T)
    assert reversal['abs'] <= TOL
    record['pair_reversal'] = reversal
    baseline = h.bare_virtual_ladder(r, prepared, doubles, max_bytes=h.required_bytes,
                                     max_work=h.ladder_work_bound)
    mixed = linear_virtual_ladder_terms(r, prepared, doubles, SINGLES,
                                        max_bytes=h.required_bytes, max_work=LINEAR_WORK)
    assembly = {}
    for name, values in [('bare', baseline), ('x', mixed.x), ('y', mixed.y)]:
        if name == 'bare':
            values = {ij: spaces.orient_tensor(*ij, values) for ij in frames[4]}
        else:
            leg = 0 if name == 'x' else 1
            values = {ij: mixed.placed(spaces, *ij)[leg] for ij in frames[4]}
        assembly[name] = compare(values, refs[name], frames[4])
    totals = tuple(a+b+c for a, b, c in zip(baseline, mixed.total, actual, strict=True))
    assembly['sum'] = compare({ij: spaces.orient_tensor(*ij, totals) for ij in frames[4]},
                               refs['assembly'], frames[4])
    record.update(assembly=assembly, zero_singles_max=0.,
                  coverage=['vvvv*T2', '-X(T2)*s', '-s*Y(T2)', 'vvvv*(t1_i*t1_j)'],
                  remaining=['-A(t1_i,t1_j)*s', '-s*B(t1_i,t1_j)', '.5*sum_mn tau_mn*(Z+Z1)'],
                  limits=limits, resources=resource_census(), ordered_pairs=36, components=174,
                  source_record=h.provenance, mp2_per_cell=prepared.solution.e_pair_per_cell,
                  representatives=spaces.representative_pairs, ranks=list(spaces.pair_ranks),
                  outputs={name: [a.tolist() for a in values] for name, values in
                           [('disconnected', actual), ('bare', baseline), ('x', mixed.x),
                            ('y', mixed.y), ('sum', totals)]})
    return record


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