"""Synthetic local request handling. SQLite state survives connection closure.
The role argument is a teaching fixture, NOT real authentication.
"""
import json
import sqlite3
import tempfile
from pathlib import Path

def apply(path, request_id, order_id, amount_paise, role='approver', fail_after_write=False):
    if role != 'approver':return 'forbidden'
    if not isinstance(request_id,str) or not request_id.strip() or not isinstance(order_id,str) or not order_id.strip():
        return 'invalid'
    if type(amount_paise) is not int or amount_paise<=0:return 'invalid'
    payload=json.dumps([order_id,amount_paise],separators=(',',':'))
    db=sqlite3.connect(path)
    try:
        db.execute('CREATE TABLE IF NOT EXISTS orders(id TEXT PRIMARY KEY, amount INTEGER NOT NULL CHECK(amount>0))')
        db.execute('CREATE TABLE IF NOT EXISTS requests(id TEXT PRIMARY KEY, payload TEXT NOT NULL)')
        db.commit()
        with db:
            db.execute('BEGIN IMMEDIATE')
            previous=db.execute('SELECT payload FROM requests WHERE id=?',(request_id,)).fetchone()
            if previous:return 'replayed' if previous[0]==payload else 'conflict'
            if db.execute('SELECT 1 FROM orders WHERE id=?',(order_id,)).fetchone():return 'order-exists'
            db.execute('INSERT INTO orders VALUES (?,?)',(order_id,amount_paise))
            if fail_after_write:raise RuntimeError('synthetic failure before recording request')
            db.execute('INSERT INTO requests VALUES (?,?)',(request_id,payload))
        return 'approved'
    finally:db.close()

def totals(path):
    db=sqlite3.connect(path)
    try:return db.execute('SELECT COUNT(*),COALESCE(SUM(amount),0) FROM orders').fetchone()
    finally:db.close()

if __name__=='__main__':
    with tempfile.TemporaryDirectory() as folder:
        path=str(Path(folder)/'synthetic.db')
        print('First request:',apply(path,'R1','O1',10000))
        print('After connection restart:',apply(path,'R1','O1',10000))
        print('Changed payload:',apply(path,'R1','O1',20000))
        print('Unpermitted role:',apply(path,'R2','O2',5000,role='viewer'))
        try:apply(path,'R3','O3',7000,fail_after_write=True)
        except RuntimeError:print('Failed batch rolled back')
        print('Before recovery:',totals(path))
        print('Recovery:',apply(path,'R3','O3',7000))
        print('Final count and paise:',totals(path))
