"""Synthetic latency interpretation, temporary SQLite recovery and BI baseline."""
import json,math,sqlite3,statistics,tempfile
from pathlib import Path

def latency(samples):
 valid=[];timeouts=0
 for value in samples:
  if value is None:timeouts+=1;continue
  if type(value) not in (int,float) or not math.isfinite(value) or value<0:raise ValueError('finite nonnegative milliseconds or None required')
  valid.append(value)
 ordered=sorted(valid)
 return {'attempts':len(samples),'successes':len(valid),'timeouts':timeouts,'median_success_ms':statistics.median(valid) if valid else None,'p95_success_ms':ordered[math.ceil(.95*len(ordered))-1] if ordered else None}

def recovery_demo():
 # All writes occur inside a new temporary directory, removed on exit.
 with tempfile.TemporaryDirectory(prefix='amit-recovery-') as folder:
  root=Path(folder);source=sqlite3.connect(root/'source.db');backup=sqlite3.connect(root/'backup.db');restored=sqlite3.connect(root/'restored.db')
  try:
   source.execute('CREATE TABLE orders(id TEXT PRIMARY KEY, amount INTEGER NOT NULL)');source.executemany('INSERT INTO orders VALUES (?,?)',[('O1',100),('O2',200)]);source.commit();source.backup(backup)
   source.execute("INSERT INTO orders VALUES ('O3',300)");source.commit()
   backup.backup(restored)
   rows=restored.execute('SELECT id,amount FROM orders ORDER BY id').fetchall();integrity=restored.execute('PRAGMA integrity_check').fetchone()[0]
   return {'source_count_after_backup':source.execute('SELECT COUNT(*) FROM orders').fetchone()[0],'restored_rows':rows,'restored_total':sum(x[1] for x in rows),'integrity_check':integrity,'post_backup_order_absent':not any(x[0]=='O3' for x in rows)}
  finally:source.close();backup.close();restored.close()

def bi_baseline():
 rows=[('North',100000,80000,10,9),('South',50000,45000,90,45)]
 return {'revenue':sum(r[1] for r in rows),'profit':sum(r[1]-r[2] for r in rows),'on_time':sum(r[4] for r in rows),'orders':sum(r[3] for r in rows),'on_time_rate':sum(r[4] for r in rows)/sum(r[3] for r in rows)}
if __name__=='__main__':print(json.dumps({'latency':latency([10,20,20,30,100,None]),'recovery':recovery_demo(),'bi':bi_baseline()},indent=2))
