#!/usr/bin/env python3
# summary: Send a permitted add-on request to the desktop host.
"""Send a declared add-on request to Starchaser's host from a restricted script."""
import argparse
import json
import os
import tempfile
import time
from pathlib import Path


def main():
    parser = argparse.ArgumentParser(prog="starchaser satellite request", description=__doc__)
    parser.add_argument('action', choices=('notify', 'panel', 'overlay', 'menu'))
    parser.add_argument('title', nargs='?', default='')
    parser.add_argument('body', nargs='?', default='')
    args = parser.parse_args()
    folder = os.environ.get('STARCHASER_SATELLITE_RUN')
    if not folder or not os.environ.get('STARCHASER_SATELLITE_ID'):
        parser.error('Run this request from an enabled add-on.')
    if len(args.title) > 120 or len(args.body) > 1000:
        parser.error('Use a short title and message.')
    root = Path(folder)
    root.mkdir(parents=True, exist_ok=True, mode=0o700)
    fd, temp = tempfile.mkstemp(prefix='.request-', dir=root)
    try:
        with os.fdopen(fd, 'w') as stream:
            json.dump({'action': args.action, 'title': args.title, 'body': args.body, 'at': time.time()*1000}, stream)
            stream.flush()
            os.fsync(stream.fileno())
        os.replace(temp, root / 'request.json')
    finally:
        Path(temp).unlink(missing_ok=True)
    return 0


if __name__ == '__main__':
    raise SystemExit(main())
