import os
import subprocess
import json
import time

SESSION_FILE = r"c:\Projects\Historical\runpod_session.json"
SSH_KEY = os.path.expanduser(r"~/.ssh/id_ed25519")

with open(SESSION_FILE, "r") as f:
    session = json.load(f)

HOST = session["host"]
PORT = str(session["port"])

# Start background pipeline
ssh_cmd = [
    "ssh", "-o", "StrictHostKeyChecking=no", "-i", SSH_KEY, "-p", PORT, f"root@{HOST}",
    "nohup python3 -u /workspace/trt_pipeline.py > /workspace/trt_run.log 2>&1 &"
]
subprocess.run(ssh_cmd, check=True)
print("Pipeline launched in background!")

time.sleep(3)

# Check if running
ssh_check = [
    "ssh", "-o", "StrictHostKeyChecking=no", "-i", SSH_KEY, "-p", PORT, f"root@{HOST}",
    "ps aux | grep trt_pipeline.py | grep -v grep; head -n 30 /workspace/trt_run.log 2>/dev/null"
]
res = subprocess.run(ssh_check, capture_output=True, text=True, encoding="utf-8")
print(res.stdout)
if res.stderr:
    print(res.stderr)
