#!/usr/bin/env python3
"""Executable normalized social authority, edges, tag projection and reactions."""
import argparse
import importlib.util
import json
import re
import sqlite3
import tempfile
import threading
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path


def load(name):
    spec = importlib.util.spec_from_file_location(name.replace('-', '_'), Path(__file__).with_name(name + '.py'))
    module = importlib.util.module_from_spec(spec); spec.loader.exec_module(module); return module


C = load('m22-common')
EDGES = [('Ada','Bo'),('Ada','Cy'),('Dee','Bo'),('Dee','Cy'),('Eli','Cy'),('Fay','Cy')]


def extract(caption):
    """ASCII tag alphabet with explicit ASCII whitespace/punctuation boundaries."""
    return sorted({match.group(1).lower() for match in re.finditer(
        r'(?:^|[ \t\r\n(,;:!?])#([A-Za-z][A-Za-z0-9_]{0,31})(?=$|[ \t\r\n),;:.!?])', caption)})


class Social:
    def __init__(self, path):
        self.path = str(path)
        with C.connect(self.path) as db:
            C.initialize(db)
            db.executescript('''
              CREATE TABLE IF NOT EXISTS follows(follower TEXT NOT NULL REFERENCES users(id), followee TEXT NOT NULL REFERENCES users(id),
                PRIMARY KEY(follower,followee), CHECK(follower<>followee));
              CREATE TABLE IF NOT EXISTS reverse_edges(followee TEXT NOT NULL REFERENCES users(id), follower TEXT NOT NULL REFERENCES users(id),
                PRIMARY KEY(followee,follower), CHECK(follower<>followee));
              CREATE TABLE IF NOT EXISTS posts(sequence INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE,
                author TEXT NOT NULL REFERENCES users(id), body TEXT NOT NULL, visibility TEXT NOT NULL,
                version INTEGER NOT NULL, deleted INTEGER NOT NULL CHECK(deleted IN(0,1)),
                CHECK(visibility IN('public','followers','private')));
              CREATE INDEX IF NOT EXISTS author_order ON posts(author,sequence DESC);
              CREATE TABLE IF NOT EXISTS changes(position INTEGER PRIMARY KEY AUTOINCREMENT, post TEXT NOT NULL REFERENCES posts(id),
                version INTEGER NOT NULL, body TEXT NOT NULL, UNIQUE(post,version));
              CREATE TABLE IF NOT EXISTS tag_versions(post TEXT NOT NULL PRIMARY KEY REFERENCES posts(id), version INTEGER NOT NULL, body TEXT NOT NULL);
              CREATE TABLE IF NOT EXISTS post_tags(post TEXT NOT NULL REFERENCES posts(id),tag TEXT NOT NULL,PRIMARY KEY(post,tag));
              CREATE INDEX IF NOT EXISTS tag_lookup ON post_tags(tag,post);
              CREATE TABLE IF NOT EXISTS reactions(actor TEXT NOT NULL REFERENCES users(id),post TEXT NOT NULL REFERENCES posts(id),kind TEXT,
                version INTEGER NOT NULL, PRIMARY KEY(actor,post), CHECK(kind IS NULL OR kind IN('heart','clap')));
              CREATE TABLE IF NOT EXISTS reaction_counts(post TEXT NOT NULL REFERENCES posts(id),kind TEXT NOT NULL,total INTEGER NOT NULL,PRIMARY KEY(post,kind));
            ''')

    def seed_edges(self):
        with C.connect(self.path) as db, C.transaction(db):
            db.executemany('INSERT OR IGNORE INTO follows VALUES(?,?)', EDGES)
            db.executemany('INSERT OR IGNORE INTO reverse_edges VALUES(?,?)', [(a,v) for v,a in EDGES])

    @staticmethod
    def visible(db, who, post):
        if post is None or post['deleted']: return False
        if not db.execute('SELECT 1 FROM users WHERE id=? AND active=1',(post['author'],)).fetchone(): return False
        return post['author'] == who or post['visibility'] == 'public' or (
            post['visibility'] == 'followers' and db.execute('SELECT 1 FROM follows WHERE follower=? AND followee=?',
                                                          (who,post['author'])).fetchone() is not None)

    def edge(self, who, target, wanted, operation, interrupt=False):
        C.text(target,64); C.require(type(wanted) is bool); body={'edge':target,'wanted':wanted}
        with C.connect(self.path) as db, C.transaction(db):
            prior=C.receipt(db,who,operation,body)
            if prior is not None:return {'duplicate':True,**prior}
            C.actor(db,target); C.require(who!=target,400,'self follow refused')
            if wanted:
                db.execute('INSERT OR IGNORE INTO follows VALUES(?,?)',(who,target))
                if interrupt:raise RuntimeError('between edge writes')
                db.execute('INSERT OR IGNORE INTO reverse_edges VALUES(?,?)',(target,who))
            else:
                db.execute('DELETE FROM follows WHERE follower=? AND followee=?',(who,target))
                if interrupt:raise RuntimeError('between edge writes')
                db.execute('DELETE FROM reverse_edges WHERE followee=? AND follower=?',(target,who))
            result={'accepted_state':wanted};C.remember(db,who,operation,body,result);return {'duplicate':False,**result}

    def adjacent(self, who, reverse=False):
        with C.connect(self.path) as db,C.transaction(db,False):
            C.actor(db,who)
            query=('SELECT follower FROM reverse_edges WHERE followee=? ORDER BY follower' if reverse else
                   'SELECT followee FROM follows WHERE follower=? ORDER BY followee')
            return [r[0] for r in db.execute(query,(who,))]

    def publish(self,who,operation,pid,caption,visibility='public'):
        C.text(pid,64);C.text(caption);C.require(visibility in ('public','followers','private'))
        body={'post':pid,'caption':caption,'visibility':visibility}
        with C.connect(self.path) as db,C.transaction(db):
            prior=C.receipt(db,who,operation,body)
            if prior is not None:return {'duplicate':True,**prior}
            C.require(db.execute('SELECT 1 FROM posts WHERE id=?',(pid,)).fetchone() is None,409,'post exists')
            cursor=db.execute('INSERT INTO posts(id,author,body,visibility,version,deleted) VALUES(?,?,?,?,1,0)',(pid,who,caption,visibility))
            state=dict(db.execute('SELECT * FROM posts WHERE id=?',(pid,)).fetchone())
            db.execute('INSERT INTO changes(post,version,body) VALUES(?,?,?)',(pid,1,C.encoded(state)))
            result={'post':pid,'sequence':cursor.lastrowid,'version':1};C.remember(db,who,operation,body,result)
            return {'duplicate':False,**result}

    def edit(self,who,operation,pid,base,caption,visibility='public',deleted=False):
        C.text(pid,64);C.text(caption);C.integer(base,1);C.require(type(deleted) is bool)
        C.require(visibility in ('public','followers','private'))
        body={'edit':pid,'base':base,'caption':caption,'visibility':visibility,'deleted':deleted}
        with C.connect(self.path) as db,C.transaction(db):
            prior=C.receipt(db,who,operation,body)
            if prior is not None:return {'duplicate':True,**prior}
            post=db.execute('SELECT * FROM posts WHERE id=?',(pid,)).fetchone()
            C.require(post is not None,404,'post missing');C.require(post['author']==who,403,'owner required')
            C.require(post['version']==base,409,'version conflict')
            db.execute('UPDATE posts SET body=?,visibility=?,deleted=?,version=version+1 WHERE id=?',(caption,visibility,int(deleted),pid))
            state=dict(db.execute('SELECT * FROM posts WHERE id=?',(pid,)).fetchone())
            db.execute('INSERT INTO changes(post,version,body) VALUES(?,?,?)',(pid,base+1,C.encoded(state)))
            result={'version':base+1};C.remember(db,who,operation,body,result);return {'duplicate':False,**result}

    def post(self,who,pid):
        with C.connect(self.path) as db,C.transaction(db,False):
            C.actor(db,who);row=db.execute('SELECT * FROM posts WHERE id=?',(pid,)).fetchone()
            C.require(self.visible(db,who,row),404,'post unavailable');return dict(row)

    def apply_tags(self,position):
        with C.connect(self.path) as db,C.transaction(db):
            event=db.execute('SELECT * FROM changes WHERE position=?',(position,)).fetchone();C.require(event is not None,404)
            state=json.loads(event['body']);old=db.execute('SELECT * FROM tag_versions WHERE post=?',(event['post'],)).fetchone()
            if old and old['version']>=event['version']:
                if old['version']==event['version']:C.require(old['body']==event['body'],409,'changed source version')
                return 'old or repeated'
            db.execute('DELETE FROM post_tags WHERE post=?',(event['post'],))
            tags=[] if state['deleted'] else extract(state['body'])
            db.executemany('INSERT INTO post_tags VALUES(?,?)',[(event['post'],tag) for tag in tags])
            db.execute('INSERT INTO tag_versions VALUES(?,?,?) ON CONFLICT(post) DO UPDATE SET version=excluded.version,body=excluded.body',
                       (event['post'],event['version'],event['body']))
            return tags

    def tag_page(self,who,tag):
        with C.connect(self.path) as db,C.transaction(db,False):
            C.actor(db,who)
            rows=db.execute('SELECT p.* FROM post_tags t JOIN posts p ON p.id=t.post JOIN tag_versions v ON v.post=p.id '
                            'WHERE t.tag=? AND v.version=p.version ORDER BY p.sequence DESC,p.id',(tag,)).fetchall()
            return [r['id'] for r in rows if self.visible(db,who,r)]

    def react(self,who,operation,pid,base,kind):
        C.text(pid,64);C.integer(base);C.require(kind in ('heart','clap',None))
        body={'reaction':pid,'base':base,'kind':kind}
        with C.connect(self.path) as db,C.transaction(db):
            prior=C.receipt(db,who,operation,body)
            if prior is not None:return {'duplicate':True,**prior}
            post=db.execute('SELECT * FROM posts WHERE id=?',(pid,)).fetchone();C.require(self.visible(db,who,post),404,'post unavailable')
            old=db.execute('SELECT * FROM reactions WHERE actor=? AND post=?',(who,pid)).fetchone()
            version=old['version'] if old else 0;C.require(base==version,409,'version conflict')
            db.execute('INSERT INTO reactions VALUES(?,?,?,?) ON CONFLICT(actor,post) DO UPDATE SET kind=excluded.kind,version=excluded.version',
                       (who,pid,kind,version+1))
            result={'version':version+1,'accepted_kind':kind};C.remember(db,who,operation,body,result);return {'duplicate':False,**result}

    def reaction_state(self,who,pid):
        with C.connect(self.path) as db,C.transaction(db,False):
            C.actor(db,who);post=db.execute('SELECT * FROM posts WHERE id=?',(pid,)).fetchone();C.require(self.visible(db,who,post),404)
            row=db.execute('SELECT kind,version FROM reactions WHERE actor=? AND post=?',(who,pid)).fetchone()
            return dict(row) if row else {'kind':None,'version':0}

    def repair(self,pid):
        with C.connect(self.path) as db,C.transaction(db):
            rows=db.execute('SELECT kind,count(*) n FROM reactions WHERE post=? AND kind IS NOT NULL GROUP BY kind ORDER BY kind',(pid,)).fetchall()
            db.execute('DELETE FROM reaction_counts WHERE post=?',(pid,))
            db.executemany('INSERT INTO reaction_counts VALUES(?,?,?)',[(pid,r['kind'],r['n']) for r in rows])
            return {r['kind']:r['n'] for r in rows}


def refusal(action):
    try:action()
    except C.Refusal as exc:return exc.status
    except sqlite3.IntegrityError:return 'constraint'
    raise AssertionError('expected refusal')


def demo(mode):
    with tempfile.TemporaryDirectory(prefix='m22-social-') as tmp:
        social=Social(Path(tmp)/'social.sqlite');social.seed_edges()
        if mode=='model':
            social.publish('Bo','publish1','p1','Hello #Cache')
            social.publish('Cy','publish2','p2','Hello #SQL','private')
            print('Ada p1:',social.post('Ada','p1')['body'])
            print('Ada private p2:',refusal(lambda:social.post('Ada','p2')))
            print('same follow: accepted state=',social.edge('Ada','Bo',True,'edge1')['accepted_state'],sep='')
            print('self follow:',refusal(lambda:social.edge('Ada','Ada',True,'edge2')))
            with C.connect(social.path) as db:
                print('missing foreign key:',refusal(lambda:db.execute('INSERT INTO follows VALUES(?,?)',('Ada','Missing'))))
            print('Ada edits Bo:',refusal(lambda:social.edit('Ada','edit1','p1',1,'Changed')))
            with C.connect(social.path) as db:
                print('rows:',C.encoded({table:db.execute('SELECT count(*) FROM '+table).fetchone()[0] for table in ('users','posts','follows','reverse_edges','changes')}))
                print('Bo author lookup rows:',len(db.execute('SELECT id FROM posts WHERE author=?',('Bo',)).fetchall()))
        elif mode=='graph':
            print('Ada follows:',','.join(social.adjacent('Ada')))
            print('Cy followers:',','.join(social.adjacent('Cy',True)))
            try:social.edge('Eli','Bo',True,'follow1',interrupt=True)
            except RuntimeError:pass
            print('interrupted Eli->Bo: forward=', 'Bo' in social.adjacent('Eli'), ' reverse=', 'Eli' in social.adjacent('Bo',True),sep='')
            social.edge('Eli','Bo',True,'follow1');print('retry committed:',C.encoded(social.edge('Eli','Bo',True,'follow1')))
            social.edge('Eli','Bo',False,'unfollow1');social.edge('Eli','Bo',True,'follow1')
            print('delayed old follow: current=', 'Bo' in social.adjacent('Eli'),sep='')
            print('absent unfollow:',C.encoded(social.edge('Eli','Bo',False,'unfollow2')))
            print('changed operation:',refusal(lambda:social.edge('Eli','Cy',True,'follow1')))
            with C.connect(social.path) as db:
                forward=set(map(tuple,db.execute('SELECT follower,followee FROM follows')))
                reverse=set(map(tuple,db.execute('SELECT follower,followee FROM reverse_edges')))
                if forward != reverse:
                    raise RuntimeError('Committed forward and reverse edges disagree')
                print('committed forward/reverse pairs:',len(forward),len(reverse))
        elif mode=='tags':
            for caption in ['#Cache, #CACHE (#sql); #x_2!', 'word#bad #9bad # #café ##bad', '#Go #go #Go', 'plain text']:
                print(repr(caption)+': '+C.encoded(extract(caption)))
            social.publish('Bo','p1','p1','#Cache #SQL');print('v1:',C.encoded(social.apply_tags(1)))
            social.edit('Bo','e2','p1',1,'#Cache #Graph');print('before projection: sql=',social.tag_page('Ada','sql'),sep='')
            print('v2:',C.encoded(social.apply_tags(2)));print('late v1:',social.apply_tags(1))
            social.edit('Bo','e3','p1',2,'#Cache #Graph',deleted=True)
            print('deleted source: graph=',social.tag_page('Ada','graph'),sep='')
            print('v3 removal:',C.encoded(social.apply_tags(3)))
            with C.connect(social.path) as db:print('retained post/tag relations:',db.execute('SELECT count(*) FROM post_tags').fetchone()[0])
        elif mode=='reactions':
            social.publish('Bo','post1','p1','Post')
            print('set:',C.encoded(social.react('Ada','a1','p1',0,'heart')))
            print('change:',C.encoded(social.react('Ada','a2','p1',1,'clap')))
            print('old retry:',C.encoded(social.react('Ada','a1','p1',0,'heart')))
            print('current:',C.encoded(social.reaction_state('Ada','p1')))
            print('changed identity:',refusal(lambda:social.react('Ada','a1','p1',0,'clap')))
            barrier=threading.Barrier(2)
            def submit(kind):
                barrier.wait()
                try:social.react('Ada','race-'+kind,'p1',2,kind);return 200
                except C.Refusal as exc:return exc.status
            with ThreadPoolExecutor(2) as pool:statuses=sorted(pool.map(submit,['heart','clap']))
            print('concurrent base2 statuses:',statuses)
            social.react('Ada','remove','p1',3,None);social.react('Cy','cy1','p1',0,'heart')
            with C.connect(social.path) as db:db.execute('INSERT INTO reaction_counts VALUES(?,?,?)',('p1','clap',99))
            print('repaired exact totals:',C.encoded(social.repair('p1')))
            print('removed Ada:',C.encoded(social.reaction_state('Ada','p1')))


if __name__=='__main__':
    parser=argparse.ArgumentParser();parser.add_argument('mode',choices=['model','graph','tags','reactions']);demo(parser.parse_args().mode)
