/* GaspardOS i686 backend for newlib's reentrant syscall covers. */
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <reent.h>
#include <stdint.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/times.h>
#include <sys/time.h>
#include <unistd.h>
#include <utime.h>
#ifdef GASPARDOS_NEWLIB_X64
#include "x64/transport.h"
_Static_assert(sizeof(void *) == 8 && sizeof(long) == 8 && sizeof(off_t) == 8,
               "newlib x64 requires LP64 including off_t");
#else
#include "GaspardOSApps.h"
#endif

/* newlib's _xxx_r covers copy this transport errno into struct _reent. */
#undef errno
extern int errno;

#ifndef GASPARDOS_HEAP_SIZE
#define GASPARDOS_HEAP_SIZE (16u * 1024u * 1024u)
#endif

static int fail(int error)
{
    errno = error;
    __errno_r(_REENT) = error;
    return -1;
}

/* Per-image state: this port deliberately builds newlib without threads. */
static char current_directory[4096] = "/IDEDISK0/";
static intptr_t result(intptr_t value);
static int refresh_directory(void)
{
#ifdef GASPARDOS_NEWLIB_X64
    intptr_t rc = GO64_syscall6(153, (uintptr_t)current_directory,
                              sizeof(current_directory), 0, 0, 0, 0);
    if (rc < 0 && rc != -38) return (int)result(rc);
#endif
    return 0;
}
static mode_t creation_mask;
static int console_fd_flags[3];

static int absolute_path(const char *src, char out[4096])
{
    char joined[4096];
    size_t base, length, used = 1;
    if (!src) return fail(EFAULT);
    if (!*src) return fail(ENOENT);
    if (refresh_directory()) return -1;
    base = (*src == '/' || *src == '\\') ? 0 : strlen(current_directory);
    length = strlen(src);
    if (base + length >= sizeof(joined)) return fail(ENAMETOOLONG);
    memcpy(joined, current_directory, base);
    memcpy(joined + base, src, length + 1);
    out[0] = '/';
    const char *p = joined;
    while (*p) {
        while (*p == '/' || *p == '\\') ++p;
        const char *part = p;
        while (*p && *p != '/' && *p != '\\') ++p;
        size_t count = (size_t)(p - part);
        if (!count || (count == 1 && part[0] == '.')) continue;
        if (count == 2 && part[0] == '.' && part[1] == '.') {
            if (used > 1) {
                --used;
                while (used > 1 && out[used - 1] != '/') --used;
            }
            continue;
        }
        if (used + count + 1 >= 4096) return fail(ENAMETOOLONG);
        memcpy(out + used, part, count);
        used += count;
        out[used++] = '/';
    }
    /* Kernel mount roots require their trailing separator. */
    unsigned separators = 0;
    for (size_t i = 1; i < used; ++i) if (out[i] == '/') ++separators;
    if (separators > 1) --used;
    out[used] = 0;
    return 0;
}

/* The kernel uses Linux error numbers; newlib does not. */
static intptr_t result(intptr_t value)
{
    if (value >= 0) return value;
    switch (-value) {
    case GO_ENAMETOOLONG: return fail(ENAMETOOLONG);
    case GO_ENOSYS: return fail(ENOSYS);
    case GO_ENOTEMPTY: return fail(ENOTEMPTY);
    case GO_EPROTONOSUPPORT: return fail(EPROTONOSUPPORT);
    case GO_ESOCKTNOSUPPORT: return fail(EPROTONOSUPPORT);
    case GO_EAFNOSUPPORT: return fail(EAFNOSUPPORT);
    case GO_EADDRINUSE: return fail(EADDRINUSE);
    case GO_ENETRESET: return fail(ENETRESET);
    case GO_ENOTCONN: return fail(ENOTCONN);
    default: return fail(-value);
    }
}

/* Strict UTF-8; normalize relative paths before crossing the kernel ABI. */
static int path32(const char *src, wchar_t dst[4096])
{
    char absolute[4096];
    size_t n = 0;
    if (absolute_path(src, absolute)) return -1;
    src = absolute;
    while (*src) {
        uint32_t c = (unsigned char)*src++, min = 0;
        unsigned more = 0;
        if (c >= 0xc2 && c <= 0xdf) { c &= 31; more = 1; min = 0x80; }
        else if (c >= 0xe0 && c <= 0xef) { c &= 15; more = 2; min = 0x800; }
        else if (c >= 0xf0 && c <= 0xf4) { c &= 7; more = 3; min = 0x10000; }
        else if (c >= 0x80) return fail(EILSEQ);
        while (more--) {
            unsigned next = (unsigned char)*src;
            if ((next & 0xc0) != 0x80) return fail(EILSEQ);
            ++src; c = (c << 6) | (next & 63);
        }
        if (c < min || c > 0x10ffff || (c >= 0xd800 && c <= 0xdfff))
            return fail(EILSEQ);
        if (n == 4095) return fail(ENAMETOOLONG);
        dst[n++] = c == '/' ? '\\' : c;
    }
    dst[n] = 0;
    return 0;
}

int _open(const char *path, int flags, ...)
{
    wchar_t wide[4096];
    int known = O_ACCMODE | O_CREAT | O_EXCL | O_TRUNC | O_APPEND;
    if ((flags & ~known) || (flags & O_ACCMODE) == O_ACCMODE) return fail(EINVAL);
    if (path32(path, wide)) return -1;
    unsigned native = flags & O_ACCMODE;
    if (flags & O_CREAT) native |= GO_O_CREAT;
    if (flags & O_EXCL) native |= GO_O_EXCL;
    if (flags & O_TRUNC) native |= GO_O_TRUNC;
    if (flags & O_APPEND) native |= GO_O_APPEND;
    return result(GO_FS_Open(wide, native));
}

int _close(int fd)
{
    /* Console descriptors are permanent and cannot be redirected. */
    if (fd >= 0 && fd <= 2) return 0;
    return result(GO_FS_Close(fd));
}

int _write(int fd, const void *buffer, size_t count)
{
    if (count > INT_MAX) return fail(EINVAL);
    if (count && !buffer) return fail(EFAULT);
    if (fd == 1 || fd == 2) {
        const unsigned char *bytes = buffer;
        for (size_t i = 0; i < count; ++i) GO_PrintChar(bytes[i]);
        return (int)count;
    }
    if (fd == 0) return fail(EBADF);
    return result(GO_FS_Write(fd, buffer, count));
}

int _read(int fd, void *buffer, size_t count)
{
    if (count > INT_MAX) return fail(EINVAL);
    if (count && !buffer) return fail(EFAULT);
    /* The keyboard snapshot syscall cannot implement a consuming byte stream. */
    if (fd == 0) return count ? fail(ENOSYS) : 0;
    if (fd == 1 || fd == 2) return fail(EBADF);
    return result(GO_FS_Read(fd, buffer, count));
}

off_t _lseek(int fd, off_t offset, int origin)
{
    if (fd >= 0 && fd <= 2) return fail(ESPIPE);
#ifndef GASPARDOS_NEWLIB_X64
    if (offset < INT32_MIN || offset > INT32_MAX) return fail(EOVERFLOW);
#endif
    return result(GO_FS_Seek(fd, offset, origin));
}

static int metadata(const GO_FSInfo *info, struct stat *out)
{
    if (info->bytes > (uint64_t)(sizeof(off_t) == 8 ? INT64_MAX : INT32_MAX)) return fail(EOVERFLOW);
    memset(out, 0, sizeof(*out));
    out->st_ino = info->id;
    out->st_mode = (info->is_directory ? S_IFDIR : S_IFREG) | 0777;
    out->st_nlink = 1;
    out->st_size = info->bytes;
    return 0;
}

int _fstat(int fd, struct stat *out)
{
    GO_FSInfo info;
    if (!out) return fail(EFAULT);
    if (fd >= 0 && fd <= 2) {
        memset(out, 0, sizeof(*out));
        out->st_mode = S_IFCHR | 0666; out->st_nlink = 1;
        return 0;
    }
    if (result(GO_FS_FStat(fd, &info)) < 0) return -1;
    return metadata(&info, out);
}

int _stat(const char *path, struct stat *out)
{
    wchar_t wide[4096]; GO_FSInfo info;
    if (!out) return fail(EFAULT);
    if (path32(path, wide) || result(GO_FS_Stat(wide, &info)) < 0) return -1;
    return metadata(&info, out);
}

int _isatty(int fd)
{
    if (fd >= 0 && fd <= 2) return 1;
    struct stat st;
    if (_fstat(fd, &st)) return 0;
    errno = ENOTTY; return 0;
}

int _unlink(const char *path)
{
    wchar_t wide[4096];
    if (path32(path, wide)) return -1;
    return result(GO_FS_Unlink(wide));
}

int _mkdir(const char *path, mode_t mode)
{
    wchar_t wide[4096]; (void)mode;
    if (path32(path, wide)) return -1;
    return result(GO_FS_Mkdir(wide));
}

int mkdir(const char *path, mode_t mode)
{
    return _mkdir_r(_REENT, path, mode);
}

int _rmdir(const char *path)
{
    wchar_t wide[4096];
    if (path32(path, wide)) { *__errno() = errno; return -1; }
    int rc = result(GO_FS_Rmdir(wide));
    if (rc < 0) *__errno() = errno;
    return rc;
}

int rmdir(const char *path) { return _rmdir(path); }

mode_t _umask(mode_t mask)
{
    mode_t previous = creation_mask;
    creation_mask = mask & 0777;
    return previous;
}
mode_t umask(mode_t mask) { return _umask(mask); }

/* GaspardFS2 has neither permission enforcement nor symbolic links. */
int _chmod(const char *path, mode_t mode)
{
    struct stat st;
    (void)mode;
    return _stat(path, &st);
}
int chmod(const char *path, mode_t mode) { return _chmod(path, mode); }

/* No ownership or timestamp fields in the current GaspardFS2 ABI.
 * Accept metadata changes permissively after a real kernel existence check.
 * times == NULL (current time) is accepted without requiring a clock. */
int _utime(const char *path, const struct utimbuf *times)
{
    struct stat st;
    (void)times;
    return _stat(path, &st);
}
int utime(const char *path, const struct utimbuf *times)
{
    return _utime(path, times);
}
int _chown(const char *path, uid_t owner, gid_t group)
{
    struct stat st;
    (void)owner;
    (void)group;
    return _stat(path, &st);
}
int chown(const char *path, uid_t owner, gid_t group)
{
    return _chown(path, owner, group);
}
int _lstat(const char *path, struct stat *st) { return _stat(path, st); }
int lstat(const char *path, struct stat *st) { return _lstat(path, st); }
int _access(const char *path, int mode)
{
    struct stat st;
    if (mode & ~(R_OK | W_OK | X_OK)) return fail(EINVAL);
    return _stat(path, &st);
}
int access(const char *path, int mode) { return _access(path, mode); }

char *_getcwd(char *buffer, size_t size)
{
    if (refresh_directory()) return NULL;
    size_t needed = strlen(current_directory) + 1;
    if (!buffer) {
        if (!size) size = needed;
        if (size < needed) { fail(ERANGE); return NULL; }
        buffer = malloc(size);
        if (!buffer) { fail(ENOMEM); return NULL; }
    } else if (!size || size < needed) {
        fail(size ? ERANGE : EINVAL);
        return NULL;
    }
    memcpy(buffer, current_directory, needed);
    return buffer;
}
char *getcwd(char *buffer, size_t size) { return _getcwd(buffer, size); }
int chdir(const char *path)
{
#ifdef GASPARDOS_NEWLIB_X64
    intptr_t rc = GO64_syscall6(154, (uintptr_t)path, 0, 0, 0, 0, 0);
    if (rc != -38) return rc < 0 ? (int)result(rc) : refresh_directory();
#endif
    struct stat st;
    char absolute[4096];
    if (_stat(path, &st)) return -1;
    if (!S_ISDIR(st.st_mode)) return fail(ENOTDIR);
    if (absolute_path(path, absolute)) return -1;
    size_t n = strlen(absolute);
    if (absolute[n - 1] != '/') {
        if (n + 1 >= sizeof(absolute)) return fail(ENAMETOOLONG);
        absolute[n++] = '/'; absolute[n] = 0;
    }
    memcpy(current_directory, absolute, n + 1);
    return 0;
}

long sysconf(int name)
{
#ifdef _SC_PAGESIZE
    if (name == _SC_PAGESIZE) return 4096;
#endif
#ifdef _SC_PAGE_SIZE
    if (name == _SC_PAGE_SIZE) return 4096;
#endif
#ifdef _SC_OPEN_MAX
    if (name == _SC_OPEN_MAX) return 67; /* 64 kernel slots + console. */
#endif
#ifdef _SC_NPROCESSORS_ONLN
    if (name == _SC_NPROCESSORS_ONLN) return 1;
#endif
#ifdef _SC_NPROCESSORS_CONF
    if (name == _SC_NPROCESSORS_CONF) return 1;
#endif
#ifdef _SC_JOB_CONTROL
    if (name == _SC_JOB_CONTROL) return -1;
#endif
#ifdef _SC_SAVED_IDS
    if (name == _SC_SAVED_IDS) return -1;
#endif
#ifdef _SC_CLK_TCK
    if (name == _SC_CLK_TCK) return fail(ENOSYS);
#endif
    return fail(EINVAL);
}

int _rename(const char *oldpath, const char *newpath)
{
    wchar_t oldwide[4096], newwide[4096];
    if (path32(oldpath, oldwide) || path32(newpath, newwide)) return -1;
    return result(GO_FS_Rename(oldwide, newwide));
}

int _fcntl(int fd, int cmd, ...)
{
    int arg = 0, native_cmd;
    switch (cmd) {
    case F_GETFD: native_cmd = 0; break;
    case F_SETFD: native_cmd = 1; break;
    case F_GETFL: native_cmd = 2; break;
    case F_SETFL: native_cmd = 3; break;
    default: {
        struct stat st;
        if (_fstat(fd, &st)) return -1;
        return fail(ENOSYS);
    }
    }
    if (cmd == F_SETFD || cmd == F_SETFL) {
        va_list ap;
        va_start(ap, cmd); arg = va_arg(ap, int); va_end(ap);
    }
    if (fd >= 0 && fd <= 2) {
        if (cmd == F_GETFD) return console_fd_flags[fd];
        if (cmd == F_SETFD) { console_fd_flags[fd] = arg & FD_CLOEXEC; return 0; }
        if (cmd == F_GETFL) return fd ? O_WRONLY : O_RDONLY;
        return 0; /* Console writes are already synchronous. */
    }
    if (cmd == F_SETFL) arg = (arg & O_APPEND) ? GO_O_APPEND : 0;
    int rc = result(GO_FS_Fcntl(fd, native_cmd, arg));
    if (rc < 0 || cmd != F_GETFL) return rc;
    return (rc & GO_O_ACCMODE) | ((rc & GO_O_APPEND) ? O_APPEND : 0);
}

/* One contiguous arena per application image; never call newlib malloc here. */
void *_sbrk(ptrdiff_t increment)
{
    static unsigned char *arena;
    static size_t used;
    if (!arena) {
        arena = GO_Alloc(GASPARDOS_HEAP_SIZE);
        if (!arena) { errno = ENOMEM; return (void *)-1; }
    }
    if ((increment >= 0 && (size_t)increment > GASPARDOS_HEAP_SIZE - used) ||
        (increment < 0 && (size_t)(-(increment + 1)) + 1 > used)) {
        errno = ENOMEM; return (void *)-1;
    }
    void *previous = arena + used;
    used += increment;
    return previous;
}

void _exit(int status) { (void)status; GO_Exit(); }
/* No process identity, fork, signals, or clock ABI is currently exposed. */
int _getpid(void) { return fail(ENOSYS); }
int _kill(int pid, int sig) { (void)pid; (void)sig; return fail(ENOSYS); }
int _fork(void) { return fail(ENOSYS); }
int _execve(const char *p, char *const a[], char *const e[])
{ (void)p; (void)a; (void)e; return fail(ENOSYS); }
int _wait(int *status) { (void)status; return fail(ECHILD); }
int _link(const char *a, const char *b)
{
    struct stat st;
    wchar_t wide[4096];
    if (_stat(a, &st) || path32(b, wide)) return -1;
    /* The on-disk format cannot represent hard links. */
    return fail(ENOTSUP);
}
int _getentropy(void *buf, size_t count)
{ (void)buf; (void)count; return fail(ENOSYS); }
clock_t _times(struct tms *t) { (void)t; return fail(ENOSYS); }
int _gettimeofday(struct timeval *tv, void *tz)
{ (void)tv; (void)tz; return fail(ENOSYS); }
