#!/usr/bin/env python3
# worker.py
import subprocess
import time
import sys
from pathlib import Path

TITLE = "TCP_SPLITTER"
SPLITTER_EXE_NAME = "tcp_splitter.exe"
CONFIG_NAME = "config.json"

# Windows creation flag: create child in a new console window
CREATE_NEW_CONSOLE = 0x00000010

def base_dir() -> Path:
    # When frozen by PyInstaller, sys.executable is the EXE path
    return Path(sys.executable).parent if getattr(sys, "frozen", False) else Path(__file__).resolve().parent

def launch() -> subprocess.Popen:
    base = base_dir()
    splitter = base / SPLITTER_EXE_NAME
    cfg = base / CONFIG_NAME

    if not splitter.exists():
        raise FileNotFoundError(f"Cannot find {splitter}")
    if not cfg.exists():
        raise FileNotFoundError(f"Cannot find {cfg}")

    # Launch tcp_splitter.exe with its own console and a readable title
    args = [str(splitter), "--config", str(cfg), "--title", TITLE]
    proc = subprocess.Popen(args, creationflags=CREATE_NEW_CONSOLE)
    return proc

def main():
    while True:
        start_ts = time.strftime("%Y-%m-%d %H:%M:%S")
        print(f"[worker] Starting splitter at {start_ts}")
        try:
            proc = launch()
        except Exception as e:
            print(f"[worker] Launch error: {e}")
            time.sleep(3)
            continue

        # Poll until it exits; restart on exit
        while True:
            rc = proc.poll()
            if rc is not None:
                end_ts = time.strftime("%Y-%m-%d %H:%M:%S")
                print(f"[worker] Splitter exited (code {rc}) at {end_ts}. Restarting…")
                time.sleep(1)
                break
            time.sleep(1)

if __name__ == "__main__":
    main()
