import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.locks.LockSupport;

public class Worker {
    private static final Logger logger = LoggerFactory.getLogger(Worker.class);

    // Update this if you run a cluster
    private static final String ZOOKEEPER_ADDRESS = "127.0.0.1:2181";
    private static final int SESSION_TIMEOUT = 3000;

    private static final String AUTOHEALER_ZNODES_PATH = "/workers";
    private static final float CHANCE_TO_FAIL = 0.1F;

    private final Random random = new Random();
    private ZooKeeper zooKeeper;

    public void connectToZookeeper() throws IOException {
        this.zooKeeper = new ZooKeeper(ZOOKEEPER_ADDRESS, SESSION_TIMEOUT, event -> {});
        logger.info("Connected to ZooKeeper at {}", ZOOKEEPER_ADDRESS);
    }

    public void work() throws KeeperException, InterruptedException {
        addChildZnode();
        logger.info("Worker node created, starting work loop...");

        while (true) {
            // Minimal console output, detailed logs go to file
            logger.debug("Working...");

            LockSupport.parkNanos(100_000_000); // ~0.1 second

            if (random.nextFloat() < CHANCE_TO_FAIL) {
                logger.error("Critical error happened, exiting...");
                throw new RuntimeException("Worker simulated failure");
            }
        }
    }

    private void addChildZnode() throws KeeperException, InterruptedException {
        zooKeeper.create(AUTOHEALER_ZNODES_PATH + "/worker_",
                new byte[]{},
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL_SEQUENTIAL);
        logger.info("Registered ephemeral znode under {}", AUTOHEALER_ZNODES_PATH);
    }
}
