"""Read-only audit of application telemetry and independent original Journal arrival records."""
import argparse,json,math
from datetime import datetime,timedelta
from pathlib import Path

p=argparse.ArgumentParser(description=__doc__)
p.add_argument('--report',type=Path,required=True);p.add_argument('--journal-directory',type=Path,required=True);p.add_argument('--output',type=Path,required=True)
a=p.parse_args();report=json.loads(a.report.read_text(encoding='utf-8-sig'))
def dt(v):return datetime.fromisoformat(v.replace('Z','+00:00'))
def vec(v):return [v[k] for k in ('x','y','z')]
def dot(v,w):return sum(x*y for x,y in zip(v,w))
def length(v):return math.sqrt(dot(v,v))
def angle(v,w):return math.degrees(math.acos(max(-1,min(1,dot(v,w)/length(v)/length(w)))))
def blocked(f):
    centre=vec(f['currentStar']['centre']);pos=vec(f['position']);target=vec(f['targetPosition']);delta=[t-s for s,t in zip(pos,target)]
    t=max(0,min(1,dot([c-s for c,s in zip(centre,pos)],delta)/dot(delta,delta)))
    near=[s+t*d-c for s,d,c in zip(pos,delta,centre)]
    return length(near)<=f['currentStar']['exclusionRadius']*1.05
first=None;frames=0;charge_full_throttle=0;charged_wait=0;charging_turns=0;full_throttle_turns=0;bad=[];states=set();fuel=[];peak=0;minimum_ratio=math.inf;target_locked=True;saw_scoop=False
with Path(str(a.report)+'.jsonl').open(encoding='utf-8') as source:
    for line in source:
        row=json.loads(line)
        if row.get('kind')!='application-frame':continue
        f=row['frame'];decision=row.get('decision');frames+=1;first=first or f;peak=max(peak,f['heatPercent']);fuel.append(f.get('fuelMain') or 0)
        target_locked &= f['targetSystemAddress']==report['expectedSystem'];saw_scoop |= f['scoopActive']
        minimum_ratio=min(minimum_ratio,length(vec(f['position']))/f['currentStar']['exclusionRadius'])
        if f['inSupercruise'] and f['fsd']==1 and f.get('observedThrottleCommand',0)>=.999:charge_full_throttle+=1
        if f['inSupercruise'] and f['fsd']==2 and abs(f.get('observedThrottleCommand') or 0)<.001:charged_wait+=1
        if not decision:continue
        if f['inSupercruise'] and f['fsd']==1 and decision.get('direction') and angle(vec(f['forward']),vec(decision['direction']))>8:
            charging_turns+=1
            if f.get('observedThrottleCommand',0)>=.999:full_throttle_turns+=1
        states.add(decision['state'])
        if (decision['beginCharging'] or decision['permitJump']) and not decision['enterSupercruise']:
            if not f['nativeAllowsCharging'] or blocked(f) or f['fuelMain']<f['fuelNeededToNextRefuel']:bad.append({'sequence':f['sequence'],'reason':'FSD geometric/fuel/thermal gate'})
        if decision['permitJump']:
            wanted=[t-s for t,s in zip(vec(f['targetPosition']),vec(f['position']))]
            if f['fsd']!=2 or angle(vec(f['forward']),wanted)>1.001 or decision['throttle']!=1:bad.append({'sequence':f['sequence'],'reason':'FSD charge/alignment/throttle commit gate'})
arrivals=[];heat_events=[];start=dt(report['start'])-timedelta(seconds=1)
for path in a.journal_directory.glob('Journal.*.log'):
    if datetime.fromtimestamp(path.stat().st_mtime,start.tzinfo)<start:continue
    with path.open(encoding='utf-8-sig') as source:
        for line in source:
            if not line.rstrip().endswith('}'):continue
            row=json.loads(line)
            if not row.get('timestamp') or dt(row['timestamp'])<start:continue
            if row.get('event')=='FSDJump' and row.get('SystemAddress')==report['expectedSystem']:arrivals.append({'path':str(path),'event':row})
            if row.get('event') in ('HeatWarning','HeatDamage'):heat_events.append(row)
result={'passed':report.get('passed') is True and bool(arrivals) and not bad and not heat_events and target_locked and charge_full_throttle>0 and (charging_turns<10 or full_throttle_turns>=10) and peak<100,
        'frames':frames,'initiallyStarObscured':blocked(first),'initialFuel':fuel[0],'maximumMainFuel':max(fuel),'sawActualScooping':saw_scoop,
        'sampledPeakHeatPercent':peak,'minimumObservedRadiusOverExclusion':minimum_ratio,'chargingAtObservedFullThrottleFrames':charge_full_throttle,
        'chargedWaitingWithObservedZeroThrottleFrames':charged_wait,'targetAlwaysMatched':target_locked,'invalidChargeOrCommitDecisions':bad,
        'chargingTurnDecisionFrames':charging_turns,'chargingTurnsWithObservedFullThrottleFrames':full_throttle_turns,
        'states':sorted(states),'independentOriginalJournalArrivals':arrivals,'journalHeatEvents':heat_events,'screenUse':False,'osInputSent':False,'scope':'Current pinned game build, actual current ship and this application run; sampled telemetry plus original Journal'}
with a.output.open('x',encoding='utf-8') as out:json.dump(result,out,ensure_ascii=False,indent=2)
print(json.dumps({k:v for k,v in result.items() if k not in ('states','independentOriginalJournalArrivals')},ensure_ascii=False))
raise SystemExit(0 if result['passed'] else 1)
