#!/usr/bin/env python3
# summary: Manage Ask requests and local conversation history.
"""Ask's per-user streaming service. request reads JSON on stdin; history, load ID, clear, feedback ID yes|no, report ID and facts read local data only."""
import fcntl
import json
import os
import runpy
import select
import signal
import socket
import socketserver
import subprocess
import sys
import time
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from starchaser_ask_store import Store
from starchaser_ask_workers import WorkerPool, run_worker


def engine():
    return runpy.run_path(str(Path(__file__).resolve().with_name('starchaser-ask')))


def quick_fact(q):
    # The menu asks on typing; the fact readers are enough, so the Ask engine never starts for these.
    from starchaser_ask_facts import quick_fact as read
    return read(q)


def socket_path():
    root = Path(os.environ.get('XDG_RUNTIME_DIR') or f'/run/user/{os.getuid()}') / 'starchaser-ask'
    root.mkdir(mode=0o700, parents=True, exist_ok=True)
    os.chmod(root, 0o700)
    return root / 'service.sock'


class Handler(socketserver.StreamRequestHandler):
    def handle(self):
        # Unix permissions plus peer credentials: never accept another account's question.
        import struct
        _, uid, _ = struct.unpack('3i', self.request.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12))
        if uid != os.getuid(): return
        raw = self.rfile.readline(262145)
        if len(raw) > 262144: return
        try:
            packet = json.loads(raw)
            if not isinstance(packet, dict) or not isinstance(packet.get('question'), str) or not packet['question'].strip(): return
        except ValueError: return
        worker = self.server.workers.acquire(self.request)
        if worker is None: return
        child = worker.process
        reply, sent = None, []
        complete, pending = False, b''
        try:
            remaining = memoryview(json.dumps(packet).encode() + b'\n')
            while remaining:
                remaining = remaining[child.stdin.write(remaining):]
            while not complete:
                ready, _, _ = select.select([child.stdout, self.request], [], [], 1)
                if self.request in ready:
                    break
                if child.stdout not in ready:
                    if child.poll() is not None: break
                    continue
                chunk = os.read(child.stdout.fileno(), 65536)
                if not chunk: break
                pending += chunk
                while b'\n' in pending:
                    line, pending = pending.split(b'\n', 1)
                    try: event = json.loads(line)
                    except ValueError: continue
                    if event.get('_askComplete') is True:
                        complete = True
                        break
                    if 'sent' in event: sent.append(event['sent'])
                    if 'answer' in event: reply = event
                    self.wfile.write(line + b'\n'); self.wfile.flush()
            if reply and complete:
                ident = Store().save(packet['question'], reply, sent)
                self.wfile.write(json.dumps({'saved':ident}).encode() + b'\n'); self.wfile.flush()
        except (OSError, ValueError):
            pass
        finally:
            self.server.workers.release(worker, complete)


def serve():
    path = socket_path()
    lock = open(path.parent / 'lock', 'w')
    try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except BlockingIOError: return
    path.unlink(missing_ok=True)
    class Server(socketserver.ThreadingUnixStreamServer):
        daemon_threads = True
    with Server(str(path), Handler) as server:
        server.workers = WorkerPool()
        os.chmod(path, 0o600)
        signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
        try:
            server.serve_forever()
        finally:
            server.workers.close()
            path.unlink(missing_ok=True)


def request(packet):
    path = socket_path()
    conn = None
    for attempt in range(40):
        try:
            conn = socket.socket(socket.AF_UNIX)
            conn.connect(str(path)); break
        except (FileNotFoundError, ConnectionRefusedError):
            conn.close(); conn = None
            if attempt == 0:
                subprocess.Popen([sys.executable, str(Path(__file__).resolve()), 'serve'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
            time.sleep(.05)
    if conn is None: raise RuntimeError("Ask couldn't start. Try again.")
    with conn:
        conn.sendall(json.dumps(packet).encode() + b'\n')
        with conn.makefile('r') as stream:
            for line in stream: print(line, end='', flush=True)


def main(a):
    if a == ['serve']: serve(); return
    if a == ['worker']: run_worker(engine()); return
    if a == ['request']: request(json.loads(sys.stdin.readline())); return
    if a == ['facts']:
        print(json.dumps({'fact':quick_fact(sys.stdin.readline().strip())})); return
    store = Store()
    if a == ['history']: result = store.list()
    elif a == ['clear']: store.clear(); result = {'ok':True}
    elif len(a) == 2 and a[0] == 'load': result = store.get(a[1])
    elif len(a) == 2 and a[0] == 'report': result = {'report':store.report(a[1])}
    elif len(a) == 3 and a[0] == 'feedback' and a[2] in ('yes','no'):
        store.feedback(a[1], a[2] == 'yes'); result = {'ok':True}
    else: sys.exit(__doc__)
    print(json.dumps(result))

if __name__ == '__main__':
    from starchaser_cli import safe_streams
    safe_streams()
    if any(word in ('-h', '--help', 'help') for word in sys.argv[1:]):
        print(__doc__)
        sys.exit(0)
    try: main(sys.argv[1:])
    except (OSError, ValueError, RuntimeError) as e: sys.exit(str(e))
