#!/usr/bin/env python3
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json, subprocess, time, re

HOST = '127.0.0.1'
PORT = 19091

def run_cmd(name, cmd, timeout=120):
    started = time.time()
    try:
        p = subprocess.run(
            cmd,
            shell=True,
            text=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            timeout=timeout,
            executable='/bin/bash',
        )
        out = p.stdout or ''
        out = re.sub(
            r'(?i)(api[_-]?key|token|secret|password|authorization|app_secret|verification_token|encrypt_key)([=: ]+)([^\s]+)',
            r'\1\2[REDACTED]',
            out,
        )
        return {
            'ok': p.returncode == 0,
            'name': name,
            'exit_code': p.returncode,
            'elapsed_sec': round(time.time() - started, 2),
            'stdout_tail': out[-4000:],
        }
    except subprocess.TimeoutExpired as e:
        out = (e.stdout or '') if isinstance(e.stdout, str) else ''
        return {
            'ok': False,
            'name': name,
            'exit_code': 124,
            'elapsed_sec': round(time.time() - started, 2),
            'stdout_tail': out[-2000:],
            'error': 'timeout',
        }
    except Exception as e:
        return {
            'ok': False,
            'name': name,
            'exit_code': 125,
            'elapsed_sec': round(time.time() - started, 2),
            'stdout_tail': '',
            'error': type(e).__name__ + ': ' + str(e),
        }

class Handler(BaseHTTPRequestHandler):
    def _send(self, code, obj):
        body = json.dumps(obj, ensure_ascii=False, indent=2).encode('utf-8')
        self.send_response(code)
        self.send_header('Content-Type', 'application/json; charset=utf-8')
        self.send_header('Content-Length', str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, fmt, *args):
        print(time.strftime('%Y-%m-%d %H:%M:%S'), self.client_address[0], fmt % args, flush=True)

    def do_GET(self):
        path = self.path.split('?', 1)[0]
        if path == '/health':
            return self._send(200, {'ok': True, 'service': 'kestra-poc-bridge', 'time': time.strftime('%Y-%m-%d %H:%M:%S')})
        if path == '/ping/bot1':
            cmd = "HOME=/Users/bot1 hermes -p it chat -q 'Reply exactly BOT1_OK.' -t none -Q"
            return self._send(200, run_cmd('bot1_profile_ping', cmd, timeout=180))
        if path == '/ping/openclaw':
            cmd = "HOME=/Users/bot1 openclaw health 2>/dev/null || HOME=/Users/bot1 openclaw status 2>/dev/null || HOME=/Users/bot1 openclaw --version"
            return self._send(200, run_cmd('openclaw_ping', cmd, timeout=60))
        if path == '/ping/bot2':
            cmd = "ssh -o BatchMode=yes -o ConnectTimeout=8 bot2 \"HOME=/Users/bot2 hermes -p it2 chat -q 'Reply exactly BOT2_OK.' -t none -Q\""
            return self._send(200, run_cmd('bot2_profile_ping', cmd, timeout=240))
        return self._send(404, {'ok': False, 'error': 'unknown path', 'path': path})

if __name__ == '__main__':
    httpd = ThreadingHTTPServer((HOST, PORT), Handler)
    print(f'kestra-poc-bridge listening on http://{HOST}:{PORT}', flush=True)
    httpd.serve_forever()
