/**
 * @file liveside.c
 * @brief Tiny portable live-reload server using Server-Sent Events.
 *
 * liveside: watch a directory for changes and notify connected
 * browsers over Server-Sent Events (SSE) so they can reload themselves.
 *
 * This is deliberately NOT a file server — pair it with whatever's
 * already serving the site (darkhttpd, lighttpd, python3 -m http.server,
 * ...), running on its own port. liveside only ever answers two
 * requests: `/livereload` (the SSE stream) and `/liveside.js` (the client
 * snippet). Point a page's <script src="http://localhost:PORT/liveside.js">
 * at it — cross-origin script tags don't need CORS — and it reconnects on
 * its own and reloads the page whenever a watched file changes.
 *
 * File-change detection is platform-native where available (kqueue on
 * macOS/BSD, inotify on Linux) so reloads are instant instead of waiting
 * on a poll interval; anywhere else (including Windows) it falls back to
 * polling.
 *
 * The server body is POSIX-first: it uses poll, dirent, unistd, stat, and BSD
 * socket concepts. TinyCThread supplies the portable thread/mutex API, and
 * frankensocket smooths the small unavoidable POSIX/Win32 socket differences.
 */

#include <errno.h>
#include <signal.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#ifdef _WIN32
#include "ports/frankensocket/frankensocket.h"

#include <dirent.h>
#include <fcntl.h>
#include <getopt.h>
#include <poll.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <tinycthread.h>
#include <unistd.h>

#include "ports/ignore/ignore.h"

#define lstat stat
#ifndef S_ISDIR
#define S_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR)
#endif
#ifndef S_ISREG
#define S_ISREG(m) (((m) & _S_IFMT) == _S_IFREG)
#endif
#else
#include <dirent.h>
#include <fcntl.h>
#include <poll.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <tinycthread.h>
#include <unistd.h>

#include "ports/frankensocket/frankensocket.h"
#include "ports/ignore/ignore.h"
#endif

static void
usleep_ms(long ms)
{
	struct timespec ts;
	ts.tv_sec = ms / 1000;
	ts.tv_nsec = (ms % 1000) * 1000000L;
	thrd_sleep(&ts, NULL);
}

static long long
now_ms(void)
{
	struct timeval tv;
	gettimeofday(&tv, NULL);
	return (long long)tv.tv_sec * 1000 + tv.tv_usec / 1000;
}

#if defined(_WIN32)
#define WATCH_WIN32 1
#include "ports/win32/watch.h"
#elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || \
    defined(__OpenBSD__) || defined(__DragonFly__)
#define WATCH_KQUEUE 1
#include <sys/event.h>
#include <sys/resource.h>
#include <sys/time.h>
#elif defined(__linux__)
#define WATCH_INOTIFY 1
#include <sys/inotify.h>
#else
#define WATCH_POLL 1
#endif

static volatile sig_atomic_t g_running = 1;
static uint16_t g_port = 8081;
static const char *g_watch_dir = ".";
static const char *g_build_cmd = NULL;
static int g_poll_ms = 300; /* only used by the WATCH_POLL fallback */
static ignore_context_t g_ignore;

/**
 * @brief Decide whether a path should be skipped by watchers.
 * @param path Path to test.
 * @param is_dir Whether @p path is a directory.
 * @return true when @p path is ignored, false otherwise.
 */
static bool
path_ignored(const char *path, bool is_dir)
{
	return ignore_path_ignored(&g_ignore, path, is_dir);
}

static void
tree_scan_signature(const char *path, unsigned long *sig)
{
	DIR *dir = opendir(path);
	if (!dir)
		return;
	struct dirent *entry;
	while ((entry = readdir(dir)) != NULL) {
		char child[4096];
		snprintf(child, sizeof(child), "%s/%s", path, entry->d_name);
		struct stat st;
		if (lstat(child, &st) != 0)
			continue;
		bool is_dir = S_ISDIR(st.st_mode);
		if (path_ignored(child, is_dir) || ignore_is_ignore_file(child))
			continue;
		for (const char *p = entry->d_name; *p; p++)
			*sig = *sig * 131 + (unsigned char) * p;
		if (is_dir)
			tree_scan_signature(child, sig);
		else if (S_ISREG(st.st_mode)) {
			*sig ^= (unsigned long)st.st_mtime * 2654435761UL;
			*sig ^= (unsigned long)st.st_size;
		}
	}
	closedir(dir);
}

static unsigned long
tree_signature(const char *root)
{
	unsigned long sig = 0;
	tree_scan_signature(root, &sig);
	return sig;
}

/** @name Watcher backend
 *
 * Opaque watcher abstraction implemented by kqueue, inotify, or a polling
 * fallback. Each backend provides watch_open(), watch_wait(), watch_settle(),
 * and watch_close().
 * @{
 */

typedef struct watcher watcher_t;

#if defined(WATCH_WIN32)

struct watcher {
	win32_watch_t *native;
};

static watcher_t *
watch_open(const char *root)
{
	watcher_t *w = calloc(1, sizeof(*w));
	if (!w)
		return NULL;
	w->native = win32_watch_open(root, &g_ignore);
	if (!w->native) {
		free(w);
		return NULL;
	}
	printf("[liveside] watching '%s' via ReadDirectoryChangesW\n", root);
	return w;
}

static bool
watch_wait(watcher_t *w)
{
	return win32_watch_wait(w->native);
}

static void
watch_settle(watcher_t *w)
{
	(void)w;
	usleep_ms(150);
}

static void
watch_close(watcher_t *w)
{
	if (!w)
		return;
	win32_watch_close(w->native);
	free(w);
}

#elif defined(WATCH_KQUEUE)

struct kq_path {
	int fd;
	bool ignore_file;
};

struct watcher {
	int kq;
	struct kq_path *paths;
	size_t count, cap;
	char root[4096];
	unsigned long last_sig;
};

/**
 * @brief Add one file or directory vnode to a kqueue watcher.
 * @param w Watcher receiving the new file descriptor and kevent.
 * @param path File-system path to monitor.
 */
static void
kq_add_path(watcher_t *w, const char *path)
{
	if (w->count == w->cap) {
		w->cap = w->cap ? w->cap * 2 : 64;
		w->paths = realloc(w->paths, w->cap * sizeof(*w->paths));
	}
	int flags;
	int fd;

#ifdef O_EVTONLY
	/* O_EVTONLY: get notifications without holding the file open in a
	 * way that blocks unmounts/deletes underneath us. This is available
	 * on macOS; BSDs use a normal read-only descriptor for EVFILT_VNODE. */
	flags = O_EVTONLY;
#else
	flags = O_RDONLY;
#endif
	fd = open(path, flags);
	if (fd < 0)
		return;
	/* Deliberately no NOTE_ATTRIB: it fires on *any* attribute change,
	 * not just content-relevant ones, including a plain atime bump from
	 * something merely reading the file (e.g. Spotlight/mdworker
	 * indexing it shortly after a save) -- indistinguishable from a real
	 * edit but with nothing to actually reload. NOTE_WRITE/NOTE_EXTEND
	 * already cover real content changes; a bare `touch` with no
	 * write() won't trigger a reload here, which is the right call for
	 * this tool's purpose. */
	struct kevent kev;
	EV_SET(&kev, fd, EVFILT_VNODE, EV_ADD | EV_CLEAR,
	       NOTE_WRITE | NOTE_DELETE | NOTE_RENAME | NOTE_EXTEND |
	       NOTE_LINK,
	       0, NULL);
	if (kevent(w->kq, &kev, 1, NULL, 0, NULL) < 0) {
		close(fd);
		return;
	}
	w->paths[w->count].fd = fd;
	w->paths[w->count].ignore_file = ignore_is_ignore_file(path);
	w->count++;
}

/**
 * @brief Recursively add a tree of regular files and directories to kqueue.
 * @param w Watcher to populate.
 * @param path Root of the subtree being scanned.
 */
static void
kq_scan(watcher_t *w, const char *path)
{
	kq_add_path(w, path);
	DIR *dir = opendir(path);
	if (!dir)
		return;
	struct dirent *entry;
	while ((entry = readdir(dir)) != NULL) {
		char child[4096];
		snprintf(child, sizeof(child), "%s/%s", path, entry->d_name);
		struct stat st;
		if (lstat(child, &st) != 0)
			continue;
		bool is_dir = S_ISDIR(st.st_mode);
		if (path_ignored(child, is_dir))
			continue;
		if (is_dir)
			kq_scan(w, child);
		else if (S_ISREG(st.st_mode))
			kq_add_path(w, child);
	}
	closedir(dir);
}

/**
 * @brief Rebuild all kqueue watches after tree structure changes.
 * @param w Watcher to refresh.
 */
static void
kq_rebuild(watcher_t *w)
{
	for (size_t i = 0; i < w->count; i++)
		close(w->paths[i].fd);
	w->count = 0;
	kq_scan(w, w->root);
}

/**
 * @brief Initialize the active platform watcher backend.
 * @param root Root directory to watch recursively.
 * @return Allocated watcher, or NULL on failure.
 */
static watcher_t *
watch_open(const char *root)
{
	/* Watching every file needs one fd each; raise the soft limit to
	 * whatever the hard limit allows so a normal-sized site doesn't
	 * quietly hit macOS's low default (often 256). */
	struct rlimit rl;
	if (getrlimit(RLIMIT_NOFILE, &rl) == 0) {
		rl.rlim_cur = rl.rlim_max;
		setrlimit(RLIMIT_NOFILE, &rl);
	}
	watcher_t *w = calloc(1, sizeof(*w));
	w->kq = kqueue();
	if (w->kq < 0) {
		free(w);
		return 0;
	}
	snprintf(w->root, sizeof(w->root), "%s", root);
	w->last_sig = tree_signature(root);
	kq_rebuild(w);
	printf("[liveside] watching %zu paths via kqueue\n", w->count);
	return w;
}

/**
 * @brief Block until a relevant file-system change is detected.
 * @param w Active watcher.
 * @return true after a normal wakeup/interrupted wait, false on fatal error.
 */
static bool
watch_wait(watcher_t *w)
{
	struct kevent ev;
	int n;
again:
	n = kevent(w->kq, NULL, 0, &ev, 1, NULL); /* blocks */
	if (n < 0)
		return errno == EINTR;
	if (n == 0)
		return true;
	bool ignore_file_event = false;
	for (size_t i = 0; i < w->count; i++) {
		if ((uintptr_t)w->paths[i].fd == ev.ident) {
			ignore_file_event = w->paths[i].ignore_file;
			break;
		}
	}
	/* Debounce: a save is often a write + truncate + attrib change in
	 * quick succession, and `make` can touch several files at once.
	 * Coalesce whatever else is pending into a single reload. Note we
	 * deliberately don't call kq_rebuild() here -- the existing watches
	 * are still valid for this notification, and watch_settle() (called
	 * by the caller after it's done reacting, e.g. after running a -c
	 * build) is what refreshes the watch set. Rebuilding here too would
	 * just double the (expensive, one-open()-per-file) cost of every
	 * detected change for no benefit. */
	usleep_ms(80);
	struct kevent drain[64];
	struct timespec zero = {0, 0};
	while (kevent(w->kq, NULL, 0, drain, 64, &zero) > 0)
		;
	unsigned long cur_sig = tree_signature(w->root);
	if (ignore_file_event || cur_sig == w->last_sig) {
		kq_rebuild(w);
		w->last_sig = cur_sig;
		goto again;
	}
	w->last_sig = cur_sig;
	return true;
}

/** Absorbs any filesystem events generated by our own -c build command,
 * so they aren't mistaken for the next user-made change. See the comment
 * on watch_settle's call site in watcher_loop for why this exists. */
static void
watch_settle(watcher_t *w)
{
	usleep_ms(150);
	struct kevent drain[64];
	struct timespec zero = {0, 0};
	while (kevent(w->kq, NULL, 0, drain, 64, &zero) > 0)
		;
	kq_rebuild(w);
	w->last_sig = tree_signature(w->root);
}

/**
 * @brief Release all resources owned by a watcher.
 * @param w Watcher to destroy; may be NULL where supported.
 */
static void
watch_close(watcher_t *w)
{
	if (!w)
		return;
	for (size_t i = 0; i < w->count; i++)
		close(w->paths[i].fd);
	free(w->paths);
	close(w->kq);
	free(w);
}

#elif defined(WATCH_INOTIFY)

struct watch_entry {
	int wd;
	char path[4096];
};

struct watcher {
	int fd;
	struct watch_entry *entries;
	size_t count, cap;
	char root[4096];
};

/**
 * @brief Recursively add a directory and its subdirectories to inotify.
 * @param w Watcher to populate.
 * @param path Directory path to monitor.
 */
static void
in_add_dir(watcher_t *w, const char *path)
{
	/* inotify watches report changes to files *inside* a watched
	 * directory, so unlike kqueue we only need one watch per directory,
	 * not per file.
	 *
	 * Deliberately no IN_ATTRIB, matching kq_add_path's reasoning on the
	 * kqueue side: it fires on any metadata change including a plain
	 * atime bump from something merely reading the file (e.g. a search
	 * indexer), which was confirmed (on macOS/kqueue; untested here on
	 * Linux, but the same class of issue applies) to cause a spurious
	 * second "change" shortly after a real edit, with nothing new to
	 * actually reload. IN_MODIFY/IN_CLOSE_WRITE already cover real
	 * content changes. */
	int wd = inotify_add_watch(w->fd, path,
	                           IN_MODIFY | IN_CREATE | IN_DELETE | IN_MOVED_FROM |
	                           IN_MOVED_TO | IN_CLOSE_WRITE);
	if (wd < 0)
		return;
	if (w->count == w->cap) {
		w->cap = w->cap ? w->cap * 2 : 64;
		w->entries = realloc(w->entries, w->cap * sizeof(*w->entries));
	}
	w->entries[w->count].wd = wd;
	snprintf(w->entries[w->count].path, sizeof(w->entries[w->count].path),
	         "%s", path);
	w->count++;
	DIR *dir = opendir(path);
	if (!dir)
		return;
	struct dirent *entry;
	while ((entry = readdir(dir)) != NULL) {
		char child[4096];
		snprintf(child, sizeof(child), "%s/%s", path, entry->d_name);
		struct stat st;
		if (lstat(child, &st) == 0 && S_ISDIR(st.st_mode) &&
		    !path_ignored(child, true))
			in_add_dir(w, child);
	}
	closedir(dir);
}

/**
 * @brief Rebuild all inotify directory watches after tree changes.
 * @param w Watcher to refresh.
 */
static void
in_rebuild(watcher_t *w)
{
	for (size_t i = 0; i < w->count; i++)
		inotify_rm_watch(w->fd, w->entries[i].wd);
	w->count = 0;
	in_add_dir(w, w->root);
}

/**
 * @brief Initialize the active platform watcher backend.
 * @param root Root directory to watch recursively.
 * @return Allocated watcher, or NULL on failure.
 */
static watcher_t *
watch_open(const char *root)
{
	watcher_t *w = calloc(1, sizeof(*w));
	w->fd = inotify_init1(0);
	if (w->fd < 0) {
		free(w);
		return 0;
	}
	snprintf(w->root, sizeof(w->root), "%s", root);
	in_rebuild(w);
	printf("[liveside] watching %zu directories via inotify\n",
	       w->count);
	return w;
}

/**
 * @brief Block until a relevant file-system change is detected.
 * @param w Active watcher.
 * @return true after a normal wakeup/interrupted wait, false on fatal error.
 */
static bool
watch_wait(watcher_t *w)
{
	char buf[4096] __attribute__((aligned(__alignof__(struct inotify_event))));
again:
	ssize_t n = read(w->fd, buf, sizeof(buf)); /* blocks */
	if (n < 0)
		return errno == EINTR;
	if (n == 0)
		return true;
	bool relevant = false;
	for (char *p = buf; p < buf + n;) {
		struct inotify_event *ev = (struct inotify_event *)p;
		const char *dir = NULL;
		for (size_t i = 0; i < w->count; i++)
			if (w->entries[i].wd == ev->wd)
				dir = w->entries[i].path;
		if (dir && ev->len > 0) {
			char full[4096];
			snprintf(full, sizeof(full), "%s/%s", dir, ev->name);
			bool is_dir = (ev->mask & IN_ISDIR) != 0;
			if (!ignore_is_ignore_file(full) && !path_ignored(full, is_dir))
				relevant = true;
		}
		p += sizeof(*ev) + ev->len;
	}
	usleep_ms(80);
	struct pollfd pfd = {.fd = w->fd, .events = POLLIN};
	while (poll(&pfd, 1, 0) > 0 && (pfd.revents & POLLIN))
		read(w->fd, buf, sizeof(buf));
	/* No in_rebuild() here -- see the matching comment in the kqueue
	 * watch_wait() above. watch_settle() does the one rebuild that's
	 * actually needed, after the caller's done reacting. */
	if (!relevant) {
		in_rebuild(w);
		goto again;
	}
	return true;
}

/** Absorbs any filesystem events generated by our own -c build command,
 * so they aren't mistaken for the next user-made change. See the comment
 * on watch_settle's call site in watcher_loop for why this exists. */
static void
watch_settle(watcher_t *w)
{
	usleep_ms(150);
	char buf[4096] __attribute__((aligned(__alignof__(struct inotify_event))));
	struct pollfd pfd = {.fd = w->fd, .events = POLLIN};
	while (poll(&pfd, 1, 0) > 0 && (pfd.revents & POLLIN))
		read(w->fd, buf, sizeof(buf));
	in_rebuild(w);
}

/**
 * @brief Release all resources owned by a watcher.
 * @param w Watcher to destroy; may be NULL where supported.
 */
static void
watch_close(watcher_t *w)
{
	if (!w)
		return;
	for (size_t i = 0; i < w->count; i++)
		inotify_rm_watch(w->fd, w->entries[i].wd);
	free(w->entries);
	close(w->fd);
	free(w);
}

#else /* WATCH_POLL */

struct watcher {
	char root[4096];
	unsigned long last;
	unsigned long last_ignore;
};

/**
 * @brief Fold a directory tree snapshot into a lightweight polling signature.
 * @param path Directory to scan recursively.
 * @param sig In/out hash accumulator updated with names, sizes, and mtimes.
 */
static void
poll_scan(const char *path, unsigned long *sig, bool ignore_files_only)
{
	DIR *dir = opendir(path);
	if (!dir)
		return;
	struct dirent *entry;
	while ((entry = readdir(dir)) != NULL) {
		char child[4096];
		snprintf(child, sizeof(child), "%s/%s", path, entry->d_name);
		struct stat st;
		if (lstat(child, &st) != 0)
			continue;
		bool is_dir = S_ISDIR(st.st_mode);
		bool is_ignore_file = ignore_is_ignore_file(child);
		if (path_ignored(child, is_dir))
			continue;
		if (ignore_files_only != is_ignore_file && !is_dir)
			continue;
		for (const char *p = entry->d_name; *p; p++)
			*sig = *sig * 131 + (unsigned char) * p;
		if (is_dir) {
			poll_scan(child, sig, ignore_files_only);
		} else if (S_ISREG(st.st_mode)) {
			*sig ^= (unsigned long)st.st_mtime * 2654435761UL;
			*sig ^= (unsigned long)st.st_size;
		}
	}
	closedir(dir);
}

/**
 * @brief Compute a polling signature for a whole watched tree.
 * @param root Root directory to scan.
 * @return Hash-like signature of current file names, sizes, and mtimes.
 */
static unsigned long
poll_snapshot(const char *root, bool ignore_files_only)
{
	unsigned long sig = 0;
	poll_scan(root, &sig, ignore_files_only);
	return sig;
}

/**
 * @brief Initialize the active platform watcher backend.
 * @param root Root directory to watch recursively.
 * @return Allocated watcher, or NULL on failure.
 */
static watcher_t *
watch_open(const char *root)
{
	watcher_t *w = calloc(1, sizeof(*w));
	snprintf(w->root, sizeof(w->root), "%s", root);
	w->last = poll_snapshot(root, false);
	w->last_ignore = poll_snapshot(root, true);
	printf("[liveside] watching '%s' via polling (%dms interval)\n",
	       root, g_poll_ms);
	return w;
}

/**
 * @brief Block until a relevant file-system change is detected.
 * @param w Active watcher.
 * @return true after a normal wakeup/interrupted wait, false on fatal error.
 */
static bool
watch_wait(watcher_t *w)
{
	while (g_running) {
		usleep_ms(g_poll_ms);
		unsigned long cur_ignore = poll_snapshot(w->root, true);
		unsigned long cur = poll_snapshot(w->root, false);
		if (cur_ignore != w->last_ignore && cur == w->last) {
			w->last_ignore = cur_ignore;
			continue;
		}
		if (cur != w->last) {
			w->last = cur;
			w->last_ignore = cur_ignore;
			return true;
		}
	}
	return true;
}

/** Absorbs any filesystem changes made by our own -c build command, so
 * they aren't mistaken for the next user-made change. See the comment
 * on watch_settle's call site in watcher_loop for why this exists. */
static void
watch_settle(watcher_t *w)
{
	w->last = poll_snapshot(w->root, false);
	w->last_ignore = poll_snapshot(w->root, true);
}

/**
 * @brief Release all resources owned by a watcher.
 * @param w Watcher to destroy; may be NULL where supported.
 */
static void
watch_close(watcher_t *w)
{
	free(w);
}

#endif

/** @}
 * @name SSE client registry
 *
 * Tracks connected browser EventSource sockets and broadcasts reload frames.
 * @{
 */

#define MAX_CLIENTS 64

static SOCKET g_client_fds[MAX_CLIENTS];
static int g_nclients = 0;
static mtx_t g_clients_mu;

/**
 * @brief Register a newly connected SSE client socket.
 * @param fd Connected socket whose ownership moves to the registry on success.
 */
static void
add_client(SOCKET fd)
{
	mtx_lock(&g_clients_mu);
	if (g_nclients < MAX_CLIENTS) {
		g_client_fds[g_nclients++] = fd;
	} else {
		fprintf(stderr, "[liveside] client limit reached, dropping\n");
		frankensocket_close(fd);
	}
	mtx_unlock(&g_clients_mu);
}

/**
 * @brief Remove and close an SSE client socket.
 * @param fd Socket descriptor to drop from the registry.
 */
static void
remove_client(SOCKET fd)
{
	mtx_lock(&g_clients_mu);
	for (int i = 0; i < g_nclients; i++) {
		if (g_client_fds[i] == fd) {
			g_client_fds[i] = g_client_fds[--g_nclients];
			break;
		}
	}
	frankensocket_close(fd);
	mtx_unlock(&g_clients_mu);
}

/**
 * @brief Send a raw SSE frame or comment to every connected client.
 *
 * Clients whose socket write fails are removed from the registry after the
 * broadcast pass so the registry is not modified while it is being iterated.
 *
 * @param msg Buffer containing the bytes to send.
 * @param len Number of bytes in @p msg.
 */
static void
broadcast(const char *msg, size_t len)
{
	SOCKET dead[MAX_CLIENTS];
	int ndead = 0;
	mtx_lock(&g_clients_mu);
	int n = g_nclients;
	for (int i = 0; i < n; i++) {
		if (frankensocket_send(g_client_fds[i], msg, len) < 0)
			dead[ndead++] = g_client_fds[i];
	}
	mtx_unlock(&g_clients_mu);
	for (int i = 0; i < ndead; i++)
		remove_client(dead[i]);
}

/** @brief Broadcast the SSE reload event to all connected browsers. */
static void
broadcast_reload(void)
{
	static const char frame[] = "data: reload\n\n";
	printf("[liveside] notifying %d client(s)\n", g_nclients);
	broadcast(frame, sizeof(frame) - 1);
}

/**
 * @brief Periodically send SSE comments to keep idle connections alive.
 * @param arg Unused.
 * @return 0 when g_running becomes false.
 */
static int
ping_thread(void *arg)
{
	(void)arg;
	static const char ping[] = ": keep-alive\n\n";
	while (g_running) {
		usleep_ms(30000);
		if (g_nclients > 0)
			broadcast(ping, sizeof(ping) - 1);
	}
	return 0;
}

/** @}
 * @name Minimal HTTP server
 *
 * Handles only the endpoints required by liveside: /livereload, /liveside.js,
 * /, and 404 responses for everything else.
 * @{
 */

/** JavaScript client served from /liveside.js.
 *
 * Generated from client/liveside.js by the Makefile. The generated include is
 * deliberately not committed.
 */
static const char CLIENT_JS[] =
#include "client/liveside.js.inc"
    ;

/**
 * @brief Handle /livereload by upgrading the response to an SSE stream.
 * @param fd Connected client socket.
 */
static void
handle_livereload(SOCKET fd)
{
	static const char headers[] =
	    "HTTP/1.1 200 OK\r\n"
	    "Content-Type: text/event-stream\r\n"
	    "Cache-Control: no-cache\r\n"
	    "Connection: keep-alive\r\n"
	    "Access-Control-Allow-Origin: *\r\n"
	    "\r\n"
	    ": connected\n\n";
	if (frankensocket_send(fd, headers, sizeof(headers) - 1) < 0) {
		frankensocket_close(fd);
		return;
	}
	add_client(fd);
	printf("[liveside] client connected (%d total)\n", g_nclients);
	/* This thread's only remaining job is to notice when the browser
	 * goes away; broadcast()/ping_thread() do all the writing. */
	char buf[64];
	while (g_running) {
		long n = frankensocket_recv(fd, buf, sizeof(buf));
		if (n <= 0)
			break;
	}
	remove_client(fd);
}

/**
 * @brief Serve the embedded JavaScript client.
 * @param fd Connected client socket.
 */
static void
handle_reload_js(SOCKET fd)
{
	char header[256];
	int hlen = snprintf(header, sizeof(header),
	                    "HTTP/1.1 200 OK\r\n"
	                    "Content-Type: application/javascript; charset=utf-8\r\n"
	                    "Cache-Control: no-store\r\n"
	                    "Access-Control-Allow-Origin: *\r\n"
	                    "Content-Length: %zu\r\n"
	                    "Connection: close\r\n"
	                    "\r\n",
	                    sizeof(CLIENT_JS) - 1);
	frankensocket_send(fd, header, (size_t)hlen);
	frankensocket_send(fd, CLIENT_JS, sizeof(CLIENT_JS) - 1);
	frankensocket_close(fd);
}

/**
 * @brief Serve a small plaintext status response.
 * @param fd Connected client socket.
 */
static void
handle_root(SOCKET fd)
{
	char body[256];
	int blen = snprintf(body, sizeof(body),
	                    "liveside\nwatching: %s\nSSE endpoint: /livereload\n"
	                    "client script: /liveside.js\n", g_watch_dir);
	char header[256];
	int hlen = snprintf(header, sizeof(header),
	                    "HTTP/1.1 200 OK\r\n"
	                    "Content-Type: text/plain\r\n"
	                    "Content-Length: %d\r\n"
	                    "Connection: close\r\n"
	                    "\r\n", blen);
	frankensocket_send(fd, header, (size_t)hlen);
	frankensocket_send(fd, body, (size_t)blen);
	frankensocket_close(fd);
}

/**
 * @brief Send a 404 response for unsupported paths.
 * @param fd Connected client socket.
 */
static void
handle_not_found(SOCKET fd)
{
	static const char resp[] =
	    "HTTP/1.1 404 Not Found\r\n"
	    "Content-Length: 0\r\n"
	    "Connection: close\r\n"
	    "\r\n";
	frankensocket_send(fd, resp, sizeof(resp) - 1);
	frankensocket_close(fd);
}

/**
 * @brief Parse one HTTP request and dispatch it to the matching handler.
 * @param arg Connected socket cast through intptr_t.
 * @return 0 after the connection is handled.
 */
static int
connection_thread(void *arg)
{
	SOCKET fd = (SOCKET)(uintptr_t)arg;
	char buf[4096];
	long n = frankensocket_recv(fd, buf, sizeof(buf) - 1);
	if (n <= 0) {
		frankensocket_close(fd);
		return 0;
	}
	buf[n] = '\0';
	char method[16] = { 0 };
	char path[512] = { 0 };
	sscanf(buf, "%15s %511s", method, path);
	if (strcmp(path, "/livereload") == 0)
		handle_livereload(fd);
	else if (strcmp(path, "/liveside.js") == 0)
		handle_reload_js(fd);
	else if (strcmp(path, "/") == 0)
		handle_root(fd);
	else
		handle_not_found(fd);
	return 0;
}

static SOCKET g_listen_fd = INVALID_SOCKET;

/**
 * @brief Create, bind, and listen on the liveside HTTP socket.
 * @return Listening socket, or INVALID_SOCKET on failure.
 */
static SOCKET
start_http_server(void)
{
	SOCKET srv = socket(AF_INET, SOCK_STREAM, 0);
	if (srv == INVALID_SOCKET) {
		frankensocket_perror("socket");
		return INVALID_SOCKET;
	}
	int yes = 1;
	setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, (const char *)&yes, sizeof(yes));
	struct sockaddr_in addr = { 0 };
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = INADDR_ANY;
	addr.sin_port = htons(g_port);
	if (bind(srv, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
		frankensocket_perror("bind");
		frankensocket_close(srv);
		return INVALID_SOCKET;
	}
	if (listen(srv, 32) < 0) {
		frankensocket_perror("listen");
		frankensocket_close(srv);
		return INVALID_SOCKET;
	}
	return srv;
}

/** @}
 * @name Change handling and program entry point
 *
 * Runs the watcher loop, optional build command, reload cooldown, signal
 * handling, CLI parsing, and process startup/shutdown.
 * @{
 */

/** Minimum time between two reload broadcasts. Root-caused the double-fire
 * this was originally added to paper over: it was NOTE_ATTRIB (see
 * kq_add_path) picking up an atime bump from something merely reading a
 * just-written file (e.g. Spotlight/mdworker indexing it), not a race in
 * write detection or our own -c build's writes -- dropping NOTE_ATTRIB and
 * watch_settle() together were enough on their own (confirmed: zero
 * duplicate reloads with this cooldown effectively disabled). This stays
 * on as a cheap safety net for whatever's left uncaught (inotify's
 * IN_ATTRIB has the same class of issue; the poll fallback has none of
 * this, but costs nothing to also guard), kept short enough that it
 * shouldn't ever visibly swallow a genuine rapid second edit. */
#define RELOAD_COOLDOWN_MS 150

static long long g_last_broadcast_ms = 0;
static bool g_have_last_broadcast = false;

/**
 * @brief React to one coalesced file-system change.
 *
 * Runs the optional build command, enforces the reload cooldown, and notifies
 * connected browsers only when the build succeeds.
 */
static void
on_change(void)
{
	printf("[liveside] change detected\n");
	if (g_build_cmd) {
		int status = system(g_build_cmd);
		if (status != 0) {
			fprintf(stderr,
			        "[liveside] build command failed (status %d), "
			        "not reloading\n", status);
			return;
		}
	}
	if (g_have_last_broadcast &&
	    (now_ms() - g_last_broadcast_ms) < RELOAD_COOLDOWN_MS) {
		printf("[liveside] reload sent recently, skipping duplicate\n");
		return;
	}
	broadcast_reload();
	g_last_broadcast_ms = now_ms();
	g_have_last_broadcast = true;
}

/**
 * @brief Worker thread that waits for file changes and triggers reloads.
 * @param arg Unused.
 * @return 0 when the watcher stops.
 */
static int
watcher_loop(void *arg)
{
	(void)arg;
	watcher_t *w = watch_open(g_watch_dir);
	if (!w) {
		fprintf(stderr, "[liveside] failed to initialize file watcher\n");
		return 0;
	}
	while (g_running) {
		if (!watch_wait(w))
			break; /* fatal watcher error */
		if (!g_running)
			break;
		on_change();
		/* If -c runs a build that writes into the watched tree itself
		 * (e.g. regenerating .html from .html.in in place, as
		 * saikrupagas.com's `make dev-all` does), those writes are
		 * filesystem events too. Without this, they'd be picked up as
		 * a second "change" on the next watch_wait() -- triggering a
		 * second, spurious rebuild-and-reload for every real one. */
		watch_settle(w);
	}
	watch_close(w);
	return 0;
}

/**
 * @brief Signal handler that requests graceful shutdown.
 * @param sig Signal number, ignored.
 */
static void
handle_sigint(int sig)
{
	(void)sig;
	g_running = 0;
}

/**
 * @brief Print command-line usage.
 * @param prog Program name to show in the usage line.
 */
static void
usage(const char *prog)
{
	fprintf(stderr,
	        "usage: %s [-p port] [-d watch-dir] [-c build-cmd] [-i poll-ms]\n"
	        "  -p port       HTTP/SSE port to serve on (default: 8081)\n"
	        "  -d watch-dir  Directory to watch recursively (default: .)\n"
	        "  -c build-cmd  Shell command to run before notifying clients\n"
	        "  -i poll-ms    Polling interval in ms (only used as a fallback\n"
	        "                on platforms without kqueue/inotify; default: 300)\n",
	        prog);
}

/**
 * @brief Program entry point.
 * @param argc Command-line argument count.
 * @param argv Command-line argument vector.
 * @return Process exit status.
 */
int
main(int argc, char **argv)
{
	if (frankensocket_startup() != 0)
		return 1;
	if (mtx_init(&g_clients_mu, mtx_plain) != thrd_success) {
		fprintf(stderr, "[liveside] mutex initialization failed\n");
		frankensocket_cleanup();
		return 1;
	}
	int opt;
	while ((opt = getopt(argc, argv, "p:d:c:i:h")) != -1) {
		switch (opt) {
		case 'p':
			g_port = (uint16_t)atoi(optarg);
			break;
		case 'd':
			g_watch_dir = optarg;
			break;
		case 'c':
			g_build_cmd = optarg;
			break;
		case 'i':
			g_poll_ms = atoi(optarg);
			break;
		case 'h':
		default:
			usage(argv[0]);
			return opt == 'h' ? 0 : 1;
		}
	}
	ignore_init(&g_ignore, g_watch_dir);
	signal(SIGINT, handle_sigint);
	signal(SIGTERM, handle_sigint);
	frankensocket_ignore_sigpipe();
	printf("[liveside] watching '%s'\n", g_watch_dir);
	printf("[liveside] SSE endpoint: http://localhost:%d/livereload\n",
	       g_port);
	printf("[liveside] client script: http://localhost:%d/liveside.js\n",
	       g_port);
	if (g_build_cmd)
		printf("[liveside] build command: %s\n", g_build_cmd);
	g_listen_fd = start_http_server();
	if (g_listen_fd == INVALID_SOCKET)
		return 1;
	thrd_t watcher, pinger;
	if (thrd_create(&watcher, watcher_loop, NULL) == thrd_success)
		thrd_detach(watcher);
	if (thrd_create(&pinger, ping_thread, NULL) == thrd_success)
		thrd_detach(pinger);
	while (g_running) {
		/* accept() blocking indefinitely can't be woken up reliably from
		 * a signal handler (shutdown()/close() on a *listening* socket
		 * doesn't unblock a pending accept() on macOS/BSD), so poll with
		 * a short timeout instead and just recheck g_running each time
		 * it expires. */
		struct pollfd pfd = { .fd = g_listen_fd, .events = POLLIN };
		int pr = poll(&pfd, 1, 500);
		if (pr <= 0)
			continue;
		SOCKET fd = accept(g_listen_fd, NULL, NULL);
		if (fd == INVALID_SOCKET)
			continue;
		int yes = 1;
		setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const char *)&yes, sizeof(yes));
		thrd_t conn;
		if (thrd_create(&conn, connection_thread, (void *)(uintptr_t)fd) == thrd_success)
			thrd_detach(conn);
		else
			frankensocket_close(fd);
	}
	frankensocket_close(g_listen_fd);
	printf("\n[liveside] shutting down\n");
	frankensocket_cleanup();
	return 0;
}

/** @} */
