"""Minimal CAN job worker; requires VideoGrace VIP/src and websockets>=12."""
import asyncio
import logging
import os

from videograce import CANClient


async def handle(can, job):
    text = job.payload.get("text")
    if job.job_type != "example.echo" or not isinstance(text, str) or len(text.encode("utf-8")) > 65536:
        await can.fail(job.job_id, "Unsupported job or text exceeds 64 KiB")
        return
    await can.event(job.job_id, "running", "Processing example")
    await can.complete(job.job_id, "Example completed", {"echo": text})


async def main():
    can = CANClient(
        os.environ["VG_CAN_URL"], os.environ["VG_CAN_SERVICE_TOKEN"],
        os.environ.get("VG_CAN_NODE_ID", "example-worker-01"),
        "worker", ["example.echo"], max_concurrent_jobs=1,
    )
    await can.run(handle)


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        pass
