"""원격 서버의 index.html을 패치하는 스크립트"""
path = '/var/www/html/attendance-counter/web/index.html'

with open(path, 'r') as f:
    content = f.read()

# 1. onmessage 핸들러 교체 - 시퀀스 번호 검증 추가
old_onmessage = """  ws.onmessage = (e) => {
    const msg = JSON.parse(e.data);
    if (msg.type === 'frame') {
      renderFrame(msg.data);
    } else if (msg.type === 'status') {
      state.currentStatus = msg.status;
      updateStatusBadge(msg.status);
    }
  };"""

new_onmessage = """  ws.onmessage = (e) => {
    const msg = JSON.parse(e.data);
    if (msg.type === 'frame') {
      const seq = msg.seq || 0;
      if (seq >= lastRenderedSeq) {
        lastRenderedSeq = seq;
        renderFrame(msg.data);
      }
    } else if (msg.type === 'status') {
      state.currentStatus = msg.status;
      updateStatusBadge(msg.status);
      lastRenderedSeq = 0;
    }
  };"""

if old_onmessage in content:
    content = content.replace(old_onmessage, new_onmessage)
    print('OK: onmessage patched with sequence check')
else:
    print('SKIP: onmessage already patched or not found')

with open(path, 'w') as f:
    f.write(content)

print('DONE: index.html saved')
