"""本主题专属离线算法，仅读取同目录合成JSON，不联网、不控制设备。"""
import csv, json, math, re, struct
from pathlib import Path
from fractions import Fraction
BASE=Path(__file__).resolve().parent
data=json.loads((BASE/'input.json').read_text(encoding='utf-8'))['data']
rows=[]
for text in data['sequences']:
 b=bytes.fromhex(text);active=set();events=[];triggers=0
 for i in range(0,len(b),3):
  status,note,velocity=b[i:i+3];assert note<128 and velocity<128
  channel=(status&15)+1;pressed=(status>>4)==9 and velocity>0
  assert status>>4 in (8,9)
  key=(channel,note)
  if pressed and key not in active:triggers+=1;active.add(key)
  if not pressed:active.discard(key)
  events.append({'channel':channel,'note':note,'event':'pressed' if pressed else 'released','raw_status':status,'velocity':velocity})
 rows.append({'input':text,'events':events,'virtual_cue_count':triggers,'active_after':sorted(active)})
assert all(r['virtual_cue_count']==1 and not r['active_after'] for r in rows)
result={'sequences':rows,'device_commands_sent':False}
(BASE/'result.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
print(json.dumps(result,ensure_ascii=False))
