"""Freeze waveform-derived timing proxies before looking at any converted MIDI."""
import array,csv,hashlib,json,pathlib,shutil,sys
D=pathlib.Path(__file__).parent
assert not (D/'reference.json').exists(),'Do not replace a frozen reference after observing output'
x=array.array('f');x.frombytes((D/'source-analysis-f32le.pcm').read_bytes())
if sys.byteorder!='little':x.byteswap()
env=list(csv.DictReader((D/'source-envelope.csv').open(encoding='utf-8')))
# Eight separated attacks are visible in the saved measured-envelope plot.
# The earlier simple silence-gap finder merged the repeated train: retain that
# diagnostic as a failed segmentation proxy, never as reference strike count.
windows=[(.20,.45),(2.40,2.65),(2.75,3.00),(3.08,3.32),(3.42,3.65),(3.75,4.00),(4.08,4.32),(4.42,4.65)]
peak=max(map(abs,x));references=[]
for i,(lo,hi) in enumerate(windows,1):
 valid=[j for j,r in enumerate(env)if lo<=float(r['startSeconds'])<hi]
 j=max(valid,key=lambda j:float(env[j]['peak'])-(float(env[j-1]['peak'])if j else 0))
 a=int(round(float(env[j]['startSeconds'])*44100));end=min(a+441,len(x))
 crossing=next((k for k in range(a,end)if abs(x[k])>=.1*peak),a)
 references.append({'id':i,'start':crossing/44100,'sampleIndex':crossing,'visualReviewWindow':[lo,hi],'envelopeFrameStart':a/44100,'sourceCategory':'bass drum according to source attribution','timingKind':'waveform-derived proxy; not hardware or performer annotation','localizationUncertaintySeconds':.01})
report={'result':'FROZEN_PRE_OUTPUT_WAVEFORM_REFERENCE_WITH_DECODE_LIMIT',
 'source':'source-kick.ogg','sourceSHA256':hashlib.sha256((D/'source-kick.ogg').read_bytes()).hexdigest(),
 'referenceCount':len(references),'references':references,'createdBeforeAnyModelExecution':True,
 'manualReview':'Saved envelope PNG inspected; one isolated attack followed by seven visibly separated attacks. No listening study or hardware annotation.',
 'failedInitialCandidateRule':{'file':'source-inspection.json','count':2,'reason':'A gap between above-threshold samples can remain under200ms through repeated decaying hits; two groups are not two strikes.'},
 'timingAxis':{'sampleRate':44100,'decodedFrames':len(x),'ffmpegDecodedSeconds':len(x)/44100,'sourcePageReportedSeconds':5.411995464852608,'differenceSeconds':len(x)/44100-5.411995464852608,'nativeBrowserDecodeAxisVerified':False,'gate':'Do not report precise onset matches until native-browser timing origin is independently reconciled; do not fit a shift to maximize output matches'},
 'intendedReceiver':{'kind':'Declared General MIDI percussion target, not all custom drum racks','channelHuman':10,'channelWire':9,'acceptedBassDrumNotes':[35,36],'preferredNote':36,'mappingSource':'https://musescore.org/sites/musescore.org/files/General%20MIDI%20Standard%20Percussion%20Set%20Key%20Map.pdf','limitation':'A custom sampler may use another channel/note map; channel alone does not identify a drum class'},
 'matchingPlan':{'toleranceSeconds':.05,'timeOnlySeparateFromKitLaneMatch':True,'sameClassOneToOneNearestUnused':True,'noAccuracyDenominatorUntilBrowserTimeAxisKnown':True},
 'modelExecutions':0,'browserConversions':0,'actualMIDIOutput':None}
(D/'reference.json').write_text(json.dumps(report,indent=2)+'\n',encoding='utf-8')
with(D/'reference.csv').open('w',newline='',encoding='utf-8')as f:
 w=csv.DictWriter(f,fieldnames=['id','start','sampleIndex','localizationUncertaintySeconds']);w.writeheader();w.writerows({k:r[k]for k in w.fieldnames}for r in references)
shutil.copyfile('D:/JOBS/2026-11-16-polyphonic-audio-to-midi/evidence/midi_reader.py',D/'midi_reader.py')
print(json.dumps({'result':report['result'],'onsetProxies':[x['start']for x in references],'decodeDurationDifferenceSeconds':report['timingAxis']['differenceSeconds'],'actualMIDIOutput':None,'modelRuns':0}))
