# Portable copy of the watcher used on both commits; local paths are command arguments.
import sqlite3,time,json,subprocess,sys
from pathlib import Path
lock=Path(sys.argv[1])
database=sys.argv[2]
native_thread=sys.argv[3]
history_script=str(Path(__file__).with_name('native-history.py'))
lock.touch(exist_ok=False)
db=sqlite3.connect('file:'+database+'?mode=ro',uri=True)
print('Index locked; waiting for failed rollback restore',flush=True)
while True:
 row=db.execute("select attempt_count,status,last_error from orchestration_v2_effect_outbox where effect_type='provider-thread.rollback' order by created_at desc limit 1").fetchone()
 if row and row[2]:
  print('First failure:',row,flush=True)
  print(subprocess.check_output(['python3',history_script,native_thread],text=True),flush=True)
  lock.unlink()
  print('Removed index lock; worker may retry',flush=True)
  break
 time.sleep(.01)
while True:
 row=db.execute("select attempt_count,status,last_error from orchestration_v2_effect_outbox where effect_type='provider-thread.rollback' order by created_at desc limit 1").fetchone()
 if row and row[1] in ('succeeded','failed'):
  print('Final rollback:',row,flush=True)
  print(subprocess.check_output(['python3',history_script,native_thread],text=True),flush=True)
  break
 time.sleep(.02)
