#!/usr/bin/env python3
"""Private Module 15 fixtures. Logical ticks are injected, never wall-clock waits."""
import argparse
import json
import sqlite3
import tempfile
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from threading import Barrier


def connect(path):
    c = sqlite3.connect(path, timeout=10, isolation_level=None)
    c.row_factory = sqlite3.Row
    c.execute('PRAGMA foreign_keys=ON')
    c.execute('PRAGMA synchronous=EXTRA')
    return c


def race(function):
    gate = Barrier(2)
    def call(i):
        gate.wait()
        return function(i)
    with ThreadPoolExecutor(max_workers=2) as pool:
        return list(pool.map(call, [0, 1]))


def scheduler(path):
    with connect(path) as c:
        c.executescript('''CREATE TABLE runs(id TEXT PRIMARY KEY, due INTEGER, state TEXT,
          token INTEGER, until_tick INTEGER); CREATE TABLE effects(run_id TEXT PRIMARY KEY,
          token INTEGER);''')
        for _ in range(2):
            for due in (10, 20):
                c.execute("INSERT OR IGNORE INTO runs VALUES(?,?, 'ready',0,NULL)",
                          (f'cleanup/v1/{due}', due))
        print('materialize twice: occurrences=' + str(c.execute('SELECT count(*) FROM runs').fetchone()[0]))
    def claim(now):
        with connect(path) as c:
            c.execute('BEGIN IMMEDIATE')
            row = c.execute("SELECT * FROM runs WHERE due<=? AND (state='ready' OR "
                            "(state='claimed' AND until_tick<=?)) ORDER BY due LIMIT 1", (now, now)).fetchone()
            if row is None:
                c.commit()
                return None
            token = row['token'] + 1
            c.execute("UPDATE runs SET state='claimed', token=?, until_tick=? WHERE id=?", (token, now+5, row['id']))
            c.commit()
            return row['id'], token
    def effect(run, token, now, complete):
        with connect(path) as c:
            c.execute('BEGIN IMMEDIATE')
            row = c.execute('SELECT * FROM runs WHERE id=?', (run,)).fetchone()
            if row['state'] != 'claimed' or row['token'] != token or row['until_tick'] <= now:
                c.rollback()
                return 'stale'
            cur = c.execute('INSERT OR IGNORE INTO effects VALUES(?,?)', (run, token))
            outcome = 'inserted' if cur.rowcount else 'replayed'
            if complete:
                c.execute("UPDATE runs SET state='done' WHERE id=?", (run,))
            c.commit()
            return outcome
    print('tick 9 claim: ' + str(claim(9)))
    claims = race(lambda _: claim(10))
    a = next(x for x in claims if x)
    print(f'tick 10 competing claims: accepted={sum(x is not None for x in claims)} token={a[1]}')
    print('tick 11 effect, completion omitted: ' + effect(*a, 11, False))
    b = claim(15)
    print(f'tick 15 reclaim: occurrence={b[0]} token={b[1]}')
    print('tick 15 old completion: ' + effect(*a, 15, True))
    print('tick 15 new completion: ' + effect(*b, 15, True))
    with connect(path) as c:
        print('reopen states: ' + ', '.join(f"{r['id']}={r['state']}" for r in c.execute('SELECT * FROM runs ORDER BY due')))
        print('business effects=' + str(c.execute('SELECT count(*) FROM effects').fetchone()[0]))


def dag(path):
    graph = {'validate': [], 'render': ['validate'], 'index': ['validate'], 'publish': ['render', 'index']}
    def order(g):
        done = set()
        while len(done) < len(g):
            ready = sorted(n for n, parents in g.items() if n not in done and set(parents) <= done)
            if not ready:
                raise ValueError('cycle or missing dependency')
            done.update(ready)
        return done
    order(graph)
    with connect(path) as c:
        c.executescript('CREATE TABLE steps(name TEXT PRIMARY KEY,state TEXT,attempt INTEGER); CREATE TABLE effects(id TEXT PRIMARY KEY);')
        c.executemany("INSERT INTO steps VALUES(?,'pending',0)", [(n,) for n in graph])
    def ready():
        with connect(path) as c:
            state = {r['name']: r['state'] for r in c.execute('SELECT * FROM steps')}
        return sorted(n for n, parents in graph.items() if state[n] == 'pending' and all(state[p] == 'done' for p in parents))
    def execute(name, fail=False):
        with connect(path) as c:
            c.execute('BEGIN IMMEDIATE')
            states = {r['name']: r['state'] for r in c.execute('SELECT * FROM steps')}
            if states[name] != 'pending' or not all(states[p] == 'done' for p in graph[name]):
                c.rollback()
                return 'ineligible'
            c.execute('UPDATE steps SET attempt=attempt+1,state=? WHERE name=?', ('failed' if fail else 'done', name))
            if not fail:
                c.execute('INSERT OR IGNORE INTO effects VALUES(?)', ('document-A/v1/' + name,))
            c.commit()
            return 'failed' if fail else 'done'
    print('initial eligible: ' + ','.join(ready()))
    print('validate: ' + execute('validate'))
    print('eligible: ' + ','.join(ready()))
    print('render: ' + execute('render'))
    print('index: ' + execute('index', True))
    print('publish before repair: ' + execute('publish'))
    with connect(path) as c:
        c.execute("UPDATE steps SET state='pending' WHERE name='index' AND state='failed'")
    print('reopen eligible: ' + ','.join(ready()))
    print('index retry: ' + execute('index'))
    print('publish: ' + execute('publish'))
    with connect(path) as c:
        print('attempts: ' + ', '.join(f"{r['name']}={r['attempt']}" for r in c.execute('SELECT * FROM steps ORDER BY name')))
        print('recorded effects=' + str(c.execute('SELECT count(*) FROM effects').fetchone()[0]))
    try:
        order({'a':['b'], 'b':['a']})
    except ValueError:
        print('cyclic definition: rejected')


def rules(path):
    policies = {
        1: [('review-large', 10, 100, 'review'), ('review-all', 20, 0, 'review')],
        2: [('review-large', 10, 200, 'review'), ('review-all', 20, 0, 'review')],
    }
    with connect(path) as c:
        c.executescript('CREATE TABLE evaluations(event_id TEXT, version INTEGER, body TEXT, matches TEXT, winner TEXT, PRIMARY KEY(event_id,version)); CREATE TABLE actions(id TEXT PRIMARY KEY, kind TEXT);')
    def evaluate(event, version, replay=False):
        body = json.dumps(event, sort_keys=True, separators=(',', ':'))
        with connect(path) as c:
            c.execute('BEGIN IMMEDIATE')
            old = c.execute('SELECT * FROM evaluations WHERE event_id=? AND version=?', (event['id'],version)).fetchone()
            if old:
                c.rollback()
                return 'duplicate' if old['body'] == body else 'payload-conflict'
            if event['type'] != 'order.submitted' or event['schema'] != 1:
                c.rollback()
                return 'ignored-type-or-schema'
            previous = c.execute('SELECT body FROM evaluations WHERE event_id=?', (event['id'],)).fetchone()
            if previous and previous['body'] != body:
                c.rollback()
                return 'payload-conflict'
            if previous and not replay:
                c.rollback()
                return 'requires-explicit-replay'
            matches = sorted((r for r in policies[version] if event['units'] >= r[2]), key=lambda r:(r[1],r[0]))
            winner = matches[0][0] if matches else 'none'
            c.execute('INSERT INTO evaluations VALUES(?,?,?,?,?)', (event['id'],version,body,json.dumps([r[0] for r in matches]),winner))
            # Re-evaluation is audit-only; original business identity survives rule changes.
            if not replay and matches:
                c.execute('INSERT OR IGNORE INTO actions VALUES(?,?)', (event['id']+'/review', matches[0][3]))
            c.commit()
            return f"matches={','.join(r[0] for r in matches)} winner={winner} mode={'audit' if replay else 'dispatch'}"
    e = {'id':'order-A', 'type':'order.submitted', 'schema':1, 'units':150}
    print('v1: ' + evaluate(e,1))
    print('same input: ' + evaluate(e,1))
    print('changed input: ' + evaluate(dict(e,units=151),1))
    print('v2 ordinary delivery: ' + evaluate(e,2))
    print('v2 explicit replay: ' + evaluate(e,2,True))
    print('action feedback: ' + evaluate(dict(e,id='action-A',type='review.created'),1))
    with connect(path) as c:
        print(f"evaluations={c.execute('SELECT count(*) FROM evaluations').fetchone()[0]} action obligations={c.execute('SELECT count(*) FROM actions').fetchone()[0]}")


class Inventory:
    def __init__(self, path):
        self.path = path
        with connect(path) as c:
            c.executescript('''CREATE TABLE stock(id TEXT PRIMARY KEY, total INTEGER, available INTEGER CHECK(available>=0));
             INSERT INTO stock VALUES('poster',1,1);
             CREATE TABLE reservations(id TEXT PRIMARY KEY, buyer TEXT, state TEXT, token INTEGER, expires INTEGER);
             CREATE TABLE sequence(n INTEGER); INSERT INTO sequence VALUES(0);''')
    def invariant(self, c):
        total, available = c.execute('SELECT total,available FROM stock').fetchone()
        held = c.execute("SELECT count(*) FROM reservations WHERE state='held'").fetchone()[0]
        sold = c.execute("SELECT count(*) FROM reservations WHERE state='confirmed'").fetchone()[0]
        if total != available + held + sold:
            raise RuntimeError('Stock is not conserved')
        return f'available={available} reserved={held} confirmed={sold} total={total}'
    def reserve(self, rid, buyer, now):
        with connect(self.path) as c:
            c.execute('BEGIN IMMEDIATE')
            old = c.execute('SELECT * FROM reservations WHERE id=?', (rid,)).fetchone()
            if old:
                c.commit()
                return ('replay', old['token']) if old['buyer'] == buyer else ('payload-conflict', None)
            expired = c.execute("UPDATE reservations SET state='expired' WHERE state='held' AND expires<=?", (now,)).rowcount
            c.execute('UPDATE stock SET available=available+?', (expired,))
            changed = c.execute('UPDATE stock SET available=available-1 WHERE available>=1').rowcount
            if not changed:
                self.invariant(c)
                c.commit()
                return 'unavailable', None
            c.execute('UPDATE sequence SET n=n+1')
            token = c.execute('SELECT n FROM sequence').fetchone()[0]
            c.execute("INSERT INTO reservations VALUES(?,?,'held',?,?)", (rid,buyer,token,now+5))
            self.invariant(c)
            c.commit()
            return 'held', token
    def confirm(self, rid, token, now):
        with connect(self.path) as c:
            c.execute('BEGIN IMMEDIATE')
            changed = c.execute("UPDATE reservations SET state='confirmed' WHERE id=? AND token=? AND state='held' AND expires>?", (rid,token,now)).rowcount
            self.invariant(c)
            c.commit()
            return 'confirmed' if changed else 'rejected'
    def expire(self, now):
        with connect(self.path) as c:
            c.execute('BEGIN IMMEDIATE')
            n = c.execute("UPDATE reservations SET state='expired' WHERE state='held' AND expires<=?", (now,)).rowcount
            c.execute('UPDATE stock SET available=available+?', (n,))
            self.invariant(c)
            c.commit()
            return n
    def state(self):
        with connect(self.path) as c:
            return self.invariant(c)


def inventory(path):
    x = Inventory(path)
    print('initial: ' + x.state())
    result = race(lambda i:x.reserve('r'+str(i), 'buyer'+str(i), 0))
    win = next(i for i, v in enumerate(result) if v[0]=='held')
    print('competing reserves: ' + ','.join(sorted(v[0] for v in result)))
    print('after race: ' + x.state())
    print('same reservation retry: ' + x.reserve('r'+str(win),'buyer'+str(win),1)[0])
    print('expiry at tick 5 released=' + str(x.expire(5)))
    print('repeat expiry released=' + str(x.expire(5)))
    print('after expiry: ' + x.state())
    new = x.reserve('replacement','next-buyer',5)
    print(f'replacement: {new[0]} token={new[1]}')
    print('old confirmation: ' + x.confirm('r'+str(win),result[win][1],5))
    print('new confirmation: ' + x.confirm('replacement',new[1],6))
    print('reopen: ' + x.state())


if __name__ == '__main__':
    p = argparse.ArgumentParser()
    p.add_argument('mode', choices=['scheduler','dag','rules','inventory'])
    args = p.parse_args()
    with tempfile.TemporaryDirectory(prefix='fanout-m15-') as tmp:
        globals()[args.mode](Path(tmp)/'private.sqlite')
