# -*- coding: utf-8 -*-
"""
qr_agent.py — Supervisor for the Etqan QR verify service (runs on AbuMalik).

Reconciles the ACTUAL state of serve_verify.py (+ Tailscale funnel on port 8088)
to the DESIRED state chosen by admins in BI settings (services_settings.asp).

- Reads desired via HTTP:  GET  qr_agent.asp?op=poll&k=SECRET   -> "1"/"0"
- Reports heartbeat:       GET  qr_agent.asp?op=report&k=SECRET&up=1|0
No DB credentials live here; all DB access happens inside the ASP endpoint.

Run continuously (e.g. a Scheduled Task at logon). Loops every POLL seconds.
"""
import os
import sys
import time
import socket
import subprocess
import urllib.request
import urllib.parse

# ---- config ----
BASE   = "http://10.22.158.26/Mawared-Plus/admin/qr_agent.asp"
SECRET = "etqan-qr-9f3a7c2e"
ROOT   = r"D:\Projects\mawared-plus\public_verify"
SERVE  = os.path.join(ROOT, "serve_verify.py")
PYTHON = sys.executable or "python"
PORT   = 8088
POLL   = 20          # seconds between reconciliations

CREATE_NEW_PROCESS_GROUP = 0x00000200


def log(msg):
    print(time.strftime("%Y-%m-%d %H:%M:%S") + "  " + msg, flush=True)


def ts_exe():
    for c in ("tailscale", r"C:\Program Files\Tailscale\tailscale.exe"):
        try:
            subprocess.run([c, "version"], capture_output=True, timeout=8)
            return c
        except Exception:
            continue
    return "tailscale"


TS = ts_exe()


def server_up():
    """True if something answers on 127.0.0.1:PORT."""
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(1.5)
    try:
        s.connect(("127.0.0.1", PORT))
        return True
    except Exception:
        return False
    finally:
        try:
            s.close()
        except Exception:
            pass


def poll_desired():
    """Return True/False, or None on network error (keep last)."""
    url = BASE + "?op=poll&k=" + urllib.parse.quote(SECRET)
    try:
        with urllib.request.urlopen(url, timeout=15) as r:
            return r.read().decode("utf-8", "ignore").strip() == "1"
    except Exception as e:
        log("poll failed: %s" % e)
        return None


def report(up):
    url = BASE + "?op=report&k=" + urllib.parse.quote(SECRET) + "&up=" + ("1" if up else "0")
    try:
        with urllib.request.urlopen(url, timeout=15) as r:
            r.read()
    except Exception as e:
        log("report failed: %s" % e)


def kill_port(port):
    """Kill whatever process is LISTENING on the given TCP port (not ourselves)."""
    try:
        out = subprocess.check_output("netstat -ano -p tcp", shell=True,
                                      text=True, errors="ignore")
    except Exception:
        return
    pids = set()
    needle = ":%d " % port
    for line in out.splitlines():
        if needle in line and "LISTENING" in line.upper():
            pid = line.split()[-1]
            if pid.isdigit() and pid not in ("0", str(os.getpid())):
                pids.add(pid)
    for pid in pids:
        subprocess.call("taskkill /F /PID %s" % pid, shell=True,
                        stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


def funnel_on():
    subprocess.call([TS, "funnel", "--bg", str(PORT)],
                    stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


def funnel_off():
    subprocess.call([TS, "funnel", "reset"],
                    stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


def start_server():
    kill_port(PORT)  # clear any stale listener first
    log("starting serve_verify.py ...")
    return subprocess.Popen([PYTHON, SERVE], cwd=ROOT,
                            creationflags=CREATE_NEW_PROCESS_GROUP)


def main():
    log("qr_agent started (python=%s, tailscale=%s)" % (PYTHON, TS))
    child = None
    last_desired = True
    while True:
        try:
            child, last_desired = tick(child, last_desired)
        except Exception as e:
            log("tick error (continuing): %s" % e)
        time.sleep(POLL)


def tick(child, last_desired):
    if True:
        desired = poll_desired()
        if desired is None:
            desired = last_desired
        else:
            last_desired = desired

        up = server_up()

        if desired and not up:
            funnel_on()
            try:
                child = start_server()
            except Exception as e:
                log("start failed: %s" % e)
            time.sleep(2)
            up = server_up()
            log("reconcile -> started, up=%s" % up)

        elif (not desired) and up:
            log("reconcile -> stopping (admin requested off)")
            if child is not None:
                try:
                    child.terminate()
                except Exception:
                    pass
                child = None
            kill_port(PORT)
            funnel_off()
            up = False

        report(up)
        return child, last_desired


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        pass
