"""Detached, single-instance supervisor for the review app and Cloudflare tunnel.

No system configuration, DNS or labels are changed. Child-process failures are
restarted; a machine/container restart still requires running `start` again.
"""
from __future__ import annotations

import argparse
from datetime import datetime, timezone
import fcntl
import json
import logging
import os
from pathlib import Path
import re
import signal
import socket
import subprocess
import sys
import threading
import time
from urllib.request import urlopen

PROJECT = Path(__file__).resolve().parents[1]
STATE = PROJECT/'outputs/pallet_structure_review_managed_v1'
PUBLIC = PROJECT/'outputs/pallet_structure_review_tunnel_v1/public_access.json'
CLOUDFLARED = Path('/tmp/opencode/pallet_review_tunnel/cloudflared')
LOCAL = 'http://127.0.0.1:3389'
URL_PATTERN = re.compile(r'https://[a-z0-9-]+\.trycloudflare\.com')
LOG = logging.getLogger('pallet.review.supervisor')


def timestamp():
    return datetime.now(timezone.utc).isoformat(timespec='seconds')


def read_json(path):
    try: return json.loads(path.read_text())
    except (OSError, ValueError): return {}


def write_json(path, value):
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_name(path.name+f'.{os.getpid()}.tmp')
    temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2)+'\n')
    os.replace(temporary, path)


def process_identity(pid):
    try:
        text = Path(f'/proc/{pid}/stat').read_text()
        fields = text[text.rfind(')')+2:].split()
        if fields[0] in ('Z', 'X'): return None
        return fields[19]  # /proc stat field 22: starttime.
    except (OSError, IndexError): return None


def health():
    try:
        with urlopen(LOCAL+'/healthz', timeout=2) as response:
            return response.status == 200 and json.load(response).get('status') == 'ok'
    except (OSError, ValueError): return False


def port_available():
    with socket.socket() as sock:
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        try: sock.bind(('0.0.0.0', 3389)); return True
        except OSError: return False


def running():
    state = read_json(STATE/'supervisor.json')
    pid = state.get('pid')
    if type(pid) is int and state.get('process_identity') == process_identity(pid): return state
    return None


class Child:
    def __init__(self, name, command, root, env):
        self.name, self.command, self.root, self.env = name, command, root, env
        self.process = None
        self.starts = 0
        self.started = 0.
        self.retry_at = 0.
        self.log_path = None
        self.offset = 0
        self.pending_text = ''
        self.url = None
        self.connected = False

    def ensure(self):
        now = time.monotonic()
        if self.process is not None:
            code = self.process.poll()
            if code is None: return False
            LOG.error('%s exited with status %s; scheduling restart', self.name, code)
            delay = 3 if now-self.started >= 60 else min(60, 3*2**min(self.starts-1, 4))
            self.process = None
            self.connected = False
            self.retry_at = now+delay
            return True
        if now < self.retry_at: return False
        self.starts += 1
        stamp = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S%fZ')
        self.log_path = self.root/f'{self.name}_{stamp}_{self.starts}.log'
        self.offset, self.pending_text, self.url, self.connected = 0, '', None, False
        with self.log_path.open('xb') as log:
            self.process = subprocess.Popen(self.command, cwd=PROJECT, env=self.env,
                stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, close_fds=True)
        self.started = now
        LOG.info('Started %s pid=%s log=%s', self.name, self.process.pid, self.log_path)
        return True

    def read_tunnel_status(self):
        if self.log_path is None: return False
        with self.log_path.open() as stream:
            stream.seek(self.offset)
            data = stream.read()
            self.offset = stream.tell()
        if not data: return False
        before = (self.url, self.connected)
        self.pending_text += data
        lines = self.pending_text.split('\n')
        self.pending_text = lines.pop()
        for line in lines:
            url = URL_PATTERN.search(line)
            if url: self.url = url[0]
            if 'Registered tunnel connection' in line: self.connected = True
            if 'Unregistered tunnel connection' in line or 'no more connections active' in line:
                self.connected = False
        if self.process is None: self.connected = False
        return before != (self.url, self.connected)

    def status(self):
        return {'pid': self.process.pid if self.process else None, 'starts': self.starts,
            'log': str(self.log_path) if self.log_path else None}

    def stop(self):
        if self.process is None or self.process.poll() is not None: return
        self.process.terminate()
        try: self.process.wait(timeout=8)
        except subprocess.TimeoutExpired:
            self.process.kill(); self.process.wait(timeout=5)


def supervise():
    STATE.mkdir(parents=True, exist_ok=True)
    logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')
    with (STATE/'supervisor.lock').open('a') as lock:
        try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError: raise SystemExit('A review supervisor is already active')
        if not CLOUDFLARED.is_file(): raise SystemExit('Cloudflared binary is missing')
        if not port_available(): raise SystemExit('Port 3389 is occupied; refusing to replace an existing service')
        old = read_json(PUBLIC)
        archive = STATE/('prior_public_access_'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S%fZ')+'.json')
        write_json(archive, old)
        previous_url = old.get('public_url')
        env = dict(os.environ, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1', PYTHONUNBUFFERED='1')
        app = Child('app', [sys.executable, '-m', 'pallet.structure_review', '--host', '0.0.0.0', '--port', '3389'], STATE, env)
        tunnel = Child('tunnel', [str(CLOUDFLARED), 'tunnel', '--no-autoupdate', '--url', LOCAL, '--protocol', 'http2'], STATE, env)
        stopped = threading.Event()
        for sig in (signal.SIGTERM, signal.SIGINT): signal.signal(sig, lambda *_: stopped.set())
        identity = process_identity(os.getpid())
        started = timestamp()
        def persist(state):
            status = {'state': state, 'pid': os.getpid(), 'process_identity': identity,
                'started_at': started, 'updated_at': timestamp(), 'app': app.status(), 'tunnel': tunnel.status(),
                'public_url': tunnel.url, 'tunnel_connected': tunnel.connected,
                'local_url': LOCAL, 'child_autorestart': True, 'detached_session': True,
                'boot_autostart_configured': False}
            write_json(STATE/'supervisor.json', status)
            write_json(PUBLIC, {'state': state, 'public_url': tunnel.url, 'previous_public_url': previous_url,
                'local_url': LOCAL, 'tunnel_type': 'cloudflare_quick_tunnel', 'temporary_url': True,
                'updated_at': status['updated_at'], 'tunnel_connected': tunnel.connected,
                'supervisor_status': str(STATE/'supervisor.json'),
                'access_key_file': 'outputs/pallet_structure_human_review_v1/access_key.txt',
                'child_autorestart': True, 'boot_autostart_configured': False})
        persist('starting')
        try:
            while not stopped.is_set():
                changed = app.ensure()
                # Keep an existing tunnel alive across app restarts to retain its URL.
                if tunnel.process is not None or health(): changed = tunnel.ensure() or changed
                changed = tunnel.read_tunnel_status() or changed
                if changed: persist('connected' if tunnel.connected and app.process else 'reconnecting')
                stopped.wait(1)
        finally:
            tunnel.stop(); app.stop(); tunnel.connected = False
            persist('stopped')


def start(timeout):
    state = running()
    if state:
        print(json.dumps(dict(state, already_running=True), ensure_ascii=False)); return
    if not CLOUDFLARED.is_file(): raise SystemExit('Cloudflared binary is missing')
    if not port_available(): raise SystemExit('Port 3389 already has a service; no processes were changed')
    STATE.mkdir(parents=True, exist_ok=True)
    with (STATE/'supervisor.log').open('ab') as log:
        process = subprocess.Popen([sys.executable, str(Path(__file__).resolve()), 'run'], cwd=PROJECT,
            stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT,
            start_new_session=True, close_fds=True)
    # Startup readiness, not a background tool-completion poll: wait for both the
    # local HTTP endpoint and the newly registered Cloudflare connection.
    deadline = time.monotonic()+timeout
    while time.monotonic() < deadline:
        state = running()
        if state and state['pid'] == process.pid and state.get('tunnel_connected') and health():
            print(json.dumps(state, ensure_ascii=False)); return
        if process.poll() is not None: raise SystemExit('Supervisor startup failed; see '+str(STATE/'supervisor.log'))
        time.sleep(1)
    raise SystemExit('Supervisor is still connecting; inspect '+str(STATE/'supervisor.json'))


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('command', choices=('start', 'run', 'status'))
    parser.add_argument('--timeout', type=int, default=90)
    args = parser.parse_args()
    if args.command == 'run': supervise()
    elif args.command == 'start': start(args.timeout)
    else: print(json.dumps({'supervisor': running(), 'local_http_healthy': health()}, ensure_ascii=False))


if __name__ == '__main__': main()
