#!/usr/bin/python3
# A stand-in for an account's server (PDS), for trying c8-cirrus without
# an account: it makes up the session (handle tester.test, app password
# abcd-efgh-ijkl-mnop), keeps what is written in memory and says what it
# got, and passes everything read on to Bluesky's public API, so the
# posts, profiles and threads are real ones. The timeline is bsky.app's
# own posts; the notifications are made up from them.
#
#   mock-pds.py [PORT]            (default 8377; C8_ACCOUNTS_ALLOW_HTTP=1
#                                  for the app, and its Server box set to
#                                  http://127.0.0.1:PORT)
#   MOCK_EXPIRE=N                 access tokens end after N calls (40)
import json, os, sys, time, urllib.request, urllib.parse, urllib.error
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

PUBLIC = 'https://public.api.bsky.app'
DID = 'did:plc:mocktester2222222222222'
HANDLE = 'tester.test'
PASSWORD = 'abcd-efgh-ijkl-mnop'
STAND_IN = 'bsky.app'  # whose posts and profile ours are
HOT = 'at://did:plc:z72i7hdynmk6r22z27h6tvur/app.bsky.feed.generator/whats-hot'
EXPIRE = int(os.environ.get('MOCK_EXPIRE', '40'))

serial = 0
access = {}    # token -> calls left
refresh = set()
records = {}   # uri -> record
seen = False

def say(*a):
    print(*a, flush=True)

def public(path):
    req = urllib.request.Request(PUBLIC + path,
        headers={'User-Agent': 'c8-cirrus-mock', 'Accept': 'application/json'})
    try:
        with urllib.request.urlopen(req, timeout=20) as r:
            return r.status, r.read()
    except urllib.error.HTTPError as e:
        return e.code, e.read()

def new_tokens():
    global serial
    serial += 1
    a, r = 'acc-%d' % serial, 'ref-%d' % serial
    access[a] = EXPIRE
    refresh.add(r)
    return {'accessJwt': a, 'refreshJwt': r, 'handle': HANDLE, 'did': DID,
        'active': True}

def check_post(rec):
    # What the post lexicon requires
    problems = []
    if not isinstance(rec.get('text'), str): problems.append('text')
    if not isinstance(rec.get('createdAt'), str): problems.append('createdAt')
    for f in rec.get('facets', []):
        i = f.get('index', {})
        if not (isinstance(i.get('byteStart'), int) and
                isinstance(i.get('byteEnd'), int) and f.get('features')):
            problems.append('facet')
        else:
            piece = rec['text'].encode()[i['byteStart']:i['byteEnd']].decode()
            say('   facet %r -> %s' % (piece, json.dumps(f['features'])))
    r = rec.get('reply')
    if r is not None:
        for k in ('root', 'parent'):
            if not (r.get(k, {}).get('uri') and r.get(k, {}).get('cid')):
                problems.append('reply.' + k)
    e = rec.get('embed')
    if e is not None:
        t = e.get('$type')
        imgs = e.get('images') or e.get('media', {}).get('images') or []
        for im in imgs:
            b = im.get('image', {})
            if b.get('$type') != 'blob' or '$link' not in b.get('ref', {}) \
                    or 'alt' not in im:
                problems.append('image')
        if t in ('app.bsky.embed.record',) and not e.get('record', {}).get('cid'):
            problems.append('record')
        if t == 'app.bsky.embed.recordWithMedia' and \
                not e.get('record', {}).get('record', {}).get('cid'):
            problems.append('recordWithMedia')
    return problems

def notifications():
    st, body = public('/xrpc/app.bsky.feed.getAuthorFeed?actor=%s&limit=12'
        % STAND_IN)
    posts = [e['post'] for e in json.loads(body).get('feed', [])]
    out = []
    kinds = ['like', 'reply', 'follow', 'repost', 'mention', 'quote', 'like']
    for i, p in enumerate(posts[:len(kinds)]):
        k = kinds[i]
        n = {'uri': p['uri'] if k in ('reply', 'mention', 'quote') else
                'at://%s/app.bsky.feed.%s/x%d' % (p['author']['did'], k, i),
            'cid': p['cid'], 'author': p['author'], 'reason': k,
            'record': p['record'], 'isRead': seen or i > 1,
            'indexedAt': time.strftime('%Y-%m-%dT%H:%M:%S.000Z',
                time.gmtime(time.time() - i * 400))}
        if k in ('like', 'repost'):
            n['reasonSubject'] = posts[(i + 3) % len(posts)]['uri']
        out.append(n)
    return {'notifications': out}

class H(BaseHTTPRequestHandler):
    def log_message(self, *a):
        pass

    def answer(self, status, obj):
        body = obj if isinstance(obj, bytes) else json.dumps(obj).encode()
        self.send_response(status)
        self.send_header('Content-Type', 'application/json')
        self.send_header('Content-Length', str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def token(self):
        a = self.headers.get('Authorization', '')
        return a[7:] if a.startswith('Bearer ') else ''

    def authed(self):
        t = self.token()
        if t not in access:
            self.answer(400, {'error': 'InvalidToken',
                'message': 'Token could not be verified'})
            return False
        if access[t] <= 0:
            say('   (token %s has expired)' % t)
            self.answer(400, {'error': 'ExpiredToken',
                'message': 'Token has expired'})
            return False
        access[t] -= 1
        return True

    def do_GET(self):
        u = urllib.parse.urlsplit(self.path)
        method = u.path.rsplit('/', 1)[-1]
        q = urllib.parse.parse_qs(u.query)
        say('GET ', method, u.query[:100])
        if not self.authed():
            return
        if method == 'app.bsky.actor.getPreferences':
            return self.answer(200, {'preferences': [{
                '$type': 'app.bsky.actor.defs#savedFeedsPrefV2', 'items': [
                    {'id': '1', 'type': 'timeline', 'value': 'following',
                        'pinned': True},
                    {'id': '2', 'type': 'feed', 'value': HOT, 'pinned': True},
                    {'id': '3', 'type': 'feed', 'pinned': False, 'value':
                        'at://did:plc:z72i7hdynmk6r22z27h6tvur/'
                        'app.bsky.feed.generator/with-friends'}]}]})
        if method == 'app.bsky.notification.listNotifications':
            return self.answer(200, notifications())
        if method == 'app.bsky.notification.getUnreadCount':
            return self.answer(200, {'count': 0 if seen else 2})
        path = self.path
        if method == 'app.bsky.feed.getTimeline':
            path = '/xrpc/app.bsky.feed.getAuthorFeed?actor=%s&%s' % (
                STAND_IN, u.query)
        path = path.replace(urllib.parse.quote(DID, safe=''), STAND_IN)
        st, body = public(path)
        if st != 200:
            say('   public API said', st, body[:200])
        self.answer(st, body)

    def do_POST(self):
        global seen
        method = self.path.rsplit('/', 1)[-1]
        n = int(self.headers.get('Content-Length', '0'))
        raw = self.rfile.read(n)
        ctype = self.headers.get('Content-Type', '')
        say('POST', method, ctype, n, 'bytes')
        if method == 'com.atproto.server.createSession':
            j = json.loads(raw)
            if j.get('identifier') in (HANDLE, DID) and \
                    j.get('password') == PASSWORD:
                return self.answer(200, new_tokens())
            return self.answer(401, {'error': 'AuthenticationRequired',
                'message': 'Invalid identifier or password'})
        if method == 'com.atproto.server.refreshSession':
            t = self.token()
            if t not in refresh:
                return self.answer(400, {'error': 'ExpiredToken',
                    'message': 'Token has been revoked'})
            refresh.discard(t)
            say('   new tokens for', t)
            return self.answer(200, new_tokens())
        if method == 'com.atproto.server.deleteSession':
            refresh.discard(self.token())
            return self.answer(200, {})
        if not self.authed():
            return
        if method == 'com.atproto.repo.uploadBlob':
            say('   blob starts', raw[:4])
            return self.answer(200, {'blob': {'$type': 'blob',
                'ref': {'$link': 'bafkreimock%d' % len(raw)},
                'mimeType': ctype, 'size': len(raw)}})
        j = json.loads(raw) if raw else {}
        if method == 'com.atproto.repo.createRecord':
            rec = j.get('record', {})
            say('   ' + json.dumps(j)[:900])
            bad = [] if j.get('repo') == DID else ['repo']
            if rec.get('$type') != j.get('collection'): bad.append('$type')
            if j.get('collection') == 'app.bsky.feed.post':
                bad += check_post(rec)
            if bad:
                say('   INVALID:', bad)
                return self.answer(400, {'error': 'InvalidRequest',
                    'message': 'Invalid record: ' + ', '.join(bad)})
            uri = 'at://%s/%s/mock%d' % (DID, j['collection'], len(records))
            records[uri] = rec
            return self.answer(200, {'uri': uri, 'cid': 'bafyreimockcid'})
        if method == 'com.atproto.repo.deleteRecord':
            say('   ' + json.dumps(j))
            if not (j.get('repo') and j.get('collection') and j.get('rkey')):
                return self.answer(400, {'error': 'InvalidRequest',
                    'message': 'repo, collection and rkey are required'})
            return self.answer(200, {})
        if method == 'app.bsky.notification.updateSeen':
            say('   ' + json.dumps(j))
            seen = True
            return self.answer(200, {})
        if method in ('app.bsky.graph.muteActor', 'app.bsky.graph.unmuteActor'):
            say('   ' + json.dumps(j))
            return self.answer(200, {})
        self.answer(501, {'error': 'MethodNotImplemented',
            'message': 'The mock has no ' + method})

port = int(sys.argv[1]) if len(sys.argv) > 1 else 8377
say('mock PDS on http://127.0.0.1:%d' % port)
ThreadingHTTPServer(('127.0.0.1', port), H).serve_forever()
