import { existsSync, mkdirSync } from 'node:fs';
import { join } from 'node:path';
import type { VncStartParams, VncSessionInfo } from '../protocol';
import { getOwnerHomeDir } from '@@/data-path';

// Mirrors the physical display instead of spawning a virtual desktop per user, so the
// browser shows the same session as the screen. There is exactly one :0, hence one
// shared mirror — the first caller's VNC password is the one it answers with.
const MIRROR_DISPLAY = ':0';
const MIRROR_DISPLAY_NUM = 0;
const MIRROR_PORT = 5900;
const READY_TIMEOUT_MS = 5000;
// Above this framebuffer width the stream is halved; at or below it, pixels are served 1:1.
const SCALE_ABOVE_WIDTH = 2560;

// x11vnc reads :0's cookie from the logged-in user's X authority, so no root is needed. Where that
// cookie lives depends on the display manager: GDM (Ubuntu GNOME on Xorg) keeps it in the per-session
// dir /run/user/<uid>/gdm/Xauthority; LightDM (or a manual startx) uses the classic ~/.Xauthority. Try
// the GDM path first, then fall back. While the greeter owns :0 the user's cookie doesn't exist yet and
// mirroring fails until someone is logged in.
function resolveXauthority(): string | null {
  const uid = typeof process.getuid === 'function' ? process.getuid() : null;
  const candidates = [
    uid != null ? `/run/user/${uid}/gdm/Xauthority` : null,
    join(process.env.HOME ?? '', '.Xauthority'),
  ].filter((p): p is string => Boolean(p));
  return candidates.find((p) => existsSync(p)) ?? null;
}

type MirrorSession = {
  email: string;
  username: string;
  display: number;
  port: number;
  pid: number;
};

let mirror: MirrorSession | null = null;

function isProcessAlive(pid: number): boolean {
  try {
    process.kill(pid, 0);
    return true;
  } catch {
    return false;
  }
}

// Provision the pair of files a VNC session needs: `password` in plaintext, which the API hands to
// the browser, and `passwd` in rfbauth format, which x11vnc authenticates against. Idempotent —
// returns the existing password when both are already present.
//
// x11vnc writes the rfbauth file itself via -storepasswd. This used to shell out to tigervnc's
// `vncpasswd -f`, which is not installed by default (and is not in tigervnc-common, despite what
// setup-desktop.sh claimed), so the rfbauth file silently never appeared — the failure was swallowed
// because only a zero exit code triggered the write.
export async function ensureVncPassword(homeDir: string): Promise<{ password: string; passwdFile: string }> {
  const vncDir = join(homeDir, '.vnc');
  const passwdFile = join(vncDir, 'passwd');
  const plainFile = join(vncDir, 'password');

  if (existsSync(passwdFile) && existsSync(plainFile)) {
    const password = (await Bun.file(plainFile).text()).trim();
    if (password) return { password, passwdFile };
  }

  mkdirSync(vncDir, { recursive: true });

  // 8 printable ASCII characters. VNC truncates to 8, so there is no point generating more.
  const password = Array.from(crypto.getRandomValues(new Uint8Array(8)))
    .map((b) => String.fromCharCode(33 + (b % 94)))
    .join('');

  await Bun.write(plainFile, password);

  const proc = Bun.spawnSync({
    cmd: ['x11vnc', '-storepasswd', password, passwdFile],
    stdout: 'ignore',
    stderr: 'pipe',
  });
  if (proc.exitCode !== 0 || !existsSync(passwdFile)) {
    const stderr = proc.stderr.toString().trim();
    throw new Error(`Could not write the VNC password file: ${stderr || 'x11vnc -storepasswd failed'}`);
  }

  Bun.spawnSync({ cmd: ['chmod', '600', passwdFile], stdout: 'ignore', stderr: 'ignore' });
  Bun.spawnSync({ cmd: ['chmod', '600', plainFile], stdout: 'ignore', stderr: 'ignore' });

  console.log(`[vnc] provisioned VNC password at ${vncDir}`);
  return { password, passwdFile };
}

// Width of :0's framebuffer, or null when it cannot be read (xrandr missing, X not up). Callers
// treat null as "don't scale" — serving too many pixels beats serving an unreadable thumbnail.
function getFramebufferWidth(xauthority: string): number | null {
  const proc = Bun.spawnSync({
    cmd: ['xrandr', '--current'],
    env: { ...process.env, DISPLAY: MIRROR_DISPLAY, XAUTHORITY: xauthority },
    stdout: 'pipe',
    stderr: 'ignore',
  });
  if (proc.exitCode !== 0) return null;
  const match = proc.stdout.toString().match(/current\s+(\d+)\s*x\s*(\d+)/);
  return match ? Number(match[1]) : null;
}

async function isPortOpen(port: number): Promise<boolean> {
  try {
    const socket = await Bun.connect({
      hostname: '127.0.0.1',
      port,
      socket: { data() {}, error() {} },
    });
    socket.end();
    return true;
  } catch {
    return false;
  }
}

// x11vnc stays in the foreground, so readiness is the listening port rather than exit code.
async function waitForPort(port: number): Promise<boolean> {
  const deadline = Date.now() + READY_TIMEOUT_MS;
  while (Date.now() < deadline) {
    if (await isPortOpen(port)) return true;
    await Bun.sleep(100);
  }
  return false;
}

export async function startSession(params: VncStartParams): Promise<{ port: number; display: number }> {
  if (mirror && isProcessAlive(mirror.pid)) {
    return { port: mirror.port, display: mirror.display };
  }
  mirror = null;

  const homeDir = getOwnerHomeDir(params.email);
  const { passwdFile } = await ensureVncPassword(homeDir);

  const xauthority = resolveXauthority();
  if (!xauthority) {
    throw new Error(`No X authority found (GDM or ~/.Xauthority) — nobody is logged in on ${MIRROR_DISPLAY}`);
  }

  // Halving a 4K framebuffer keeps the stream sane over the tailnet, but the same 0.5 applied to a
  // small screen is just lost detail — and with no monitor plugged in, X falls back to something
  // tiny (800x480 here), which halves to an unreadable 400x240. Scale only when there is genuinely
  // too much to send.
  const width = getFramebufferWidth(xauthority);
  const scale = width !== null && width > SCALE_ABOVE_WIDTH ? ['-scale', '0.5'] : [];
  if (width !== null) {
    console.log(`[vnc] :0 framebuffer is ${width}px wide — ${scale.length ? 'scaling to 50%' : 'serving 1:1'}`);
  }

  const proc = Bun.spawn({
    cmd: [
      'x11vnc',
      '-display',
      MIRROR_DISPLAY,
      '-auth',
      xauthority,
      '-rfbport',
      String(MIRROR_PORT),
      '-rfbauth',
      passwdFile,
      '-localhost',
      '-forever',
      '-shared',
      ...scale,
      '-noxdamage',
      '-quiet',
    ],
    stdout: 'ignore',
    stderr: 'pipe',
  });

  // Drain stderr so the pipe cannot fill and stall x11vnc; keep the tail for errors
  let stderrTail = '';
  (async () => {
    const reader = (proc.stderr as ReadableStream<Uint8Array>).getReader();
    const decoder = new TextDecoder();
    try {
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        stderrTail = (stderrTail + decoder.decode(value, { stream: true })).slice(-2000);
      }
    } catch {
      // process ended
    }
  })();

  if (!(await waitForPort(MIRROR_PORT))) {
    try {
      proc.kill();
    } catch {
      // already dead
    }
    throw new Error(`x11vnc failed to listen on ${MIRROR_PORT}: ${stderrTail.trim() || 'timed out'}`);
  }

  mirror = {
    email: params.email,
    username: params.username ?? '',
    display: MIRROR_DISPLAY_NUM,
    port: MIRROR_PORT,
    pid: proc.pid,
  };
  console.log(`[vnc] mirroring ${MIRROR_DISPLAY} on port ${MIRROR_PORT} (pid ${proc.pid})`);

  return { port: MIRROR_PORT, display: MIRROR_DISPLAY_NUM };
}

export function stopSession(_email: string): void {
  if (!mirror) return;

  try {
    process.kill(mirror.pid);
  } catch {
    // already dead
  }

  console.log(`[vnc] stopped mirror of ${MIRROR_DISPLAY} (pid ${mirror.pid})`);
  mirror = null;
}

export function getSession(_email: string): VncSessionInfo | null {
  if (!mirror) return null;

  const alive = mirror.pid > 0 && isProcessAlive(mirror.pid);
  if (!alive) {
    mirror = null;
    return null;
  }

  return {
    email: mirror.email,
    display: mirror.display,
    port: mirror.port,
    pid: mirror.pid,
    alive,
  };
}

export function stopAll(): void {
  stopSession('');
}
