import os
import sys
import time
import subprocess
import datetime

SCRATCH_DIR = os.path.dirname(os.path.abspath(__file__))
ITEMS_WATCHER = os.path.join(SCRATCH_DIR, "sbox_items_watcher.py")
VOTE_EXECUTOR = os.path.join(SCRATCH_DIR, "execute_roadmap_votes.py")

def log(msg):
    now = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
    print(f"[{now}] {msg}", flush=True)

def run_step(script_path):
    try:
        res = subprocess.run([sys.executable, script_path], capture_output=True, text=True, timeout=60)
        if res.stdout:
            for l in res.stdout.strip().splitlines():
                log(f"  {l}")
        if res.stderr:
            for l in res.stderr.strip().splitlines():
                log(f"  [ERR] {l}")
    except Exception as e:
        log(f"  Failed running {os.path.basename(script_path)}: {e}")

def main():
    log("s&box Master Loot, Store & Roadmap Poller Daemon Started.")
    while True:
        log("Running scheduled cycle...")
        # 1. Check Store & Cosmetics (Silent if no changes)
        run_step(ITEMS_WATCHER)
        # 2. Check & execute any due roadmap votes
        run_step(VOTE_EXECUTOR)
        log("Cycle finished. Sleeping 300s (5m)...")
        time.sleep(300)

if __name__ == "__main__":
    main()
