"""Original fictional local key/payload handler and deliberate response adapter."""
import json,sqlite3

class ResponseLost(Exception):
    pass

def connect(path):
    c=sqlite3.connect(path,timeout=5,isolation_level=None,
                      autocommit=sqlite3.LEGACY_TRANSACTION_CONTROL)
    c.execute('PRAGMA journal_mode=DELETE');c.execute('PRAGMA synchronous=FULL')
    return c

def settings(c):
    return {'isolation_level':c.isolation_level,'autocommit':c.autocommit,
            'autocommit_label':'LEGACY_TRANSACTION_CONTROL',
            'journal_mode':c.execute('PRAGMA journal_mode').fetchone()[0],
            'synchronous':c.execute('PRAGMA synchronous').fetchone()[0],
            'in_transaction':c.in_transaction,'sqlite_version':sqlite3.sqlite_version}

def initialize(path):
    c=connect(path)
    try:
        c.executescript('''CREATE TABLE reservations (
          reservation_id INTEGER PRIMARY KEY AUTOINCREMENT,
          reservation_key TEXT NOT NULL,sku TEXT NOT NULL,quantity INTEGER NOT NULL);
          CREATE TABLE ledger (reservation_key TEXT PRIMARY KEY,payload_json TEXT NOT NULL,
          reservation_id INTEGER NOT NULL,created_at_hours INTEGER NOT NULL);''')
        c.execute('BEGIN IMMEDIATE')
        c.execute('INSERT INTO reservations VALUES (?,?,?,?)',(1,'seed-key','seed',1))
        c.execute('INSERT INTO ledger VALUES (?,?,?,?)',('seed-key','{"quantity":1,"sku":"seed"}',1,0))
        c.execute('COMMIT');return settings(c)
    finally:c.close()

def _reserve(path,key,payload,now_hours,duplicate_before_replay):
    c=connect(path)
    try:
        canonical=json.dumps(payload,sort_keys=True,separators=(',',':'))
        prior=c.execute('SELECT payload_json,reservation_id FROM ledger WHERE reservation_key=?',(key,)).fetchone()
        if prior is not None:
            if prior[0]!=canonical:
                return {'kind':'conflict','code':'KEY_PAYLOAD_MISMATCH','reservation_id':None}
            if duplicate_before_replay:
                # Seeded defect: real extra effect despite the correct original returned ID.
                c.execute('BEGIN IMMEDIATE')
                c.execute('INSERT INTO reservations (reservation_key,sku,quantity) VALUES (?,?,?)',
                          (key,payload['sku'],payload['quantity']))
                c.execute('COMMIT')
            return {'kind':'reserved','reservation_id':prior[1]}
        c.execute('BEGIN IMMEDIATE')
        row=c.execute('INSERT INTO reservations (reservation_key,sku,quantity) VALUES (?,?,?)',
                      (key,payload['sku'],payload['quantity']))
        reservation_id=row.lastrowid
        c.execute('INSERT INTO ledger VALUES (?,?,?,?)',(key,canonical,reservation_id,now_hours))
        c.execute('COMMIT')
        return {'kind':'reserved','reservation_id':reservation_id}
    finally:
        if c.in_transaction:c.execute('ROLLBACK')
        c.close()

def baseline_reserve(path,key,payload,now_hours):
    return _reserve(path,key,payload,now_hours,True)

def corrected_reserve(path,key,payload,now_hours):
    return _reserve(path,key,payload,now_hours,False)

def call_adapter(handler,path,key,payload,now_hours,withhold=False):
    response=handler(path,key,payload,now_hours)
    if withhold:
        # Deliberately discard the handler's completed result. No network is involved.
        del response
        raise ResponseLost('test adapter withheld the completed handler result')
    return response
