"""Tiny stub of the RoboVisionAI_PI motor server for local smoke tests.
Listens on :8765 and logs every /trigger-motor and /stop-motors call.
Run with:  python stub_motor_server.py
"""
from http.server import BaseHTTPRequestHandler, HTTPServer
import json, threading, time

LOCK = threading.Lock()
ACTIVE = None  # (motor_name, until_ts)

class H(BaseHTTPRequestHandler):
    def log_message(self, fmt, *a): pass
    def _send(self, code, body):
        self.send_response(code); self.send_header("Content-Type","application/json"); self.end_headers()
        self.wfile.write(json.dumps(body).encode())
    def do_POST(self):
        global ACTIVE
        ln = int(self.headers.get("Content-Length","0"))
        body = json.loads(self.rfile.read(ln) or b"{}")
        if self.path == "/trigger-motor":
            with LOCK:
                now = time.time()
                if ACTIVE and ACTIVE[1] > now:
                    self._send(409, {"error":"busy", "active": ACTIVE[0]})
                    return
                name = body["motor_name"]; secs = int(body["seconds"])
                ACTIVE = (name, now + secs)
            print(f"[stub] TRIGGER {name} for {secs}s")
            threading.Timer(secs, lambda: (print(f"[stub] DONE {name}"), _clear(name))).start()
            self._send(200, {"ok": True, "motor": name, "seconds": secs})
        elif self.path == "/stop-motors":
            with LOCK:
                ACTIVE = None
            print("[stub] STOP all")
            self._send(200, {"ok": True})
        else:
            self._send(404, {"error":"unknown path"})

def _clear(name):
    global ACTIVE
    with LOCK:
        if ACTIVE and ACTIVE[0] == name:
            ACTIVE = None

if __name__ == "__main__":
    HTTPServer(("127.0.0.1", 8765), H).serve_forever()