/*
 * VT-based curses replacement for OpenVMS 9.x
 * All public functions use vc_ prefix to avoid DECC$ name collisions.
 * The header maps standard curses names to vc_ via macros.
 */
#ifdef __VMS

#include "vms_curses.h"
#include <starlet.h>
#include <iodef.h>
#include <ssdef.h>
#include <descrip.h>
#include <lib$routines.h>

WINDOW *stdscr = NULL;
int LINES = 24;
int COLS = 80;

static unsigned short vms_chan = 0;
static chtype *screen_buf = NULL;
static int screen_buf_size = 0;
static int cur_screen_attr = -1;

#define MAX_PENDING 8
static WINDOW *pending_wins[MAX_PENDING];
static int n_pending = 0;

/* --- Terminal I/O --- */

static void vms_init_terminal(void)
{
    $DESCRIPTOR(tt, "SYS$INPUT");
    sys$assign(&tt, &vms_chan, 0, 0, 0);
}

static int vms_readch(void)
{
    char c;
    unsigned short iosb[4];
    int status = sys$qiow(0, vms_chan, IO$_READVBLK | IO$M_NOECHO | IO$M_NOFILTR,
                          iosb, 0, 0, &c, 1, 0, 0, 0, 0);
    if ((status & 1) == 0 || (iosb[0] & 1) == 0) return ERR;
    return (unsigned char)c;
}

static int vms_readch_timed(void)
{
    char c;
    unsigned short iosb[4];
    int status = sys$qiow(0, vms_chan, IO$_READVBLK | IO$M_NOECHO | IO$M_NOFILTR | IO$M_TIMED,
                          iosb, 0, 0, &c, 1, 0, 0, 0, 0);
    if (iosb[0] == SS$_TIMEOUT) return ERR;
    if ((status & 1) == 0 || (iosb[0] & 1) == 0) return ERR;
    return (unsigned char)c;
}

static void vms_write_raw(const char *buf, int len)
{
    unsigned short iosb[4];
    while (len > 0) {
        int chunk = len > 16384 ? 16384 : len;
        sys$qiow(0, vms_chan, IO$_WRITEVBLK | IO$M_NOFORMAT,
                 iosb, 0, 0, (char *)buf, chunk, 0, 0, 0, 0);
        buf += chunk;
        len -= chunk;
    }
}

static void vms_out(const char *s)
{
    int len = strlen(s);
    if (len > 0) vms_write_raw(s, len);
}

static void vms_flush(void)
{
}

static void vms_goto(int row, int col)
{
    char buf[24];
    sprintf(buf, "\033[%d;%dH", row + 1, col + 1);
    vms_out(buf);
}

static void vms_set_attr(int attr)
{
    if (attr == cur_screen_attr) return;
    vms_out("\033[0m");
    if (attr & A_BOLD)    vms_out("\033[1m");
    if (attr & A_BLINK)   vms_out("\033[5m");
    if (attr & A_REVERSE) vms_out("\033[7m");
    cur_screen_attr = attr;
}

/* --- Terminal size detection --- */

static void vms_detect_size(void)
{
    char buf[32];
    int n;

    vms_out("\0337");
    vms_out("\033[999;999H");
    vms_out("\033[6n");
    vms_flush();

    n = 0;
    for (;;) {
        int c = vms_readch();
        if (c == ERR) break;
        if (n < (int)sizeof(buf) - 1) buf[n++] = c;
        if (c == 'R') break;
    }
    buf[n] = 0;
    vms_out("\0338");

    int rows = 0, cols = 0;
    char *p = buf;
    while (*p && *p != '[') p++;
    if (*p == '[') {
        p++;
        rows = atoi(p);
        while (*p && *p != ';') p++;
        if (*p == ';') {
            p++;
            cols = atoi(p);
        }
    }
    if (rows > 0) LINES = rows;
    if (cols > 0) COLS = cols;
}

/* --- Window management --- */

static WINDOW *win_alloc(int h, int w, int y, int x)
{
    WINDOW *win = (WINDOW *)calloc(1, sizeof(WINDOW));
    if (!win) return NULL;
    win->maxy = h;
    win->maxx = w;
    win->begy = y;
    win->begx = x;
    win->attr = A_NORMAL;
    win->cells = (chtype *)calloc(h * w, sizeof(chtype));
    win->dirty = (int *)calloc(h, sizeof(int));
    if (!win->cells || !win->dirty) {
        free(win->cells);
        free(win->dirty);
        free(win);
        return NULL;
    }
    for (int i = 0; i < h * w; i++)
        win->cells[i] = ' ';
    for (int i = 0; i < h; i++)
        win->dirty[i] = 1;
    return win;
}

WINDOW *vc_initscr(void)
{
    vms_init_terminal();
    vms_detect_size();
    stdscr = win_alloc(LINES, COLS, 0, 0);
    screen_buf_size = LINES * COLS;
    screen_buf = (chtype *)calloc(screen_buf_size, sizeof(chtype));
    for (int i = 0; i < screen_buf_size; i++)
        screen_buf[i] = ' ';
    vms_out("\033[2J\033[H\033[?25l");
    vms_flush();
    cur_screen_attr = A_NORMAL;
    return stdscr;
}

int vc_endwin(void)
{
    vms_set_attr(A_NORMAL);
    vms_out("\033[?25h");
    vms_goto(LINES - 1, 0);
    vms_out("\n");
    vms_flush();
    if (stdscr) {
        free(stdscr->cells);
        free(stdscr->dirty);
        free(stdscr);
        stdscr = NULL;
    }
    free(screen_buf);
    screen_buf = NULL;
    if (vms_chan) {
        sys$dassgn(vms_chan);
        vms_chan = 0;
    }
    return OK;
}

WINDOW *vc_newwin(int h, int w, int y, int x)
{
    return win_alloc(h, w, y, x);
}

int vc_delwin(WINDOW *w)
{
    if (!w || w == stdscr) return ERR;
    free(w->cells);
    free(w->dirty);
    free(w);
    return OK;
}

/* --- Drawing --- */

int vc_wmove(WINDOW *w, int y, int x)
{
    if (!w) return ERR;
    if (y < 0 || y >= w->maxy || x < 0 || x >= w->maxx) return ERR;
    w->cury = y;
    w->curx = x;
    return OK;
}

static void win_scroll(WINDOW *w)
{
    int row_size = w->maxx;
    memmove(&w->cells[0], &w->cells[row_size],
            (w->maxy - 1) * row_size * sizeof(chtype));
    for (int x = 0; x < w->maxx; x++)
        w->cells[(w->maxy - 1) * w->maxx + x] = ' ';
    for (int i = 0; i < w->maxy; i++)
        w->dirty[i] = 1;
}

static void win_advance(WINDOW *w)
{
    w->curx++;
    if (w->curx >= w->maxx) {
        w->curx = 0;
        w->cury++;
        if (w->cury >= w->maxy) {
            if (w->flags & VWF_SCROLL) {
                win_scroll(w);
                w->cury = w->maxy - 1;
            } else {
                w->cury = w->maxy - 1;
                w->curx = w->maxx - 1;
            }
        }
    }
}

int vc_waddch(WINDOW *w, chtype ch)
{
    if (!w) return ERR;
    int c = ch & 0xFF;
    int a = (ch & ~0xFF) | (w->attr & ~0xFF);

    if (c == '\n') {
        w->curx = 0;
        w->cury++;
        if (w->cury >= w->maxy) {
            if (w->flags & VWF_SCROLL) {
                win_scroll(w);
                w->cury = w->maxy - 1;
            } else {
                w->cury = w->maxy - 1;
            }
        }
        return OK;
    }
    if (c == '\r') { w->curx = 0; return OK; }
    if (c == '\t') {
        int next = (w->curx + 8) & ~7;
        while (w->curx < next && w->curx < w->maxx)
            vc_waddch(w, ' ' | a);
        return OK;
    }

    if (w->cury >= 0 && w->cury < w->maxy &&
        w->curx >= 0 && w->curx < w->maxx) {
        chtype cell = (a & ~0xFF) | c;
        int idx = w->cury * w->maxx + w->curx;
        if (w->cells[idx] != cell) {
            w->cells[idx] = cell;
            w->dirty[w->cury] = 1;
        }
    }
    win_advance(w);
    return OK;
}

int vc_waddstr(WINDOW *w, const char *s)
{
    if (!w || !s) return ERR;
    while (*s)
        vc_waddch(w, (unsigned char)*s++);
    return OK;
}

int vc_wprintw(WINDOW *w, const char *fmt, ...)
{
    char buf[1024];
    va_list ap;
    va_start(ap, fmt);
    vsnprintf(buf, sizeof(buf), fmt, ap);
    va_end(ap);
    return vc_waddstr(w, buf);
}

int vc_mvwprintw(WINDOW *w, int y, int x, const char *fmt, ...)
{
    if (vc_wmove(w, y, x) == ERR) return ERR;
    char buf[1024];
    va_list ap;
    va_start(ap, fmt);
    vsnprintf(buf, sizeof(buf), fmt, ap);
    va_end(ap);
    return vc_waddstr(w, buf);
}

int vc_werase(WINDOW *w)
{
    if (!w) return ERR;
    for (int i = 0; i < w->maxy * w->maxx; i++)
        w->cells[i] = ' ';
    for (int i = 0; i < w->maxy; i++)
        w->dirty[i] = 1;
    w->cury = 0;
    w->curx = 0;
    return OK;
}

int vc_wclear(WINDOW *w)
{
    return vc_werase(w);
}

int vc_touchwin(WINDOW *w)
{
    if (!w) return ERR;
    for (int i = 0; i < w->maxy; i++)
        w->dirty[i] = 1;
    return OK;
}

int vc_box(WINDOW *w, chtype vert, chtype horiz)
{
    if (!w) return ERR;
    if (vert == 0) vert = '|';
    if (horiz == 0) horiz = '-';
    int h = w->maxy;
    int ww = w->maxx;
    for (int x = 0; x < ww; x++) {
        w->cells[x] = horiz;
        w->cells[(h - 1) * ww + x] = horiz;
    }
    for (int y = 0; y < h; y++) {
        w->cells[y * ww] = vert;
        w->cells[y * ww + ww - 1] = vert;
    }
    w->cells[0] = '+';
    w->cells[ww - 1] = '+';
    w->cells[(h - 1) * ww] = '+';
    w->cells[(h - 1) * ww + ww - 1] = '+';
    for (int i = 0; i < h; i++)
        w->dirty[i] = 1;
    return OK;
}

/* --- Refresh --- */

static char outbuf[65536];
static int outpos;

static void ob_add(const char *s)
{
    while (*s && outpos < (int)sizeof(outbuf) - 1)
        outbuf[outpos++] = *s++;
}

static void ob_goto(int row, int col)
{
    char tmp[24];
    sprintf(tmp, "\033[%d;%dH", row + 1, col + 1);
    ob_add(tmp);
}

static void ob_attr(int attr, int *cur)
{
    if (attr == *cur) return;
    ob_add("\033[0m");
    if (attr & A_BOLD)    ob_add("\033[1m");
    if (attr & A_BLINK)   ob_add("\033[5m");
    if (attr & A_REVERSE) ob_add("\033[7m");
    *cur = attr;
}

int vc_wrefresh(WINDOW *w)
{
    if (!w) return ERR;
    outpos = 0;
    int last_attr = cur_screen_attr;
    int need_goto = 1;
    int last_sy = -1, last_sx = -1;

    for (int y = 0; y < w->maxy; y++) {
        if (!w->dirty[y]) { need_goto = 1; continue; }
        w->dirty[y] = 0;
        int sy = w->begy + y;
        if (sy < 0 || sy >= LINES) { need_goto = 1; continue; }

        need_goto = 1;

        for (int x = 0; x < w->maxx; x++) {
            int sx = w->begx + x;
            if (sx >= COLS) break;
            chtype cell = w->cells[y * w->maxx + x];
            int scr_idx = sy * COLS + sx;

            if (screen_buf && scr_idx < screen_buf_size &&
                screen_buf[scr_idx] == cell) {
                need_goto = 1;
                continue;
            }

            if (need_goto) {
                ob_goto(sy, sx);
                need_goto = 0;
                last_sy = sy;
                last_sx = sx;
            }

            ob_attr(cell & ~0xFF, &last_attr);

            char c = cell & 0xFF;
            if (c < 32) c = ' ';
            if (outpos < (int)sizeof(outbuf) - 1)
                outbuf[outpos++] = c;

            if (screen_buf && scr_idx < screen_buf_size)
                screen_buf[scr_idx] = cell;

            last_sx++;
        }
    }

    cur_screen_attr = last_attr;
    if (outpos > 0) {
        vms_write_raw(outbuf, outpos);
    }
    return OK;
}

void vc_mark_refresh(WINDOW *w)
{
    if (!w) return;
    for (int i = 0; i < n_pending; i++)
        if (pending_wins[i] == w) return;
    if (n_pending < MAX_PENDING)
        pending_wins[n_pending++] = w;
}

void vc_do_update(void)
{
    for (int i = 0; i < n_pending; i++)
        vc_wrefresh(pending_wins[i]);
    n_pending = 0;
    vms_flush();
}

/* --- Input --- */

int vc_wgetch(WINDOW *w)
{
    (void)w;
    vms_flush();
    int c = vms_readch();
    if (c == ERR) return ERR;

    if (c == 27) {
        int c2 = vms_readch_timed();
        if (c2 == ERR) return 27;
        if (c2 == '[') {
            int c3 = vms_readch_timed();
            if (c3 == ERR) return 27;
            switch (c3) {
            case 'A': return KEY_UP;
            case 'B': return KEY_DOWN;
            case 'C': return KEY_RIGHT;
            case 'D': return KEY_LEFT;
            case '5': vms_readch_timed(); return KEY_PPAGE;
            case '6': vms_readch_timed(); return KEY_NPAGE;
            default: return c3;
            }
        } else if (c2 == 'O') {
            int c3 = vms_readch_timed();
            if (c3 == ERR) return 27;
            switch (c3) {
            case 'A': return KEY_UP;
            case 'B': return KEY_DOWN;
            case 'C': return KEY_RIGHT;
            case 'D': return KEY_LEFT;
            default: return c3;
            }
        }
        return 27;
    }
    if (c == '\r') return '\n';
    return c;
}

/* --- Line input --- */

int vc_wgetnstr(WINDOW *w, char *buf, int n)
{
    if (!w || !buf || n <= 0) return ERR;
    int pos = 0;
    int sy = w->begy + w->cury;
    int sx = w->begx + w->curx;
    vms_out("\033[?25h");
    vms_goto(sy, sx);
    vms_flush();
    for (;;) {
        int ch = vms_readch();
        if (ch == ERR) continue;
        if (ch == '\r' || ch == '\n') {
            buf[pos] = '\0';
            vms_out("\033[?25l");
            vms_flush();
            return OK;
        }
        if (ch == 127 || ch == 8) {
            if (pos > 0) {
                pos--;
                vms_out("\b \b");
                vms_flush();
            }
            continue;
        }
        if (ch >= 32 && pos < n - 1) {
            buf[pos++] = ch;
            char ec = (char)ch;
            vms_write_raw(&ec, 1);
        }
    }
}

#endif /* __VMS */
