from pythonosc.dispatcher import Dispatcher
from pythonosc.osc_server import BlockingOSCUDPServer
from datetime import datetime

HOST = "127.0.0.1"
PORT = 9001

def log(msg):
    print(msg, flush=True)

def on_test(address, *args):
    now = datetime.now().strftime("%H:%M:%S")

    log("")
    log(f"[INFO] time={now}")
    log(f"[ACTION] OSC parameter received")
    log(f"[INFO] address={address}")
    log(f"[INFO] args={args}")

dispatcher = Dispatcher()

dispatcher.map(
    "/avatar/parameters/TestPrint",
    on_test
)

log("[CHECK] STEP=1 OSC待受開始")
log(f"[INFO] host={HOST}")
log(f"[INFO] port={PORT}")

try:
    server = BlockingOSCUDPServer(
        (HOST, PORT),
        dispatcher
    )

    log("[INFO] OSC server started")
    log("[ACTION] VRChatでTestPrintを押してください")

    server.serve_forever()

except KeyboardInterrupt:
    log("")
    log("[INFO] Ctrl+C detected")
    log("[INFO] shutdown")

except Exception as e:
    log("")
    log("[FATAL] OSC server error")
    log(f"[ERROR] detail={e}")

    print("")
    input("Press Enter to exit...")
    raise SystemExit(1)
