"""Deterministic constructed MIDI controls. No DAW, audio detector or credentials."""
import pathlib,struct,json,hashlib,sys
out=pathlib.Path(sys.argv[1]) if len(sys.argv)>1 else pathlib.Path(__file__).parent
out.mkdir(parents=True,exist_ok=True)
def vlq(n):
 b=[n&127];n>>=7
 while n:b.insert(0,(n&127)|128);n>>=7
 return bytes(b)
notes=[(0,bytes([0x90,60,80])),(480,bytes([0x80,60,0])),(960,bytes([0x90,64,80])),(1440,bytes([0x80,64,0]))]
variants={
 'notes-only.mid':[],
 'cc11-channel1.mid':[(240,bytes([0xB0,11,32]))],
 'cc11-channel2.mid':[(240,bytes([0xB1,11,32]))],
 'cc7-channel1.mid':[(240,bytes([0xB0,7,32]))],
 'cc11-value96.mid':[(240,bytes([0xB0,11,96]))],
 'cc-before-note.mid':[(0,bytes([0xB0,11,32]))],
 'cc-after-note.mid':[(0,bytes([0xB0,11,32]))]}
results=[]
for name,cc in variants.items():
 ordered=(notes+cc) if name=='cc-after-note.mid' else (cc+notes)
 ordered=sorted(enumerate(ordered),key=lambda e:(e[1][0],e[0]))
 data=b'\x00\xff\x51\x03\x07\xa1\x20';previous=0
 for _,(tick,msg) in ordered:data+=vlq(tick-previous)+msg;previous=tick
 data+=b'\x00\xff\x2f\x00'
 raw=b'MThd'+struct.pack('>IHHH',6,0,1,480)+b'MTrk'+struct.pack('>I',len(data))+data
 (out/name).write_bytes(raw)
 results.append({'file':name,'bytes':len(raw),'sha256':hashlib.sha256(raw).hexdigest()})
(out/'generated.json').write_text(json.dumps(results,indent=2)+'\n',encoding='utf-8')
print(json.dumps(results))
