"""Run read-only Leo checks using this computer's saved OpenSSH host aliases."""
import argparse
import getpass
import json
from pathlib import Path
import re
import shutil
import subprocess
import time
from urllib.error import HTTPError
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener

ALIAS = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,62}\Z")
SERVICE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.@-]{0,95}\.service\Z")
URL = "https://162.35.61.111/ssh-worker"
COMMANDS = {"host": "hostname", "uptime": "uptime", "disk": "df -h /"}


class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, *args, **kwargs):
        return None


def execute(job, hosts, ssh):
    host, check = job["host"], job["check"]
    if host not in hosts:
        raise ValueError("Host is not in this connector's allowlist.")
    command = COMMANDS.get(check)
    if check == "service":
        service = job.get("service", "")
        if not SERVICE.fullmatch(service):
            raise ValueError("Invalid service name.")
        command = "systemctl is-active -- " + service
    if not command:
        raise ValueError("Unsupported SSH check.")
    reply = subprocess.run([ssh,"-T","-o","BatchMode=yes","-o","StrictHostKeyChecking=yes",
                            "-o","ClearAllForwardings=yes","-o","ConnectTimeout=7",host,command],
                           stdin=subprocess.DEVNULL,capture_output=True,timeout=18)
    summary = b"\n".join(block for block in (reply.stdout,reply.stderr) if block).decode(errors="replace")
    return {"ok": reply.returncode == 0, "output": summary[:4000].strip() or f"SSH exit {reply.returncode}."}


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--allow", action="append", required=True, help="One of your configured SSH host aliases. Repeat to include more.")
    args = parser.parse_args()
    hosts = sorted(set(args.allow))
    if not 1 <= len(hosts) <= 24 or any(not ALIAS.fullmatch(item) for item in hosts):
        parser.error("Specify 1–24 valid host aliases.")
    ssh = shutil.which("ssh")
    if not ssh:
        parser.error("OpenSSH is unavailable on this device.")
    key = getpass.getpass("Paste the temporary Leo connector code: ").strip()
    if not re.fullmatch(r"[A-Za-z0-9_-]{43}",key):
        parser.error("Invalid connector code.")
    opener = build_opener(ProxyHandler({}),NoRedirect())

    def call(**data):
        req = Request(URL,json.dumps(data).encode(),{"Content-Type":"application/json","Authorization":"Bearer "+key})
        with opener.open(req,timeout=10) as reply:
            return json.loads(reply.read(24000))

    print("Connected aliases:", ", ".join(hosts), flush=True)
    while True:
        try:
            job = call(action="claim",hosts=hosts)["job"]
            if job:
                print("Running",job["check"],"on",job["host"],flush=True)
                try:
                    result = execute(job,hosts,ssh)
                except (OSError,ValueError,subprocess.SubprocessError) as error:
                    result = {"ok":False,"output":f"SSH check could not complete: {type(error).__name__}."}
                call(action="result",id=job["id"],**result)
            time.sleep(3)
        except HTTPError as error:
            print(f"Leo connection closed ({error.code}).")
            break
        except KeyboardInterrupt:
            break
        except OSError:
            print("Could not contact Leo. Try again.",flush=True)
            time.sleep(3)


if __name__ == "__main__":
    main()
