#!/usr/bin/env python3
"""Private notification dispatch fixture. SQLite stores local obligations and a
separate SQLite-backed fake provider. Calls are local Python calls, never email or
network requests. Timeout is injected after the fake commits acceptance. Provider
receipts have no automatic expiry in this fixture; real provider contracts differ.
"""
import json
import sqlite3
import tempfile
from pathlib import Path


def connect(path):
    c=sqlite3.connect(path);c.execute('PRAGMA synchronous=EXTRA');return c


def provider_key(event, user, channel):
    # A canonical tuple preserves boundaries even when identifiers contain separators.
    return json.dumps([event, user, channel], ensure_ascii=True, separators=(',', ':'))


class FakeProvider:
    def __init__(self,path):
        self.c=connect(path)
        self.c.executescript('''CREATE TABLE IF NOT EXISTS accepted(key TEXT PRIMARY KEY,payload TEXT,id TEXT UNIQUE,delivered INT);
        CREATE TABLE IF NOT EXISTS calls(key TEXT);''')
    def send(self,key,payload,lose_reply=False):
        body=json.dumps(payload,sort_keys=True,separators=(',',':'))
        with self.c:
            old=self.c.execute('SELECT payload,id FROM accepted WHERE key=?',(key,)).fetchone()
            if old and old[0]!=body: raise ValueError('changed provider payload')
            self.c.execute('INSERT INTO calls VALUES(?)',(key,))
            if old: message=old[1]
            else:
                message='fake-'+str(self.c.execute('SELECT count(*) FROM accepted').fetchone()[0]+1)
                self.c.execute('INSERT INTO accepted VALUES(?,?,?,0)',(key,body,message))
        if lose_reply: raise TimeoutError('injected timeout after provider acceptance')
        return message
    def deliver(self,message):
        with self.c:self.c.execute('UPDATE accepted SET delivered=1 WHERE id=?',(message,))
    def close(self):self.c.close()


class Notifications:
    def __init__(self,path):
        self.c=connect(path)
        self.c.executescript('''CREATE TABLE IF NOT EXISTS events(id TEXT PRIMARY KEY,body TEXT);
        CREATE TABLE IF NOT EXISTS preferences(user TEXT PRIMARY KEY,email INT,version INT);
        CREATE TABLE IF NOT EXISTS intents(event TEXT,user TEXT,channel TEXT,body TEXT,state TEXT,preference_version INT,
          provider_id TEXT,PRIMARY KEY(event,user,channel));
        CREATE TABLE IF NOT EXISTS attempts(event TEXT,user TEXT,channel TEXT,result TEXT);
        CREATE TABLE IF NOT EXISTS inbox(event TEXT,user TEXT,body TEXT,PRIMARY KEY(event,user));
        CREATE TABLE IF NOT EXISTS callbacks(id TEXT PRIMARY KEY);''')
    def route(self,event,body,recipients):
        with self.c:
            old=self.c.execute('SELECT body FROM events WHERE id=?',(event,)).fetchone()
            if old:
                if old[0]!=body:raise ValueError('changed event body')
                return False
            self.c.execute('INSERT INTO events VALUES(?,?)',(event,body))
            for user,channel in recipients:
                version=self.c.execute('SELECT version FROM preferences WHERE user=?',(user,)).fetchone()[0]
                self.c.execute("INSERT INTO intents VALUES(?,?,?,?,'pending',?,NULL)",(event,user,channel,body,version))
        return True
    def dispatch(self,event,user,channel,provider,lose_reply=False):
        try:
            self.c.execute('BEGIN IMMEDIATE')
            row=self.c.execute('SELECT body,state FROM intents WHERE event=? AND user=? AND channel=?',(event,user,channel)).fetchone()
            if row is None:raise ValueError('unknown intent')
            body,state=row
            if state not in ('pending','unknown'):self.c.commit();return state
            allowed,version=self.c.execute('SELECT email,version FROM preferences WHERE user=?',(user,)).fetchone()
            if state=='pending' and channel=='email' and not allowed:
                self.c.execute("UPDATE intents SET state='suppressed',preference_version=? WHERE event=? AND user=? AND channel=?",(version,event,user,channel))
                self.c.commit();return 'suppressed'
            if channel=='in-app':
                self.c.execute('INSERT OR IGNORE INTO inbox VALUES(?,?,?)',(event,user,body))
                self.c.execute("UPDATE intents SET state='visible' WHERE event=? AND user=? AND channel=?",(event,user,channel))
                self.c.commit();return 'visible'
            # An unknown send is reconciled under its original accepted decision.
            self.c.execute("UPDATE intents SET state='sending',preference_version=CASE WHEN state='pending' THEN ? ELSE preference_version END WHERE event=? AND user=? AND channel=?",(version,event,user,channel))
            self.c.commit()
        except BaseException:self.c.rollback();raise
        try:
            message=provider.send(provider_key(event,user,channel),dict(to=user,body=body,template=1),lose_reply)
            result='accepted'
        except TimeoutError:
            message=None;result='unknown'
        with self.c:
            self.c.execute('INSERT INTO attempts VALUES(?,?,?,?)',(event,user,channel,result))
            self.c.execute('UPDATE intents SET state=?,provider_id=? WHERE event=? AND user=? AND channel=?',(result,message,event,user,channel))
        return result
    def callback(self,receipt,message):
        # Trusted direct fixture call. A public endpoint requires verification.
        with self.c:
            if not self.c.execute('INSERT OR IGNORE INTO callbacks VALUES(?)',(receipt,)).rowcount:return False
            if self.c.execute("UPDATE intents SET state='delivered' WHERE provider_id=? AND state='accepted'",(message,)).rowcount!=1:
                raise ValueError('unknown or nonaccepted message')
        return True
    def close(self):self.c.close()


def main():
    with tempfile.TemporaryDirectory(prefix='m14-notify-') as directory:
        root=Path(directory);n=Notifications(root/'notifications.sqlite');p=FakeProvider(root/'provider.sqlite')
        with n.c:n.c.executemany('INSERT INTO preferences VALUES(?,?,?)',[('Ada',1,1),('Bo',0,1),('Cy',1,1)])
        recipients=[('Ada','email'),('Ada','in-app'),('Bo','email'),('Cy','email')]
        print('route new event: '+str(n.route('event-7','Your report is ready',recipients)))
        print('route duplicate: '+str(n.route('event-7','Your report is ready',recipients)))
        print('retained intents: '+str(n.c.execute('SELECT count(*) FROM intents').fetchone()[0]))
        with n.c:n.c.execute("UPDATE preferences SET email=0,version=2 WHERE user='Cy'")
        for who,channel,lose in [('Bo','email',False),('Cy','email',False),('Ada','in-app',False),('Ada','email',True)]:
            print(who+' '+channel+': '+n.dispatch('event-7',who,channel,p,lose))
        print('fake state after timeout: accepted='+str(p.c.execute('SELECT count(*) FROM accepted').fetchone()[0])+', delivered='+str(p.c.execute('SELECT count(*) FROM accepted WHERE delivered=1').fetchone()[0]))
        n.close();p.close();n=Notifications(root/'notifications.sqlite');p=FakeProvider(root/'provider.sqlite')
        print('Ada email after reopen: '+n.dispatch('event-7','Ada','email',p))
        print('provider calls='+str(p.c.execute('SELECT count(*) FROM calls').fetchone()[0])+', accepted records='+str(p.c.execute('SELECT count(*) FROM accepted').fetchone()[0]))
        message=n.c.execute("SELECT provider_id FROM intents WHERE user='Ada' AND channel='email'").fetchone()[0]
        p.deliver(message)
        print('delivery callback: '+str(n.callback('receipt-1',message)))
        print('duplicate callback: '+str(n.callback('receipt-1',message)))
        try:p.send(provider_key('event-7','Ada','email'),dict(to='Ada',body='Different',template=1))
        except ValueError as e:print('changed retry: '+str(e))
        print('user | channel | final state | preference version')
        for row in n.c.execute('SELECT user,channel,state,preference_version FROM intents ORDER BY user,channel'):
            print(' | '.join(map(str,row)))
        assert n.c.execute('SELECT count(*) FROM inbox').fetchone()[0]==1
        assert p.c.execute('SELECT count(*) FROM accepted').fetchone()[0]==1
        n.close();p.close()

if __name__=='__main__':main()
