"""Kickoff 11: stated flat geometry, float64 static dynamics, all 27 stations.

Imports: Python standard library, NumPy, scipy.linalg.eigh, scipy.optimize.
Neither previous simulation module is imported or executed. Their source bytes
are hashed; only the permitted Kickoff 10 JSON supplies placement A controls.
Run: ../.venv-knot12d-blind/bin/python flat.py
"""
import os
os.environ.setdefault('OPENBLAS_NUM_THREADS','1')
os.environ.setdefault('OMP_NUM_THREADS','1')
os.environ.setdefault('VECLIB_MAXIMUM_THREADS','1')
import argparse
from datetime import datetime, timezone
import hashlib
import json
import math
from pathlib import Path
import platform
import resource
import sys
import time
import numpy as np
import scipy
from scipy.linalg import eigh
from scipy.optimize import minimize_scalar

HERE=Path(__file__).resolve().parent
PARENT=HERE.parent
HASHES={'knot12d/knot12d.py':'0747da40871a4135ee0e29507609d09edf8b5737722c690514ac9a63576813f6',
        'kickoff10/ideal3d.py':'2689a5daeede9caada73fe19f33167fb2df1a61761d92b05d59e4a057d4d9da4',
        'kickoff10/ideal3d.json':'f73a5f491a7b9f71a35a80ea11a35a862c28d585f2d1cd2407419c3d68a5910f'}
STATION=np.arange(108)%27
PHASE=np.arange(108)%4
CARDINAL=np.array([[1.,0.,0.],[0.,1.,0.],[-1.,0.,0.],[0.,-1.,0.]])
AXIS=np.ones(3)/np.sqrt(3.)
SQ=np.array([0,27,54,81])
INTER=STATION[:,None]!=STATION[None,:]
TUBES=[.03,.05,.1,.3]
DELTAS=[0,1000,100000,10000000]

def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()

def inputs():
    for name,digest in HASHES.items():assert sha(PARENT/name)==digest,(name,'hash mismatch')
    ph=(HERE/'predictions.sha256').read_text().split()[0]
    assert sha(HERE/'predictions.json')==ph
    return json.loads((HERE/'predictions.json').read_text()),json.loads((PARENT/'kickoff10/ideal3d.json').read_text()),ph

def centres():
    theta=2*np.pi*STATION/27
    return np.column_stack((np.cos(theta),np.sin(theta),np.zeros(108)))

def geometry(r):
    X=centres()+r*CARDINAL[PHASE]
    diff=X[None,:,:]-X[:,None,:]
    D=np.linalg.norm(diff,axis=2)
    edge=float(D[0,27])
    assert abs(edge-np.sqrt(2)*r)<1e-14
    assert np.min(D[~np.eye(108,dtype=bool)])>0
    safe=np.where(D==0,1,D)
    angular=1-3*((diff@AXIS)/safe)**2
    iso=(edge/safe)**6
    dip=angular/safe**3
    dip/=abs(dip[0,27])
    np.fill_diagonal(iso,0);np.fill_diagonal(dip,0)
    pair=np.unravel_index(np.argmin(np.where(INTER,D,np.inf)),D.shape)
    g={'r':r,'edge_length':edge,'closest_interstation_distance':float(D[pair]),
       'closest_interstation_distance_over_edge':float(D[pair]/edge),
       'closest_pair_indices':list(map(int,pair)),'closest_pair_stations':[int(STATION[i]) for i in pair],
       'axis':AXIS.tolist(),'positions':X.tolist(),'station_diagonals':[],'couplings':{}}
    for s in range(27):
        row={'station':s,'diagonals':[]}
        for i,j in [(s,s+54),(s+27,s+81)]:
            row['diagonals'].append({'indices':[i,j],'distance':float(D[i,j]),
                'dipolar_angular_factor':float(angular[i,j]),'dipolar_J':float(dip[i,j]),'isotropic_J':float(iso[i,j])})
        g['station_diagonals'].append(row)
    others=np.where(STATION!=0)[0]
    for name,J in [('a',iso),('c',dip)]:
        j=int(others[np.argmax(abs(J[0,others]))])
        ij=np.unravel_index(np.argmax(np.where(INTER,abs(J),-1)),J.shape)
        g['couplings'][name]={'reference_edge_J':float(J[0,27]),'reference_square_J':J[np.ix_(SQ,SQ)].tolist(),
                'J_max_from_bead0':float(abs(J[0,j])),'bead0_partner_index':j,
                'J_max_global':float(abs(J[ij])),'global_pair_indices':list(map(int,ij))}
        assert np.max(abs(J-J.T))==0
        assert abs(abs(J[0,27])-1)<1e-12
    return g,{'a':iso,'c':dip}

def threshold():
    C=centres();U=CARDINAL[PHASE]
    candidates=[]
    for i in range(108):
        for j in range(i+1,108):
            if STATION[i]==STATION[j]:continue
            a=C[j]-C[i];b=U[j]-U[i]
            aa=float(b@b-2);bb=float(2*a@b);cc=float(a@a)
            roots=[]
            if aa==0:
                if bb<0:roots=[-cc/bb]
            else:
                disc=bb*bb-4*aa*cc
                if disc>=0:
                    q=-.5*(bb+math.copysign(math.sqrt(disc),bb))
                    roots=[q/aa]+([cc/q] if q else [])
            candidates.extend((x,i,j) for x in roots if x>0)
    r,i,j=min(candidates)
    exact_value=2*math.sin(math.pi/27)/(2+math.sqrt(2))
    assert abs(r-exact_value)<1e-14
    for factor,want in [(1-1e-7,True),(1+1e-7,False)]:
        g,_=geometry(r*factor)
        assert (g['closest_interstation_distance_over_edge']>1)==want
    return {'r':r,'three_decimals':f'{r:.3f}','exact_form':'2*sin(pi/27)/(2+sqrt(2))',
            'pair_indices':[i,j],'pair_stations':[int(STATION[i]),int(STATION[j])],
            'positive_crossings_checked':len(candidates),
            'proof':'Centre separations are at least d=2*sin(pi/27); offset differences are at most 2r. Therefore every interstation distance is at least d-2r. The vertically aligned adjacent centres at stations 13 and 14, with opposing y offsets, attain d-2r. Solving d-2r=sqrt(2)*r gives the first crossing. All pairwise quadratic roots independently checked.'}

class Spectrum:
    def __init__(self,J,delta):
        self.J=J;self.delta=delta
        H=-J+np.diag(delta*STATION);self.H=H
        w,V=eigh(H,driver='evd')
        # Separate a large energy origin from each accurate local eigenvalue.
        # Do not assume sorted eigenvectors form station quartets: close beads
        # can make interstation couplings larger than the requested detuning.
        centers=delta*np.rint(w/delta) if delta else np.zeros(108)
        local=w-centers
        groups=[np.where(centers==c)[0] for c in np.unique(centers)]
        residual_history=[]
        for iteration in range(4):
            HB=np.empty_like(V)
            for inds in groups:
                c=centers[inds[0]]
                shifted=H.copy();shifted.flat[::109]-=c
                B=V[:,inds]
                Z=shifted@B
                wb,R=eigh((B.T@Z+Z.T@B)/2,driver='evd')
                V[:,inds]=B@R;local[inds]=wb
                HB[:,inds]=shifted@V[:,inds]
            residual=HB-V*local
            residual_history.append(float(np.max(abs(residual))))
            if iteration==3:break
            off=V.T@residual
            gap=(centers[:,None]-centers[None,:])+(local[:,None]-local[None,:])
            mask=(centers[:,None]!=centers[None,:])&(abs(gap)>1e-8)
            G=np.zeros_like(off)
            G[mask]=-off[mask]/gap[mask]
            G=(G-G.T)/2
            assert np.max(abs(G))<1e-3
            V=V@(np.eye(108)+G+.5*G@G)
            V-=.5*V@(V.T@V-np.eye(108))
        self.V=V;self.centers=centers;self.local=local
        self.residual_history=residual_history
        self.transfer_coeff=(V[:27]*V[54:81]).T
        self.ref_coeff=(V[SQ]*V[0]).T
        self.stay_coeff=(V[SQ]*((V[0]+V[54])/np.sqrt(2))).T
        self.initial=np.zeros((108,28),complex)
        self.initial[np.arange(27),np.arange(27)]=1
        self.initial[[0,54],27]=1/np.sqrt(2)
        self.C=V.T@self.initial

    def phase(self,t):
        t=np.asarray(t)
        return np.exp(-1j*t[...,None]*self.centers)*np.exp(-1j*t[...,None]*self.local)

    def state(self,t):return self.V@(self.phase(t)[:,None]*self.C)

    def prob(self,t,s):return float(abs(self.phase(t)@self.transfer_coeff[:,s])**2)

    def stay(self,t):return float(np.sum(abs(self.phase(t)@self.stay_coeff)**2))

    def sample(self,dt):
        n=math.ceil(2.5/dt);dt=2.5/n
        ts=np.linspace(0,40,16*n+1)
        whole=np.empty((n+1,27));reference=np.empty(len(ts));stay=np.empty(len(ts))
        for a in range(0,len(ts),4096):
            b=min(a+4096,len(ts));phase=self.phase(ts[a:b])
            reference[a:b]=abs(phase@self.transfer_coeff[:,0])**2
            stay[a:b]=np.sum(abs(phase@self.stay_coeff)**2,axis=1)
            if a<=n:
                stop=min(b,n+1)
                whole[a:stop]=abs(phase[:stop-a]@self.transfer_coeff)**2
        return ts,whole,reference,stay,dt

    def conservation(self):
        norms=0.;errors=np.zeros(28)
        initial_energy=np.r_[self.delta*np.arange(27),0.]
        shifted=[];E0=[]
        for q,e in enumerate(initial_energy):
            h=self.H.copy();h.flat[::109]-=e
            shifted.append(h)
            p=self.initial[:,q]
            E0.append(float(np.vdot(p,h@p).real))
        for t in np.linspace(0,40,81):
            psi=self.state(float(t))
            norms=max(norms,float(np.max(abs(np.sum(abs(psi)**2,axis=0)-1))))
            for q,h in enumerate(shifted):
                terms=(psi[:,q].conj()*(h@psi[:,q])).real
                energy=math.fsum(map(float,terms))
                errors[q]=max(errors[q],abs(energy-E0[q]))
        return {'norm_max_error':norms,'energy_max_absolute_drift':float(max(errors)),
                'per_initial_state_energy_drift':errors.tolist(),'times_checked':81,
                'initial_states_checked':28,'energy_origin':'Each initial station energy subtracted from H before taking its expectation; exactly the same conservation law, without cancellation of a large constant.',
                'norm_passed':norms<=1e-9,'energy_passed':bool(max(errors)<=1e-9),
                'eigen_residual_refinement_history':self.residual_history}

def refine(ts,values,function,maximize=True):
    sign=-1 if maximize else 1
    y=sign*values
    ix=int(np.argmin(y));best=float(values[ix]);when=float(ts[ix])
    candidates=np.where((y[1:-1]<=y[:-2])&(y[1:-1]<=y[2:]))[0]+1
    candidates=candidates[np.argsort(y[candidates])[:32]]
    for i in candidates:
        result=minimize_scalar(lambda t:sign*function(t),bounds=(float(ts[i-1]),float(ts[i+1])),method='bounded',options={'xatol':1e-12})
        value=sign*float(result.fun)
        if sign*value<sign*best:best=value;when=float(result.x)
    for t in [float(ts[0]),float(ts[-1])]:
        val=function(t)
        if sign*val<sign*best:best=val;when=t
    return {'value':best,'time':when,'grid_value':float(values[ix])}

def dynamics(J,delta):
    begin=time.monotonic()
    spec=Spectrum(J,delta)
    checks=spec.conservation()
    print('conservation',delta,checks['norm_max_error'],checks['energy_max_absolute_drift'],flush=True)
    history=[];previous=None
    for level in range(9):
        dt=.004/(2**level)
        ts,whole,reference,stay,actualdt=spec.sample(dt)
        firstts=ts[:len(whole)]
        stations=[refine(firstts,whole[:,s],lambda t,s=s:spec.prob(t,s)) for s in range(27)]
        long=refine(ts,reference,lambda t:spec.prob(t,0))
        sqstay=refine(ts,stay,spec.stay,False)
        current=np.r_[[x['value'] for x in stations],long['value'],sqstay['value']]
        change=None if previous is None else float(np.max(abs(current-previous)))
        history.append({'dt':actualdt,'maximum_change':change,'whole_min':float(min(current[:27])),
                        'whole_median':float(np.median(current[:27])),'whole_max':float(max(current[:27])),
                        'reference_first_pass':float(current[0]),'reference_long':long['value'],'reference_stay':sqstay['value']})
        print('sampling',actualdt,history[-1],flush=True)
        if level>=5 and change<1e-4:break
        previous=current
    else:print('WARNING sampling tolerance not met',flush=True)
    bystation=[{'station':s,'source_index':s,'target_index':s+54,'first_pass':x['value'],'first_pass_time':x['time'],
                'grid_first_pass':x['grid_value'],'spectral_triangle_upper_bound':float(min(1,np.sum(abs(spec.transfer_coeff[:,s]))**2))} for s,x in enumerate(stations)]
    return {'reference_first_pass':stations[0]['value'],'reference_first_pass_time':stations[0]['time'],
            'reference_long_transfer':long['value'],'reference_long_transfer_time':long['time'],
            'reference_square_stay':sqstay['value'],'reference_square_stay_time':sqstay['time'],
            'whole_mala_min':float(min(current[:27])),'whole_mala_median':float(np.median(current[:27])),
            'whole_mala_max':float(max(current[:27])),'worst_station':int(np.argmin(current[:27])),
            'best_station':int(np.argmax(current[:27])),'stations':bystation,'conservation':checks,
            'sampling_history':history,'sampling_converged':change is not None and change<1e-4,
            'wall_seconds':time.monotonic()-begin}

def main():
    parser=argparse.ArgumentParser()
    parser.add_argument('--geometry-only',action='store_true')
    parser.add_argument('--case',nargs=3,metavar=('R','COUPLING','DELTA'))
    args=parser.parse_args()
    begin=time.monotonic();pred,control,ph=inputs()
    threshold_result=threshold()
    if args.geometry_only:
        result={'threshold':threshold_result,'geometries':[geometry(r)[0] for r in TUBES]}
        (HERE/'geometry-check.json').write_text(json.dumps(result,indent=2)+'\n')
        print('THRESHOLD',threshold_result,flush=True)
        for g in result['geometries']:print(g['r'],g['closest_interstation_distance_over_edge'],g['closest_pair_indices'],g['couplings'],flush=True)
        return
    records=[];geometries=[]
    for r in TUBES:
        if args.case and r!=float(args.case[0]):continue
        g,couplings=geometry(r);geometries.append(g)
        for kind in ['a','c']:
            for delta in DELTAS:
                if args.case and (kind!=args.case[1] or delta!=int(args.case[2])):continue
                print('START',r,kind,delta,flush=True)
                result=dynamics(couplings[kind],delta)
                p=next(p for p in pred['cells'] if p['r']==r and p['coupling']==kind and p['Delta']==delta)
                matches=[row for row in control['records'] if row['r']==r and row['coupling']==kind and row['detuning']==('none' if delta==0 else 'static') and row['parameter']==delta]
                reused=None if not matches else {'provenance':'Copied without rerunning from permitted Kickoff 10 ideal3d.json',
                     'reference_first_pass':matches[0]['first_pass'],'reference_long_transfer':matches[0]['long_transfer'],
                     'reference_square_stay':matches[0]['square_qubit_stay'],'whole_mala_metrics':None,
                     'whole_mala_note':'Not measured in Kickoff 10; not inferred or newly simulated.'}
                records.append({'r':r,'coupling':kind,'Delta':delta,**result,'placement_A_reused':reused,
                     'predictions':{'reference':p['reference'],'whole_min':p['whole_min'],
                     'reference_status':'HELD' if f"{result['reference_first_pass']:.2f}"==p['reference'] else 'FAILED',
                     'whole_min_status':'HELD' if f"{result['whole_mala_min']:.2f}"==p['whole_min'] else 'FAILED'}})
                print('DONE',r,kind,delta,result['reference_first_pass'],result['whole_mala_min'],flush=True)
                (HERE/'checkpoint.json').write_text(json.dumps({'records':records,'geometries':geometries},indent=2)+'\n')
    inputs()
    restoration=[]
    for p in pred['whole_mala_restoration']:
        actual=[r['Delta'] for r in records if r['r']==p['r'] and r['coupling']==p['coupling'] and r['Delta'] and r['whole_mala_min']>=.99]
        restoration.append({**p,'actual_Deltas':actual,'status':'HELD' if actual==p['Deltas'] else 'FAILED'})
    out={'completed_utc':datetime.now(timezone.utc).isoformat(),'input_hashes':HASHES,'script_sha256':sha(__file__),
         'predictions_sha256':ph,'geometry_definition':'C_s+r*(cos(pi*p/2),sin(pi*p/2),0), with the quarter-turn offsets evaluated as exact cardinal directions.',
         'coordinate_prose_discrepancy':'The explicit formula has x/y diagonals and 45-degree edges, contrary to the prose. The formula is followed without rotating the squares.',
         'imports':'Standard library; NumPy; scipy.linalg.eigh; scipy.optimize.minimize_scalar. Neither old simulation module is imported or run.',
         'axis':AXIS.tolist(),'threshold':{**threshold_result,'prediction':pred['placement_B_threshold'],
         'prediction_status':'HELD' if f"{threshold_result['r']:.2f}"==pred['placement_B_threshold'] else 'FAILED'},
         'geometries':geometries,'records':records,'restoration_assessments':restoration,
         'whole_mala_definition':'Each of the 27 station first-pass probabilities is maximized at its own time. These statistics do not assert a simultaneous common-time transfer.',
         'extrema_method':'Spectral propagation, uniform sampling with at least five successive halvings (0.004 through 0.000125) and bounded refinement of the 32 strongest local extrema per observable. Numerical estimates, not rigorous continuous-time bounds.',
         'environment':{'python':sys.version,'numpy':np.__version__,'scipy':scipy.__version__,'platform':platform.platform(),
                        'machine':platform.machine(),'logical_cpus':os.cpu_count()},
         'validation_passed':all(r['sampling_converged'] and r['conservation']['norm_passed'] and r['conservation']['energy_passed'] for r in records),
         'wall_seconds':time.monotonic()-begin,
         'peak_rss_bytes':resource.getrusage(resource.RUSAGE_SELF).ru_maxrss*(1 if sys.platform=='darwin' else 1024)}
    (HERE/('case-result.json' if args.case else 'flat.json')).write_text(json.dumps(out,indent=2)+'\n')
    print('FINISHED',out['wall_seconds'],flush=True)

if __name__=='__main__':main()
