import os
import sys

from app.integrations.laravel_api import LaravelClient


def run(lock_path=None, poster=None):
    path = lock_path or os.environ.get("TELEGRAM_WORKER_LOCK", os.path.join(os.path.expanduser("~"), "telegram-private", "worker.lock"))
    directory = os.path.dirname(path)
    if directory and not os.path.isdir(directory):
        os.makedirs(directory, exist_ok=True)
    handle = open(path, "a+")
    try:
        import fcntl

        fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
    except (BlockingIOError, OSError):
        return {"ok": True, "busy": True}
    try:
        client = LaravelClient(poster=poster)
        if not client.ready():
            return {"ok": False, "error": "Laravel connection is not configured."}
        return client.post("/api/internal/telegram/work", {})
    finally:
        handle.close()


if __name__ == "__main__":
    result = run()
    sys.stdout.write(str(result.get("ok")) + "\n")
    sys.exit(0 if result.get("ok") or result.get("busy") else 1)
