/* runtime.c -- the thin libc-level pieces of Watcom's runtime and of MACT386.LIB (util_lib,
 * file_lib) that the game expects. Kept in C for now because some are variadic (Error);
 * they get translated to Rust together with the rest of the C in the next step. */
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <ctype.h>
#include <fcntl.h>
#include <unistd.h>
#include <glob.h>
#include <sys/stat.h>

extern int32_t _argc;
extern char **_argv;

/* ---------- Watcom libc extras ---------- */
char *strupr(char *s) { char *p = s; for (; *p; p++) *p = (char)toupper((unsigned char)*p); return s; }
char *strlwr(char *s) { char *p = s; for (; *p; p++) *p = (char)tolower((unsigned char)*p); return s; }
static char *radix_str(int64_t v, char *buf, int radix)
{
	char tmp[72]; int i = 0, neg = 0; uint64_t u;
	if (radix == 10 && v < 0) { neg = 1; u = (uint64_t)(-v); } else u = (uint64_t)(uint32_t)v;
	do { int d = (int)(u % radix); tmp[i++] = (char)(d < 10 ? '0' + d : 'a' + d - 10); u /= radix; } while (u);
	if (neg) tmp[i++] = '-';
	for (int j = 0; j < i; j++) buf[j] = tmp[i - 1 - j];
	buf[i] = 0; return buf;
}
char *ltoa(int32_t v, char *buf, int radix) { return radix_str(v, buf, radix); }
char *itoa(int v, char *buf, int radix) { return radix_str(v, buf, radix); }
int32_t filelength(int fd) { struct stat st; return fstat(fd, &st) ? -1 : (int32_t)st.st_size; }
int getch(void) { extern char KB_Getch(void); extern int32_t KB_KeyWaiting(void); while (!KB_KeyWaiting()) ; return (unsigned char)KB_Getch(); }
int kbhit(void) { extern int32_t KB_KeyWaiting(void); return KB_KeyWaiting(); }

/* _dos_findfirst/_dos_findnext over glob(3), case-insensitive like DOS */
/* struct find_t is declared in compat.h (force-included) */
typedef struct { glob_t g; size_t i; } findstate;
static unsigned fill(struct find_t *f)
{
	findstate *s = (findstate *)f->_handle;
	while (s->i < s->g.gl_pathc) {
		const char *p = s->g.gl_pathv[s->i++], *base = strrchr(p, '/');
		struct stat st;
		base = base ? base + 1 : p;
		if (stat(p, &st)) continue;
		strncpy(f->name, base, sizeof(f->name) - 1); f->name[sizeof(f->name) - 1] = 0;
		f->size = (uint32_t)st.st_size; f->attrib = S_ISDIR(st.st_mode) ? 0x10 : 0;
		return 0;
	}
	globfree(&s->g); free(s); f->_handle = NULL;
	return 1;
}
unsigned _dos_findfirst(const char *pattern, unsigned attrib, struct find_t *f)
{
	char pat[512]; size_t j = 0;
	(void)attrib;
	for (const char *c = pattern; *c && j < sizeof(pat) - 5; c++) {   /* *.MAP -> *.[Mm][Aa][Pp] */
		if (isalpha((unsigned char)*c)) { pat[j++] = '['; pat[j++] = (char)toupper((unsigned char)*c); pat[j++] = (char)tolower((unsigned char)*c); pat[j++] = ']'; }
		else pat[j++] = (*c == '\\') ? '/' : *c;
	}
	pat[j] = 0;
	findstate *s = calloc(1, sizeof(*s));
	if (glob(pat, 0, NULL, &s->g) != 0) { free(s); f->_handle = NULL; return 1; }
	f->_handle = s;
	return fill(f);
}
unsigned _dos_findnext(struct find_t *f) { return f->_handle ? fill(f) : 1; }

/* ---------- MACT util_lib ---------- */
static void (*shutdownfunc)(void) = NULL;
void RegisterShutdownFunction(void (*f)(void)) { shutdownfunc = f; }
void Error(char *fmt, ...)
{
	va_list ap;
	if (shutdownfunc) { void (*f)(void) = shutdownfunc; shutdownfunc = NULL; f(); }
	va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap);
	fputc('\n', stderr);
	exit(1);
}
char CheckParm(char *check)
{
	for (int i = 1; i < _argc; i++) {
		char *a = _argv[i];
		if ((*a == '-' || *a == '/') && !strcasecmp(a + 1, check)) return (char)i;
	}
	return 0;
}
void *SafeMalloc(int32_t size) { void *p = malloc(size > 0 ? size : 1); if (!p) Error("SafeMalloc: out of memory (%d bytes)", size); return p; }
int32_t SafeMallocSize(void *p) { (void)p; return 0; }
void SafeFree(void *p) { free(p); }
void SafeRealloc(void **p, int32_t n) { void *q = realloc(*p, n > 0 ? n : 1); if (!q) Error("SafeRealloc: out of memory"); *p = q; }
int32_t ParseHex(char *hex) { return (int32_t)strtol(hex, NULL, 16); }
int32_t ParseNum(char *str) { return (int32_t)strtol(str, NULL, 0); }
int16_t IntelShort(int16_t l) { return l; }   /* host is little-endian like the 486 */
int32_t IntelLong(int32_t l) { return l; }
int16_t MotoShort(int16_t l) { return (int16_t)(((uint16_t)l >> 8) | ((uint16_t)l << 8)); }
int32_t MotoLong(int32_t l) { uint32_t u = (uint32_t)l; return (int32_t)((u >> 24) | ((u >> 8) & 0xff00) | ((u << 8) & 0xff0000) | (u << 24)); }

/* MACT's distance approximations (as in Apogee's Rise of the Triad util code) */
int32_t FindDistance2D(int32_t dx, int32_t dy)
{
	int32_t t;
	dx = abs(dx); dy = abs(dy);
	if (dx < dy) { t = dx; dx = dy; dy = t; }
	t = dy + (dy >> 1);
	return dx - (dx >> 5) - (dx >> 7) + (t >> 2) + (t >> 6);
}
int32_t FindDistance3D(int32_t dx, int32_t dy, int32_t dz)
{
	int32_t t;
	dx = abs(dx); dy = abs(dy); dz = abs(dz);
	if (dx < dy) { t = dx; dx = dy; dy = t; }
	if (dx < dz) { t = dx; dx = dz; dz = t; }
	t = dy + dz;
	return dx - (dx >> 4) + (t >> 2) + (t >> 3);
}
int32_t sgn(int32_t x) { return (x > 0) - (x < 0); }
int32_t Z_AvailHeap(void) { return 64 << 20; }   /* DOS free-memory query; anything >= 2.8 MB passes */

/* ---------- MACT file_lib ---------- */
int32_t SafeOpenRead(const char *fn, int32_t type) { int h = open(fn, O_RDONLY); (void)type; if (h < 0) Error("SafeOpenRead: cannot open %s", fn); return h; }
int32_t SafeOpenWrite(const char *fn, int32_t type) { int h = open(fn, O_WRONLY | O_CREAT | O_TRUNC, 0644); (void)type; if (h < 0) Error("SafeOpenWrite: cannot open %s", fn); return h; }
int32_t SafeOpenAppend(const char *fn, int32_t type) { int h = open(fn, O_WRONLY | O_CREAT | O_APPEND, 0644); (void)type; if (h < 0) Error("SafeOpenAppend: cannot open %s", fn); return h; }
void SafeClose(int32_t h) { close(h); }
int SafeFileExists(const char *fn) { return access(fn, F_OK) == 0; }
int32_t SafeFileLength(int32_t h) { return filelength(h); }
void SafeRead(int32_t h, void *buf, int32_t n) { if (read(h, buf, n) != n) Error("SafeRead: file read error"); }
void SafeWrite(int32_t h, void *buf, int32_t n) { if (write(h, buf, n) != n) Error("SafeWrite: file write error"); }
