"""Independent finite AO oracles for the four final R2 half updates.

Predeclared absolute component gate: 1e-10 Ha; real reconstruction: 1e-12.
Complete diagonal singles and independently constructed unequal PNO frames
are retained. Native snapshots isolate integral classes without editing C++.
"""
import json
from itertools import combinations_with_replacement
import numpy as np

try:
    from . import bipole_ring as ring_case
except ImportError:
    import bipole_ring as ring_case

fixture, bare, half_case = ring_case.fixture, ring_case.bare, ring_case.half_case
SINGLES, TOL = fixture.SINGLES, 1e-10
NAMES = ('quadratic_ovov', 'quadratic_oovv', 'linear_ovvv', 'linear_ooov')
LEGS = ('ij', 'ji', 'sum')


def oracle(inputs, singles=SINGLES, *, early_projection=False):
    """Contract four AO legs directly, before transforming the output frame."""
    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)])
    refs = {name: {leg: {} for leg in LEGS} for name in (*NAMES, 'half')}
    for ij, v in bases.items():
        u = rotations[ij]
        sm = v.T @ s @ d
        inputs_d = v @ sm if early_projection else d
        for leg, (i,j) in zip(LEGS[:2], (ij,ij[::-1]), strict=True):
            # Both integral singles inputs remain in their full diagonal frames.
            a = np.einsum('uvxy,um,v,x,yb->mb', eri, occ, inputs_d[:,i], occ[:,j], v, optimize=True)
            b = np.einsum('uvxy,um,v,xa,y->ma', eri, occ, occ[:,i], v, inputs_d[:,j], optimize=True)
            c = np.einsum('uvxy,ua,v,x,yb->ab', eri, v, inputs_d[:,i], occ[:,j], v, optimize=True)
            e = np.einsum('uvxy,um,v,x,yb->mb', eri, occ, occ[:,i], occ[:,j], v, optimize=True)
            terms = (-sm @ a, -sm @ b, c, -sm @ e)
            for name, value in zip(NAMES, terms, strict=True):
                refs[name][leg][ij] = u.T @ value @ u
            refs['half'][leg][ij] = sum(refs[name][leg][ij] for name in NAMES)
        for name in refs:
            refs[name]['sum'][ij] = refs[name]['ij'][ij] + refs[name]['ji'][ij].T
    return refs


def native_snapshots(inputs, fock, singles=SINGLES):
    """Actual shared-native half differences and returned raw R2.

    Four independent native passes per signed spectral sector: all factors;
    Bov alone (first term); Boo+Bvv (second term); Bov+Bvv (first+third).
    The fourth term is the remaining difference. No oracle value is used
    in this isolation. Fock enters only the zero-integral pass.
    """
    s,eri,virtual,occ,bases,placed,amps = inputs
    pairs = list(combinations_with_replacement(range(6),2))
    rot = {ij:bases[ij].T@s@placed[ij] for ij in pairs}
    pnos = [virtual.T@s@bases[ij] for ij in pairs]
    ts = [rot[ij]@amps[ij]@rot[ij].T for ij in pairs]
    t1 = [rot[m,m]@singles[m%2] for m in range(6)]
    boundaries = ('half_ij_ring','half_ji_ring','half_ij','half_ji','virtual_ladder','raw_R2')
    blocks = {mode:{name:{ij:np.zeros_like(t) for ij,t in zip(pairs,ts,strict=True)}
                   for name in boundaries} for mode in ('all','ovov','oovv','ovvv')}
    ev,vec = np.linalg.eigh(eri.reshape(144,144))
    for sign in (-1,1,0):
        keep = sign*ev > 0
        if sign and not keep.any(): continue
        ao = (vec[:,keep]*np.sqrt(sign*ev[keep])).T.reshape(-1,12,12) if sign else np.zeros((1,12,12))
        factors = [np.ascontiguousarray((l.T@ao@r).reshape(len(ao),-1))
                   for l,r in ((occ,virtual),(occ,occ),(virtual,virtual))]
        for mode, mask in (('all',(1,1,1)),('ovov',(1,0,0)),('oovv',(0,1,1)),('ovvv',(1,0,1))):
            if not sign and mode != 'all': continue
            fs = [a*scale for a,scale in zip(factors,mask,strict=True)]
            ov = fs[0].reshape(-1,6,6)
            k = [(ov[:,i]@p).T@(ov[:,j]@p) for (i,j),p in zip(pairs,pnos,strict=True)]
            f = np.zeros_like(fock) if sign else fock
            got = bare.native._dlpno_ccsd_pno_evaluate(*fs,occ.T@f@occ,occ.T@f@virtual,virtual.T@f@virtual,
                [i for i,j in pairs],[j for i,j in pairs],pnos,[np.ones(p.shape[1])*7 for p in pnos],
                k,ts,[list(range(6)) for _ in pairs],t1,True)
            for p,(ij,terms) in enumerate(zip(pairs,got['doubles_terms'],strict=True)):
                for name in boundaries:
                    key = name.replace('half_ji','half_ij') if ij[0]==ij[1] else name
                    value = got['R2'][p] if name=='raw_R2' else terms[key]
                    blocks[mode][name][ij] += (sign or 1)*value
    refs = {name:{leg:{} for leg in LEGS} for name in (*NAMES,'half')}
    snapshots = {name:{} for name in boundaries}
    for ij in bases:
        key=tuple(sorted(ij)); u=bases[key].T@s@placed[ij]
        for name in boundaries:
            lookup = name
            if ij[0]>ij[1] and name.startswith('half_'):
                lookup = name.replace('half_ij','half_TMP').replace('half_ji','half_ij').replace('half_TMP','half_ji')
            value = blocks['all'][lookup][key]
            if ij[0]>ij[1] and not name.startswith('half_'): value=value.T
            snapshots[name][ij]=u.T@value@u
        for leg in LEGS[:2]:
            native_leg = ('ji' if leg=='ij' else 'ij') if ij[0]>ij[1] else leg
            delta = {mode:u.T@(values['half_'+native_leg][key]-values['half_'+native_leg+'_ring'][key])@u
                     for mode,values in blocks.items()}
            vals = (delta['ovov'], delta['oovv'], delta['ovvv']-delta['ovov'],
                    delta['all']-delta['ovvv']-delta['oovv'])
            for name,value in zip(NAMES,vals,strict=True): refs[name][leg][ij]=value
            refs['half'][leg][ij]=delta['all']
        for name in refs: refs[name]['sum'][ij]=refs[name]['ij'][ij]+refs[name]['ji'][ij].T
    return refs,snapshots


def compare(actual, refs):
    return {name:{leg:half_case.compare(values[leg],refs[name][leg]) for leg in LEGS}
            for name,values in actual.items()}


def signed(actual, refs):
    return {name:{leg:ring_case.signed(values[leg],refs[name][leg]) for leg in LEGS}
            for name,values in actual.items()}


def run(*, oracle_only=False, earlier=None):
    result,prepared,doubles = fixture.prepare()
    inputs = fixture.reference_inputs(result,prepared,doubles)
    _,fock,_,_,_ = bare.supercell_operands(result,bare.op.GaussianCell(**bare.FIXTURE))
    refs = oracle(inputs)
    native,snapshots = native_snapshots(inputs,fock)
    record = dict(atol=TOL,imaginary_atol=1e-12,ordered_targets=36,components_per_comparison=174,
                  oracle_native=compare(refs,native),oracle_native_components=signed(refs,native))
    assert len(refs['half']['sum'])==36 and sum(a.size for a in refs['half']['sum'].values())==174
    signals={}
    for name in NAMES:
        signals[name]={}
        for ij,a in refs[name]['ij'].items(): bare.witness(signals[name],ij,a,np.zeros_like(a))
    assert all(w['abs']>TOL for w in signals.values())
    wrong=oracle(inputs,early_projection=True)
    negative={key:{} for key in ('wrong_sign','early_projection','missing_ji_transpose')}
    for ij in refs['half']['sum']:
        values=(refs['half']['sum'][ij]-2*refs[NAMES[0]]['sum'][ij],wrong['half']['sum'][ij],
                refs['half']['ij'][ij]+refs['half']['ji'][ij])
        for key,a in zip(negative,values,strict=True): bare.witness(negative[key],ij,a,refs['half']['sum'][ij])
    assert all(w['abs']>TOL for w in negative.values()),negative
    record.update(signals=signals,negative_controls=negative)
    print('Independent four-term oracle and isolated native differences PASS',flush=True)
    if oracle_only: return record
    return qualify(result,prepared,doubles,inputs,fock,refs,native,snapshots,record,earlier)


def qualify(result,prepared,doubles,inputs,fock,refs,native,snapshots,record,earlier):
    from dataclasses import replace
    from unittest.mock import patch
    import vibeqc.dlpno.bipole_half_updates as action
    import vibeqc.dlpno.bipole_ring as ring_action
    h,z = result.terminal_transitions,prepared.pair_build.spaces
    limits = dict(max_bytes=h.required_bytes,max_work=action.WORK_BOUND)
    record['refusals'] = half_case.quadratic.refusals(result,prepared,action.half_update_terms,limits)
    for name,budget in (('one_byte_below',dict(max_bytes=h.required_bytes-1,max_work=action.assembly_work_bound())),
                        ('one_work_below',dict(max_bytes=h.required_bytes,max_work=action.assembly_work_bound()-1))):
        try: action.doubles_residual(result,prepared,doubles,SINGLES,**budget)
        except (ValueError,MemoryError) as exc: record['refusals']['assembly_'+name]=str(exc)
        else: raise AssertionError(name)
    captured=[]; check=action._check_blocks
    def capture(*args,**kwargs):
        check(*args,**kwargs); captured[:]=[args[0]]
    with patch.object(action,'_check_blocks',capture):
        updates=action.half_update_terms(result,prepared,SINGLES,**limits)
    for name,change in (('invalid_block_identity',dict(identity='0'*64)),
                        ('invalid_block_issuer',dict(_issuer=object())),
                        ('invalid_block_transfer',dict(transfer=tuple(0 for _ in captured[0].transfer)))):
        with patch.object(type(h),'coulomb_blocks',return_value=replace(captured[0],**change)):
            try: action.half_update_terms(result,prepared,SINGLES,**limits)
            except ValueError as exc: record['refusals'][name]=str(exc)
            else: raise AssertionError(name)
    def ordered(terms):
        return {name:{leg:{ij:value.placed(z,*ij)[idx] for ij in refs[name][leg]}
                      for idx,leg in enumerate(LEGS)} for name,value in terms.items()}
    actual=ordered(updates)
    record['production']=compare(actual,refs)
    record['production_native']=compare(actual,native)
    record['signed_components']=signed(actual,refs)
    record['native_components']=signed(actual,native)
    record['reversal']={name:dict(
        raw_exchange=half_case.compare(values['ij'],{ij:values['ji'][ij[::-1]] for ij in values['ij']}),
        sum_transpose=half_case.compare(values['sum'],{ij:values['sum'][ij[::-1]].T for ij in values['sum']}))
        for name,values in actual.items()}
    zero=[np.zeros_like(t) for t in SINGLES]
    zeros=ordered(action.half_update_terms(result,prepared,zero,**limits))
    assert all(np.count_nonzero(a)==0 for values in zeros.values() for leg in values.values() for a in leg.values())
    record['zero_production']=compare(zeros,oracle(inputs,zero))
    s,eri,v,o,bases,placed,amps=inputs
    def transform(a,b,c,d):
        return np.einsum('uvxy,ui,vj,xk,yl->ijkl',eri,a,b,c,d,optimize=True)
    blocks=(transform(o,v,o,v),transform(o,o,v,v),transform(o,v,v,v),transform(o,o,o,v))
    rotations={ij:v.T@s@a for ij,a in placed.items()}
    d=np.stack([rotations[m,m]@SINGLES[m%2] for m in range(6)])
    record['scaling']={}
    for beta in (0.,-1.7,.6):
        expected=oracle(inputs,[beta*t for t in SINGLES])
        scaled=ordered(action._contract(z,rotations,beta*d,*blocks))
        sn,_=native_snapshots(inputs,fock,[beta*t for t in SINGLES])
        polynomial={name:{leg:{ij:beta**(2 if name.startswith('quadratic') else 1)*a
                              for ij,a in refs[name][leg].items()} for leg in LEGS} for name in NAMES}
        record['scaling'][str(beta)]=dict(kernel=compare(scaled,expected),native=compare(sn,expected),
            polynomial=compare(polynomial,expected),signed_components=signed(scaled,expected))
    # Independently expand the full expression at these same amplitudes.
    occupied,_,_=ring_case.fock_case.occupied_case.oracle(inputs)
    virtual,_=half_case.oracle(inputs)
    fr,_=ring_case.fock_case.oracle(inputs,fock)
    rings,_=ring_case.oracle(inputs)
    seed={ij:np.einsum('uvxy,u,va,x,yb->ab',eri,o[:,ij[0]],a,o[:,ij[1]],a,optimize=True)
          for ij,a in placed.items()}
    full_ref={ij:seed[ij]+occupied['occupied'][ij]+virtual['full'][ij]+fr['sum'][ij]
              +rings['sum'][ij]+refs['half']['sum'][ij] for ij in seed}
    record['full_oracle_native']=half_case.compare(full_ref,snapshots['raw_R2'])
    cumulative={ij:snapshots['virtual_ladder'][ij]+snapshots['half_ij'][ij]+snapshots['half_ji'][ij].T for ij in seed}
    record['native_inventory']=half_case.compare(cumulative,snapshots['raw_R2'])
    if earlier is None:
        # Ordinary executable example evaluates all earlier provider actions.
        full=action.doubles_residual(result,prepared,doubles,SINGLES,
            max_bytes=h.required_bytes,max_work=action.assembly_work_bound())
        record['earlier_reuse']='fresh fourteen-lease assembly'
    else:
        # Qualification may replay the accepted signed earlier numerical outputs.
        # Bind every source/frame/amplitude field before reusing a single value.
        current=dict(source=h.identity,source_record=h.provenance,pair_build=prepared.pair_build.identity,
            raw_mp2=prepared.solution.e_pair_per_cell,ranks=list(z.pair_ranks),
            pair_frames=[a.tolist() for a in z.pair_coefficients],singles=[a.tolist() for a in SINGLES],
            doubles=[a.tolist() for a in doubles])
        for key,value in current.items(): assert value==earlier[key],key
        previous={tuple(row['target']):np.asarray(row['actual']) for row in earlier['signed_components']['assembly']}
        prior=z.validate_tensors([previous[ij] for ij in z.representative_pairs],name='reused qualified ring assembly')
        expected_prior={ij:full_ref[ij]-refs['half']['sum'][ij] for ij in seed}
        record['reused_earlier_oracle']=half_case.compare(previous,expected_prior)
        # Exercise full public assembly wiring and its exact resource admission,
        # reusing completed numerical actions rather than repeating twelve leases.
        with patch.object(ring_action,'ladders_fock_ring_assembly',return_value=dict(total=prior)) as old_call, \
             patch.object(action,'half_update_terms',return_value=updates) as new_call:
            full=action.doubles_residual(result,prepared,doubles,SINGLES,
                max_bytes=h.required_bytes,max_work=action.assembly_work_bound())
            assert old_call.call_count==new_call.call_count==1
            assert old_call.call_args.kwargs['max_work']==ring_action.assembly_work_bound()
            assert new_call.call_args.kwargs==limits
        record['earlier_reuse']=dict(mode='exact signed outputs; source/frame/amplitude binding; public assembly wiring replay',
            earlier_groups={key:earlier[key] for key in ('outputs','virtual_outputs','fock_outputs','earlier_total')},
            assembly=earlier['signed_components']['assembly'],prior_production_leases=12,new_streamed_leases=4)
    full_actual={ij:z.orient_tensor(*ij,full['total']) for ij in seed}
    record['full_production']=half_case.compare(full_actual,full_ref)
    record['full_production_native']=half_case.compare(full_actual,snapshots['raw_R2'])
    record['full_components']=ring_case.signed(full_actual,full_ref)
    record['full_native_components']=ring_case.signed(full_actual,snapshots['raw_R2'])
    record['native_snapshots']={k:[dict(target=list(ij),value=a.tolist()) for ij,a in vals.items()] for k,vals in snapshots.items()}
    record.update(source=h.identity,source_record=h.provenance,pair_build=prepared.pair_build.identity,
        raw_mp2=prepared.solution.e_pair_per_cell,ranks=list(z.pair_ranks),pair_frames=[a.tolist() for a in z.pair_coefficients],
        singles=[a.tolist() for a in SINGLES],doubles=[a.tolist() for a in doubles],resources=action.resource_census(),
        coverage=full['coverage'],verdict='PASS')
    return record


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