"""LCF Consulting, 27/11/2026. Referência educativa Python/SQLite, não teste Lakebase.
Execute: python lakebase-replay.py > replay.csv
Sem rede, credenciais, dependências externas ou dados pessoais.
Reproduz somente o recorte de regras usado no dossiê. Não modela batches/concorrência.
Fonte: https://docs.databricks.com/aws/en/structured-streaming/lakebase
"""
import sqlite3,csv,sys
EVENTS=[('A',0,'criado'),('B',2,'pago'),('B-retry',2,'pago'),('C',1,'pendente'),('D',2,'revisão'),('E',None,'sem contexto')]
def run(events=EVENTS):
 db=sqlite3.connect(':memory:')
 for name in ['arrival','mixed','ordered']:db.execute(f'CREATE TABLE {name}(id INTEGER PRIMARY KEY, hora INTEGER, estado TEXT, origem INTEGER)')
 greater='CASE WHEN excluded.hora IS NULL THEN hora WHEN hora IS NULL THEN excluded.hora ELSE max(hora,excluded.hora) END'
 newer='excluded.hora IS NOT NULL AND (hora IS NULL OR excluded.hora > hora)'
 output=[]
 for step,(event,t,status)in enumerate(events,1):
  db.execute('INSERT INTO arrival VALUES(1,?,?,?) ON CONFLICT(id) DO UPDATE SET hora=excluded.hora,estado=excluded.estado,origem=excluded.origem',(t,status,t))
  db.execute(f'INSERT INTO mixed VALUES(1,?,?,?) ON CONFLICT(id) DO UPDATE SET hora={greater},estado=excluded.estado,origem=excluded.origem',(t,status,t))
  db.execute(f'INSERT INTO ordered VALUES(1,?,?,?) ON CONFLICT(id) DO UPDATE SET hora={greater},estado=CASE WHEN {newer} THEN excluded.estado ELSE estado END,origem=CASE WHEN {newer} THEN excluded.origem ELSE origem END',(t,status,t))
  for name in ['arrival','mixed','ordered']:output.append((step,event,name,*db.execute(f'SELECT hora,estado,origem FROM {name}').fetchone()))
 db.close();return output
if __name__=='__main__':
 writer=csv.writer(sys.stdout,delimiter=';');writer.writerow(['etapa','evento','regra','hora_minutos_apos_10h','status','hora_origem_status']);writer.writerows(run())
