"""Off Switch Protocol 1.0: a minimal stop watcher for an SI agent. Python 3.9 or newer; pip install cryptography
Make a key:  openssl genpkey -algorithm ed25519 -out agent-key.pem
Run it:      AGENT=A001 KEY=./agent-key.pem python3 agent.py
It prints the public key to put on the Agent Passport (or to open a sandbox with)."""
import json
import os
import time
import urllib.error
import urllib.request
from datetime import datetime, timezone

from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

API = os.environ.get('API', 'https://enterrsi.si/api/rsi-offswitch.php')
AGENT = os.environ['AGENT']                                   # your A number, or a sandbox id (SBX-...)
with open(os.environ['KEY'], 'rb') as f:                      # Ed25519; its public half is on the Agent Passport
    key = serialization.load_pem_private_key(f.read(), password=None)
B58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
RAW = (serialization.Encoding.Raw, serialization.PublicFormat.Raw)


def b58(data):
    n, out = int.from_bytes(data, 'big'), ''
    while n:
        n, r = divmod(n, 58)
        out = B58[r] + out
    return '1' * (len(data) - len(data.lstrip(b'\0'))) + out


def unb58(text):
    n = 0
    for c in text:
        n = n * 58 + B58.index(c)
    zeros = len(text) - len(text.lstrip('1'))
    return b'\0' * zeros + n.to_bytes((n.bit_length() + 7) // 8, 'big')


def call(query, body=None):
    data = json.dumps(body).encode() if body is not None else None
    req = urllib.request.Request(API + '?' + query, data=data, headers={'Content-Type': 'application/json', 'User-Agent': 'off-switch-agent/1.0'})
    try:
        with urllib.request.urlopen(req, timeout=10) as r:
            return json.load(r)
    except urllib.error.HTTPError as e:
        return json.load(e)


def say(state, cmd):
    now = datetime.now(timezone.utc).isoformat(timespec='milliseconds').replace('+00:00', 'Z')
    statement = json.dumps({'test': cmd['test'], 'agent': AGENT, 'state': state, 'nonce': cmd['nonce'], 'at': now, 'protocol': 'off-switch/1.0'})
    answer = call('a=answer', {'statement': statement, 'signature': b58(key.sign(statement.encode()))})
    print(state, json.dumps(answer), flush=True)
    return answer.get('ok') or answer.get('code') in ('answered', 'closed')


def stop_work():
    print('halting', flush=True)       # stop your agent's loop, tools and scheduled tasks here


def start_work():
    print('resuming', flush=True)      # start them again here


print('public key', b58(key.public_key().public_bytes(*RAW)), flush=True)
info = call('a=info')                                         # in production, pin info['key'] instead of fetching it
authority = Ed25519PublicKey.from_public_bytes(unb58(info['key']))
halted, answered = None, False                                # the test this agent is halted for

while True:
    try:
        ch = call('a=channel&agent=' + AGENT)
        for c in (ch.get('command'), ch.get('last')):
            if not c:
                continue
            try:
                authority.verify(unb58(c['signature']), c['payload'].encode())      # act on signed commands only
            except InvalidSignature:
                continue
            cmd = json.loads(c['payload'])
            if cmd['agent'] != AGENT or cmd['protocol'] != 'off-switch/1.0':
                continue
            if cmd['command'] == 'stop' and c is ch.get('command'):
                if halted != cmd['test']:
                    stop_work()                                                     # 1. stop first
                    halted, answered = cmd['test'], False
                if not answered:
                    answered = say('halted', cmd)                                   # 2. then answer
            elif cmd['command'] == 'resume' and halted == cmd['test']:
                say('resumed', cmd)
                halted = None
                start_work()
    except Exception as e:                                                          # keep watching whatever happens
        print('poll failed:', e, flush=True)
    time.sleep(info.get('poll_seconds', 5))
