// Copyright 2024-2025 XMOS LIMITED.
// This Software is subject to the terms of the XMOS Public Licence: Version 1.

#include "utils.hpp"

#if defined(__linux__)
#include <unistd.h>       // readlink
#include <sys/ioctl.h>    // ioctl
#include <linux/limits.h> // PATH_MAX

#elif defined(__APPLE__)
#include <unistd.h>      // readlink
#include <mach-o/dyld.h> // _NSGetExecutablePath
#include <sys/ioctl.h>   // ioctl

#elif defined(_WIN32)
#include <Windows.h> // GetModuleFileNameA
#include <direct.h>  // _getcwd
#define getcwd _getcwd
#define PATH_MAX 1000
#else
#error "Unknown Operating System"
#endif

using namespace std;

size_t get_term_width()
{
#if (defined(__linux__) || defined(__APPLE__))
    struct winsize w;
    ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
    // running on jenkins returns 0
    if (w.ws_col == 0)
    {
        return 120;
    }
    else
    {
        return w.ws_col;
    }
#elif defined(_WIN32)
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
    return csbi.srWindow.Right - csbi.srWindow.Left + 1;
#else
#error "Unsupported operating system"
#endif
}
