"""Independent dense AO oracle for isolated finite BIPOLE R2 rings.

Absolute component tolerance is 1e-10 Ha, real reconstruction 1e-12.
Each comparison covers all 36 ordered targets / 174 components. Complete
diagonal singles and both orientations of every source double are retained.
"""
import json
from itertools import combinations_with_replacement
import numpy as np

try:
    from . import bipole_fock as fock_case
except ImportError:
    import bipole_fock as fock_case

fixture, bare, half_case = fock_case.fixture, fock_case.bare, fock_case.half_case
SINGLES, TOL = fixture.SINGLES, 1e-10
LEGS = ('ij', 'ji', 'sum')


def oracle(inputs, singles=SINGLES, *, wrong_orientation=False):
    """Build covariant AO W kernels before any mixed pair projection.

    Independent pair PAO/PNO frames supply AO source tensors. An output
    amplitude leg is covariantized with S, so V_p.T S projects only that
    free leg; a contracted virtual leg remains in its full source frame.
    No production helper, transformed block, or common virtual lift is used.
    """
    s, eri, virtual, occ, bases, placed, amps = inputs
    rotations = {ij: v.T@s@placed[ij] for ij,v in bases.items()}
    pairs = {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)])
    sd = s@d
    c = {(m,n): np.einsum('uvwy,u,w->vy',eri,occ[:,m],occ[:,n],optimize=True)
         for m in range(6) for n in range(6)}
    kernels = {}
    for m in range(6):
        for x in range(6):
            w1 = c[m,x] + np.einsum('uvwy,u,y->vw',eri,occ[:,m],d[:,x],optimize=True)
            exchange = np.einsum('uvwy,u,v->yw',eri,occ[:,m],occ[:,x]+d[:,x],optimize=True)
            w2 = w1-exchange; wx = -exchange
            for n in range(6):
                njme = np.einsum('uvwy,u,v,w->y',eri,occ[:,n],occ[:,x],occ[:,m],optimize=True)
                mxne = np.einsum('uvwy,u,v,w->y',eri,occ[:,m],occ[:,x],occ[:,n],optimize=True)
                w1 -= np.outer(njme,sd[:,n])
                w2 += np.outer(mxne-njme,sd[:,n])
                wx += np.outer(mxne,sd[:,n])
                # Keep four independent source contractions, matching A1-A4
                # only after the AO derivation, not by calling native helpers.
                nx, xn = pairs[n,x], pairs[x,n]
                if wrong_orientation: xn = nx
                a1 = c[m,n]@nx@s
                a2 = c[m,n]@xn@s
                a3 = c[n,m]@nx@s
                a4 = c[n,m]@xn@s
                direct_ss = np.outer(c[m,n]@d[:,x],sd[:,n])
                exchange_ss = np.outer(c[n,m]@d[:,x],sd[:,n])
                w1 += a1-.5*a2-.5*a3-direct_ss
                w2 += -.5*(a2-a1)+.5*(a4-a3)+.5*a1-direct_ss+exchange_ss
                wx += .5*a4+exchange_ss
            kernels[m,x] = (w1,w2,wx)
    refs = {k:{} for k in LEGS}
    pieces = {k:{} for k in ('ij_W1','ij_W2','ij_WX','ji_W1','ji_W2','ji_WX')}
    for ij,v in bases.items():
        i,j = ij; u=rotations[ij]; p=v.T@s
        halves=[]
        for leg,(a,b) in zip(('ij','ji'),((i,j),(j,i)),strict=True):
            terms=[np.zeros((v.shape[1],)*2) for _ in range(3)]
            for m in range(6):
                w1,w2,_=kernels[m,b]; wx=kernels[m,a][2]
                terms[0] += p@(pairs[a,m]-pairs[m,a])@w1@v
                terms[1] += p@pairs[a,m]@w2@v
                terms[2] += p@pairs[m,b]@wx@v
            for name,value in zip(('W1','W2','WX'),terms,strict=True):
                pieces[leg+'_'+name][ij]=u.T@value@u
            halves.append(sum(pieces[leg+'_'+name][ij] for name in ('W1','W2','WX')))
        refs['ij'][ij],refs['ji'][ij]=halves
        refs['sum'][ij]=halves[0]+halves[1].T
    return refs,pieces


def native_snapshots(inputs, fock, singles=SINGLES):
    """Read actual cumulative half snapshots, then subtract Fock separately.

    Signed spectral resolution is reference-only. Fock is evaluated once
    in a zero-integral pass. Diagonal pairs expose only half_ij; ji is that
    same local half, not its transpose. Reversal swaps raw halves.
    """
    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)]
    names=('half_ij_fock','half_ji_fock','half_ij_ring','half_ji_ring','virtual_ladder')
    blocks={name:{ij:np.zeros_like(t) for ij,t in zip(pairs,ts,strict=True)} for name in names}
    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))]
        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)]
        f=np.zeros_like(fock) if sign else fock
        got=bare.native._dlpno_ccsd_pno_evaluate(*factors,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 ij,terms in zip(pairs,got['doubles_terms'],strict=True):
            for name in names:
                key=name.replace('half_ji','half_ij') if ij[0]==ij[1] else name
                blocks[name][ij]+=(sign or 1)*terms[key]
    ordered={k:{} for k in (*LEGS,*names,'assembly','earlier')}
    for ij in bases:
        key=tuple(sorted(ij)); u=bases[key].T@s@placed[ij]
        for boundary in ('fock','ring'):
            a,b=(blocks['half_'+leg+'_'+boundary][key] for leg in ('ij','ji'))
            if ij[0]>ij[1]: a,b=b,a
            ordered['half_ij_'+boundary][ij]=u.T@a@u
            ordered['half_ji_'+boundary][ij]=u.T@b@u
        value=blocks['virtual_ladder'][key]
        ordered['virtual_ladder'][ij]=u.T@(value.T if ij[0]>ij[1] else value)@u
        for leg in ('ij','ji'):
            ordered[leg][ij]=ordered['half_'+leg+'_ring'][ij]-ordered['half_'+leg+'_fock'][ij]
        ordered['sum'][ij]=ordered['ij'][ij]+ordered['ji'][ij].T
        ordered['assembly'][ij]=(ordered['virtual_ladder'][ij]+ordered['half_ij_ring'][ij]
                                 +ordered['half_ji_ring'][ij].T)
        ordered['earlier'][ij]=(ordered['virtual_ladder'][ij]+ordered['half_ij_fock'][ij]
                                +ordered['half_ji_fock'][ij].T)
    return ordered


def signed(actual, reference):
    return [dict(target=list(ij),actual=a.tolist(),reference=reference[ij].tolist(),
                 error=(a-reference[ij]).tolist()) for ij,a in actual.items()]


def scaling_checks(inputs, fock, spaces, doubles):
    """Exercise the same production contraction at controlled amplitudes.

    Dense integrals are used only here; the unscaled physical action separately
    checks every streamed block through its result. The polynomial degrees
    are T, T*s, T*s*s and T*T, with no singles-only ring contribution.
    """
    from vibeqc.dlpno.bipole_ring import _contract
    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,o,v),transform(o,o,v,v),transform(o,v,v,v))
    rotations={ij:v.T@s@a for ij,a in placed.items()}
    t=np.asarray([[rotations[m,n]@amps[m,n]@rotations[m,n].T for n in range(6)] for m in range(6)])
    d=np.stack([rotations[m,m]@SINGLES[m%2] for m in range(6)])
    record={}
    for alpha,beta in ((0.,1.),(-1.7,.6),(.6,-1.7)):
        scaled=(*inputs[:-1],{ij:alpha*a for ij,a in amps.items()})
        singles=[beta*a for a in SINGLES]
        refs,_=oracle(scaled,singles)
        native=native_snapshots(scaled,fock,singles)
        got=_contract(spaces,[alpha*a for a in doubles],rotations,alpha*t,beta*d,*blocks)
        actual={k:{ij:got.placed(spaces,*ij)[leg] for ij in refs[k]} for leg,k in enumerate(LEGS)}
        record[str((alpha,beta))]=dict(
            kernel={k:half_case.compare(actual[k],refs[k]) for k in LEGS},
            native={k:half_case.compare(native[k],refs[k]) for k in LEGS},
            signed_components={k:signed(actual[k],refs[k]) for k in LEGS})
        if alpha==0: assert all(np.count_nonzero(a)==0 for values in actual.values() for a in values.values())
    return record


def run(*,oracle_only=False):
    result,prepared,doubles=fixture.prepare()
    inputs=fixture.reference_inputs(result,prepared,doubles)
    _,fock,_,_,_=bare.supercell_operands(result,bare.op.GaussianCell(**bare.FIXTURE))
    refs,pieces=oracle(inputs)
    native=native_snapshots(inputs,fock)
    record=dict(atol=TOL,imaginary_atol=1e-12,ordered_targets=36,components_per_comparison=174,
        oracle_native={k:half_case.compare(refs[k],native[k]) for k in LEGS},
        oracle_native_components={k:signed(refs[k],native[k]) for k in LEGS})
    assert len(refs['sum'])==36 and sum(a.size for a in refs['sum'].values())==174
    signal={}
    for ij in refs['ij']: bare.witness(signal,ij,refs['ij'][ij],refs['ji'][ij])
    assert signal['abs']>TOL,signal
    record['orientation_distinction']=signal
    wrong,_=oracle(inputs,wrong_orientation=True)
    negative={k:{} for k in ('wrong_source_orientation','omitted_ij','omitted_ji','wrong_ji_transpose')}
    for ij in refs['sum']:
        values=(wrong['sum'][ij],refs['ji'][ij].T,refs['ij'][ij],refs['ij'][ij]+refs['ji'][ij])
        for k,value in zip(negative,values,strict=True): bare.witness(negative[k],ij,value,refs['sum'][ij])
    assert all(x['abs']>TOL for x in negative.values()),negative
    record['negative_controls']=negative
    zero=[np.zeros_like(t) for t in SINGLES]
    zr,_=oracle(inputs,zero); zn=native_snapshots(inputs,fock,zero)
    record['zero_native']={k:half_case.compare(zr[k],zn[k]) for k in LEGS}
    record['oracle_pieces']={k:[dict(target=list(ij),value=a.tolist()) for ij,a in v.items()] for k,v in pieces.items()}
    print('Independent ring oracle and native snapshots PASS',flush=True)
    if oracle_only: return record
    from vibeqc.dlpno.bipole_ring import (ring_terms,ladders_fock_ring_assembly,
        WORK_BOUND,assembly_work_bound,resource_census)
    h,z=result.terminal_transitions,prepared.pair_build.spaces
    record['scaling']=scaling_checks(inputs,fock,z,doubles)
    limits=dict(max_bytes=h.required_bytes,max_work=WORK_BOUND)
    record['refusals']=half_case.quadratic.refusals(result,prepared,
        lambda r,p,t,**kw:ring_terms(r,p,doubles,t,**kw),limits)
    for name,budget in [('one_byte_below',dict(max_bytes=h.required_bytes-1,max_work=assembly_work_bound())),
                        ('one_work_below',dict(max_bytes=h.required_bytes,max_work=assembly_work_bound()-1))]:
        try: ladders_fock_ring_assembly(result,prepared,doubles,SINGLES,**budget)
        except (ValueError,MemoryError) as exc: record['refusals']['assembly_'+name]=str(exc)
        else: raise AssertionError(name)
    # Capture the genuine authenticated block from the physical action for
    # fail-closed provenance controls, without repeating a provider lease.
    from unittest.mock import patch
    from dataclasses import replace
    import vibeqc.dlpno.bipole_ring as action
    captured=[]
    check=action._check_blocks
    def capture(*args,**kwargs):
        check(*args,**kwargs); captured[:] = [args[0]]
    with patch.object(action,'_check_blocks',capture):
        full=ladders_fock_ring_assembly(result,prepared,doubles,SINGLES,
                                       max_bytes=h.required_bytes,max_work=assembly_work_bound())
    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)))):
        invalid=replace(captured[0],**change)
        with patch.object(type(h),'coulomb_blocks',return_value=invalid):
            try: ring_terms(result,prepared,doubles,SINGLES,**limits)
            except ValueError as exc: record['refusals'][name]=str(exc)
            else: raise AssertionError(name)
    def ordered(terms):
        return {k:{ij:terms.placed(z,*ij)[leg] for ij in refs[k]} for leg,k in enumerate(LEGS)}
    actual=ordered(full['ring'])
    record['production']={k:half_case.compare(actual[k],refs[k]) for k in LEGS}
    record['production_native']={k:half_case.compare(actual[k],native[k]) for k in LEGS}
    zgot=ordered(ring_terms(result,prepared,doubles,zero,**limits))
    record['zero_production']={k:half_case.compare(zgot[k],zr[k]) for k in LEGS}
    record['reversal']={
        'raw_exchange':half_case.compare(actual['ij'],{ij:actual['ji'][ij[::-1]] for ij in actual['ij']}),
        'sum_transpose':half_case.compare(actual['sum'],{ij:actual['sum'][ij[::-1]].T for ij in actual['sum']})}
    def placed(values): return {ij:z.orient_tensor(*ij,values) for ij in refs['sum']}
    earlier=full['earlier']
    occupied,_,_=fock_case.occupied_case.oracle(inputs)
    virtual,_=half_case.oracle(inputs)
    fr,_=fock_case.oracle(inputs,fock)
    s,eri,v,o,bases,target_frames,amps=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 target_frames.items()}
    assembly={ij:seed[ij]+occupied['occupied'][ij]+virtual['full'][ij]+fr['sum'][ij]+refs['sum'][ij]
              for ij in refs['sum']}
    record['assembly']=half_case.compare(placed(full['total']),assembly)
    record['assembly_native']=half_case.compare(placed(full['total']),native['assembly'])
    record['earlier_native']=half_case.compare(placed(earlier['total']),native['earlier'])
    actual['assembly']=placed(full['total']); refs['assembly']=assembly
    record['signed_components']={k:signed(a,refs[k]) for k,a in actual.items()}
    record['native_components']={k:signed(a,native[k]) for k,a in actual.items()}
    record['native_snapshots']={k:[dict(target=list(ij),value=a.tolist()) for ij,a in v.items()]
                              for k,v in native.items() if k.startswith('half_') or k=='virtual_ladder'}
    # Keep the complete earlier array groups, rather than relying on norms.
    oc=earlier['occupied']
    outputs=dict(bare_oooo=oc['oooo']['doubles'],oooo_ss=oc['oooo']['singles'],
        x=oc['linear'].x,y=oc['linear'].y,linear=oc['linear'].total,
        cubic_x=oc['cubic'].x,cubic_y=oc['cubic'].y,cubic=oc['cubic'].total,
        half=oc['half'].total,half_tt=oc['half'].tt,t1_free=oc['t1_free'],occupied=oc['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))
    voutputs=dict(bare=earlier['virtual_bare'],linear_x=earlier['virtual_linear'].x,linear_y=earlier['virtual_linear'].y,
        quadratic=earlier['virtual_disconnected'],cubic_x=earlier['virtual_cubic'].x,cubic_y=earlier['virtual_cubic'].y,
        six=earlier['virtual_six'],full=earlier['virtual'],half=oc['half'].total,
        tt=oc['half'].tt,t_z1=oc['half'].t_z1,ss_z=oc['half'].ss_z,ss_z1=oc['half'].ss_z1)
    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=resource_census(),
        outputs={k:[a.tolist() for a in v] for k,v in outputs.items()},
        virtual_outputs={k:[a.tolist() for a in v] for k,v in voutputs.items()},
        fock_outputs={k:[a.tolist() for a in v] for k,v in zip(LEGS,earlier['fock'],strict=True)},
        earlier_total=[a.tolist() for a in earlier['total']],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)
