#include "common.h"

void msleep(int ms) {
#ifdef _WIN32
    Sleep(ms);
#else
    struct timespec ts;
    ts.tv_sec = ms / 1000;
    ts.tv_nsec = (long)(ms % 1000) * 1000000L;
    nanosleep(&ts, NULL);
#endif
}

void trim(char *s) {
    if (!s) return;
    char *p = s;
    while (*p && isspace((unsigned char)*p)) p++;
    if (p != s) memmove(s, p, strlen(p) + 1);
    size_t len = strlen(s);
    while (len && isspace((unsigned char)s[len - 1])) s[--len] = '\0';
}

void safe_strcpy(char *dst, const char *src, size_t n) {
    if (!dst || n == 0) return;
    if (!src) src = "";
    snprintf(dst, n, "%s", src);
}

int starts_with(const char *s, const char *prefix) {
    if (!s || !prefix) return 0;
    size_t n = strlen(prefix);
    return strncmp(s, prefix, n) == 0;
}

void format_time(char *out, size_t n, time_t t) {
    struct tm *tmv = localtime(&t);
    if (!tmv) {
        snprintf(out, n, "00:00:00");
        return;
    }
    strftime(out, n, "%H:%M:%S", tmv);
}

int file_exists(const char *path) {
    FILE *fp = fopen(path, "rb");
    if (!fp) return 0;
    fclose(fp);
    return 1;
}

screen_size_t get_screen_size(void) {
    screen_size_t s = {80, 25};
#ifdef _WIN32
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
    if (GetConsoleScreenBufferInfo(h, &csbi)) {
        s.width = csbi.srWindow.Right - csbi.srWindow.Left + 1;
        s.height = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
    }
#else
    struct winsize ws;
    if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0) {
        s.width = ws.ws_col;
        s.height = ws.ws_row;
    }
#endif
    if (s.width < 80) s.width = 80;
    if (s.height < 24) s.height = 24;
    return s;
}

int init_platform(void) {
#ifdef _WIN32
    WSADATA wsa;
    if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) return -1;
    HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
    DWORD mode = 0;
    if (GetConsoleMode(hout, &mode)) {
        mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
        SetConsoleMode(hout, mode);
    }
#endif
    return 0;
}

void shutdown_platform(void) {
#ifdef _WIN32
    WSACleanup();
#endif
}
