#!/usr/bin/env python3
"""Distinct senders after inbox acknowledgement, separate from thread read state."""
import importlib.util
import json
import tempfile
import threading
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

spec=importlib.util.spec_from_file_location('m22_common',Path(__file__).with_name('m22-common.py'))
C=importlib.util.module_from_spec(spec);spec.loader.exec_module(C)


class Inbox:
    def __init__(self,path):
        self.path=str(path);self.unavailable=False
        with C.connect(self.path) as db:
            C.initialize(db)
            db.executescript('''
              CREATE TABLE IF NOT EXISTS heads(recipient TEXT NOT NULL PRIMARY KEY REFERENCES users(id),position INTEGER NOT NULL DEFAULT 0,
                acknowledged INTEGER NOT NULL DEFAULT 0,projected INTEGER NOT NULL DEFAULT 0);
              CREATE TABLE IF NOT EXISTS messages(recipient TEXT NOT NULL REFERENCES users(id),position INTEGER NOT NULL,sender TEXT NOT NULL REFERENCES users(id),
                text TEXT NOT NULL,PRIMARY KEY(recipient,position));
              CREATE TABLE IF NOT EXISTS sender_latest(recipient TEXT NOT NULL,sender TEXT NOT NULL,position INTEGER NOT NULL,PRIMARY KEY(recipient,sender));
              CREATE TABLE IF NOT EXISTS inbox_snapshots(id INTEGER PRIMARY KEY AUTOINCREMENT,recipient TEXT NOT NULL,through INTEGER NOT NULL);
              CREATE TABLE IF NOT EXISTS thread_reads(recipient TEXT NOT NULL,sender TEXT NOT NULL,position INTEGER NOT NULL,PRIMARY KEY(recipient,sender));
            ''')
            db.executemany('INSERT OR IGNORE INTO heads(recipient) VALUES(?)',[(u,) for u in C.USERS])

    def send(self,who,body):
        C.fields(body,['operation','recipient','text']);C.text(body['operation'],64);C.text(body['recipient'],64);C.text(body['text'])
        with C.connect(self.path) as db,C.transaction(db):
            old=C.receipt(db,who,body['operation'],body)
            if old is not None:return 200,{**old,'duplicate':True}
            target=body['recipient'];C.actor(db,target);C.require(who!=target,400,'self message refused')
            position=db.execute('UPDATE heads SET position=position+1 WHERE recipient=? RETURNING position',(target,)).fetchone()[0]
            db.execute('INSERT INTO messages VALUES(?,?,?,?)',(target,position,who,body['text']))
            db.execute('INSERT OR IGNORE INTO thread_reads VALUES(?,?,0)',(target,who))
            result={'position':position};C.remember(db,who,body['operation'],body,result);return 201,{**result,'duplicate':False}

    def history(self,who):
        with C.connect(self.path) as db,C.transaction(db):
            C.actor(db,who);head=db.execute('SELECT position FROM heads WHERE recipient=?',(who,)).fetchone()[0]
            rows=db.execute('SELECT m.position,m.sender,m.text FROM messages m JOIN users u ON u.id=m.sender '
                            'WHERE m.recipient=? AND u.active=1 ORDER BY m.position',(who,)).fetchall()
            snapshot=db.execute('INSERT INTO inbox_snapshots(recipient,through) VALUES(?,?)',(who,head)).lastrowid
            return {'snapshot':snapshot,'observed_through':head,'messages':[dict(r) for r in rows]}

    def acknowledge(self,who,body):
        C.fields(body,['operation','snapshot']);C.text(body['operation'],64);C.integer(body['snapshot'],1)
        with C.connect(self.path) as db,C.transaction(db):
            prior=C.receipt(db,who,body['operation'],body)
            if prior is not None:return 200,{**prior,'duplicate':True}
            row=db.execute('SELECT recipient,through FROM inbox_snapshots WHERE id=?',(body['snapshot'],)).fetchone()
            C.require(row is not None,404,'snapshot missing');C.require(row['recipient']==who,403,'snapshot owner')
            boundary=db.execute('UPDATE heads SET acknowledged=max(acknowledged,?) WHERE recipient=? RETURNING acknowledged',
                                (row['through'],who)).fetchone()[0]
            result={'acknowledged_through':boundary};C.remember(db,who,body['operation'],body,result);return 200,{**result,'duplicate':False}

    def project(self,who,limit=100,interrupt=False):
        with C.connect(self.path) as db,C.transaction(db):
            head=db.execute('SELECT projected FROM heads WHERE recipient=?',(who,)).fetchone()[0]
            rows=db.execute('SELECT * FROM messages WHERE recipient=? AND position>? ORDER BY position LIMIT ?',(who,head,limit)).fetchall()
            for row in rows:
                C.require(row['position']==head+1,409,'history gap')
                db.execute('INSERT INTO sender_latest VALUES(?,?,?) ON CONFLICT(recipient,sender) DO UPDATE SET position=max(position,excluded.position)',
                           (who,row['sender'],row['position']));head=row['position']
            if interrupt:raise RuntimeError('projection interrupted')
            db.execute('UPDATE heads SET projected=? WHERE recipient=?',(head,who))
            return head

    def badge(self,who):
        with C.connect(self.path) as db,C.transaction(db,False):
            C.actor(db,who);head=db.execute('SELECT * FROM heads WHERE recipient=?',(who,)).fetchone()
            latest={r['sender']:r['position'] for r in db.execute('SELECT sender,position FROM sender_latest WHERE recipient=?',(who,))}
            tail=db.execute('SELECT sender,position FROM messages WHERE recipient=? AND position>? ORDER BY position',(who,head['projected'])).fetchall()
            expected=head['projected']
            for row in tail:
                C.require(row['position']==expected+1,409,'history gap');expected=row['position']
                latest[row['sender']]=max(latest.get(row['sender'],0),row['position'])
            C.require(expected==head['position'],409,'history incomplete')
            senders=sorted(sender for sender,position in latest.items() if position>head['acknowledged'] and
                           db.execute('SELECT active FROM users WHERE id=?',(sender,)).fetchone()[0])
            return {'senders':senders,'count':len(senders),'accepted_through':head['position'],
                    'acknowledged_through':head['acknowledged'],'projected_through':head['projected'],'tail_rows':len(tail)}

    def __call__(self,method,path,who,body):
        if self.unavailable:raise C.Refusal(503,'authority unavailable')
        if method=='POST' and path=='/messages':return self.send(who,body)
        pieces=path.strip('/').split('/')
        C.require(len(pieces) in (2,3) and pieces[0] in ('inbox','badge'),404,'route missing')
        C.require(pieces[1]==who,403,'account scope')
        if method=='GET' and pieces==['inbox',who]:return 200,self.history(who)
        if method=='GET' and pieces==['badge',who]:return 200,self.badge(who)
        if method=='POST' and pieces==['inbox',who,'ack']:return self.acknowledge(who,body)
        raise C.Refusal(405,'unsupported operation')


def main():
    request_count=0
    def request(*args,**kwargs):
        nonlocal request_count
        request_count+=1
        return C.request(*args,**kwargs)
    with tempfile.TemporaryDirectory(prefix='m22-inbox-') as tmp:
        service=Inbox(Path(tmp)/'inbox.sqlite')
        with C.serve(service) as port:
            def send(who,operation,text='hello'):
                return request(port,'POST','/messages',{'operation':operation,'recipient':'Ada','text':text},who)
            for sender,operation in [('Bo','b1'),('Bo','b2'),('Cy','c1')]:
                if send(sender,operation)[0]!=201:
                    raise RuntimeError('initial message was not accepted')
            print('offline arrivals: events=3 distinct senders='+str(request(port,'GET','/badge/Ada')[1]['count']))
            print('duplicate message:',send('Bo','b1')[0]);print('changed message:',send('Bo','b1','changed')[0])
            first=request(port,'GET','/inbox/Ada')[1]
            print('device A observes through:',first['observed_through'])
            barrier=threading.Barrier(2)
            def arrival():barrier.wait();return send('Dee','d1')
            def ack():barrier.wait();return request(port,'POST','/inbox/Ada/ack',{'operation':'ack1','snapshot':first['snapshot']})
            with ThreadPoolExecutor(2) as pool:
                one=pool.submit(arrival);two=pool.submit(ack)
                arrival_status=one.result()[0];ack_status=two.result()[0]
                if (arrival_status,ack_status)!=(201,200):
                    raise RuntimeError('arrival or acknowledgement failed')
            print('arrival races ACK3:',C.encoded(service.badge('Ada')))
            print('clear-all control: would drop new sender Dee; boundary ACK retains her')
            try:service.project('Ada',interrupt=True)
            except RuntimeError:pass
            service=Inbox(service.path) # Reopen state; HTTP closure below is restarted afterward.
            print('projection interruption/reopen: projected=',service.badge('Ada')['projected_through'],sep='')
            service.project('Ada');print('delayed projection after ACK:',C.encoded(service.badge('Ada')))
        with C.serve(service) as port:
            second=request(port,'GET','/inbox/Ada')[1]
            request(port,'POST','/inbox/Ada/ack',{'operation':'ack2','snapshot':second['snapshot']})
            older=request(port,'POST','/inbox/Ada/ack',{'operation':'older-device','snapshot':first['snapshot']})
            print('device B ACK4 then old device ACK3:',older[1]['acknowledged_through'])
            print('wrong-user acknowledgement:',request(port,'POST','/inbox/Ada/ack',{'operation':'wrong','snapshot':second['snapshot']},'Bo')[0])
            print('wrong snapshot owner:',request(port,'POST','/inbox/Bo/ack',{'operation':'wrong','snapshot':second['snapshot']},'Bo')[0])
            before=service.badge('Ada')
            malformed=C.framing_probes(port,'/messages',{'operation':'bad','recipient':'Bo','text':'hello'})
            print('malformed framing:',C.encoded(malformed))
            if service.badge('Ada')!=before:
                raise RuntimeError('malformed request changed the badge')
            with C.connect(service.path) as db:
                if db.execute('SELECT count(*) FROM messages').fetchone()[0]!=4:
                    raise RuntimeError('message count changed')
                print('thread read positions:',[r[0] for r in db.execute('SELECT position FROM thread_reads WHERE recipient=? ORDER BY sender',('Ada',))])
                payloads=[dict(r) for r in db.execute('SELECT recipient,position,sender,text FROM messages ORDER BY recipient,position')]
                print('retained events=4 serialized message bytes='+str(sum(len(C.encoded(r).encode()) for r in payloads)))
            service.unavailable=True;print('unavailable authority:',request(port,'GET','/badge/Ada')[0])
            print('HTTP requests: application='+str(request_count)+' malformed='+str(len(malformed)))


if __name__=='__main__':main()
