import { describe, expect, it } from 'vitest';
import { LABEL_TEXT_MAX as SCHEMA_LABEL_MAX } from '@pixeloffice/protocol';
import { LABEL_TEXT_MAX, cleanLabel, pickLabel, readTmux, tmuxLabel, type TmuxRun } from '../src/tmux.ts';

const pane = (autoRename: string, window: string, title: string) => ({ autoRename, window, title });

it('предел метки hook равен пределу схемы события (спека метки §3.1.3, §4.1)', () => {
  expect(LABEL_TEXT_MAX).toBe(SCHEMA_LABEL_MAX);
});

describe('pickLabel (спека метки §3.1)', () => {
  it('ручное имя окна → оно, private: false', () => {
    expect(pickLabel(pane('0', 'tmux names', '✳ Падение пайплайна'))).toEqual({ text: 'tmux names', private: false });
  });

  it('ручное имя из пробелов или управляющих символов → заголовок', () => {
    expect(pickLabel(pane('0', '   ', '✳ Падение пайплайна'))).toEqual({ text: 'Падение пайплайна', private: true });
    expect(pickLabel(pane('0', '\u0007\u001b', '✳ Падение пайплайна'))).toEqual({ text: 'Падение пайплайна', private: true });
  });

  it('автоматическое имя → заголовок без «✳ » или кадра спиннера, private: true', () => {
    expect(pickLabel(pane('1', 'node', '✳ Падение пайплайна'))).toEqual({ text: 'Падение пайплайна', private: true });
    expect(pickLabel(pane('1', 'node', '⠂ Оценка объёма'))).toEqual({ text: 'Оценка объёма', private: true });
    expect(pickLabel(pane('1', 'zsh', '⠀ Пустой кадр'))).toEqual({ text: 'Пустой кадр', private: true });
  });

  it('заголовок из одних значков, пустой или «Claude Code» → null', () => {
    for (const title of ['✳', '✳   ', '⠐', '', '✳ Claude Code', '⠂ Claude Code']) expect(pickLabel(pane('1', 'node', title))).toBeNull();
  });

  it('заголовок без значка Claude Code → null', () => {
    for (const title of ['stas@laptop-2:~/Projects/My/PixelOffice', 'laptop-2.local', 'Claude Code']) expect(pickLabel(pane('1', 'node', title))).toBeNull();
  });
});

describe('cleanLabel', () => {
  it('управляющие символы убираются, обрамляющие пробелы снимаются', () => {
    expect(cleanLabel('  a\tb\u0000c\n ')).toBe('abc');
  });

  it('обрезка до 100 кодовых единиц UTF-16 без разрыва суррогатной пары', () => {
    expect(cleanLabel('x'.repeat(150))).toBe('x'.repeat(100));
    const s = 'x'.repeat(99) + '😀'; // эмодзи — две кодовые единицы, граница посередине
    expect(cleanLabel(s)).toBe('x'.repeat(99));
    expect(cleanLabel('x'.repeat(98) + '😀')).toBe('x'.repeat(98) + '😀');
  });
});

describe('readTmux / tmuxLabel', () => {
  const ENV = { TMUX_PANE: '%7' };
  const answer = (out: string): TmuxRun => async () => out;

  it('ответ из трёх частей разбирается; аргументы — display -p -t <панель> <формат>', async () => {
    const calls: string[][] = [];
    const run: TmuxRun = async (args) => {
      calls.push(args);
      return '0\tstreet\t✳ Задача\n';
    };
    expect(await readTmux(ENV, run)).toEqual({ autoRename: '0', window: 'street', title: '✳ Задача' });
    expect(calls).toEqual([['display', '-p', '-t', '%7', '#{automatic-rename}\t#{window_name}\t#{pane_title}']]);
  });

  it('ответ не из трёх частей, пустой и ошибка вызова → undefined', async () => {
    expect(await readTmux(ENV, answer('0\tstreet\n'))).toBeUndefined();
    expect(await readTmux(ENV, answer('0\ta\tb\tc\n'))).toBeUndefined();
    expect(await readTmux(ENV, answer(''))).toBeUndefined();
    expect(await readTmux(ENV, async () => Promise.reject(new Error('no server running')))).toBeUndefined();
  });

  it('без TMUX_PANE tmux не вызывается', async () => {
    let called = false;
    const run: TmuxRun = async () => {
      called = true;
      return '0\tx\ty';
    };
    expect(await tmuxLabel({}, run)).toBeUndefined();
    expect(await tmuxLabel({ TMUX_PANE: '' }, run)).toBeUndefined();
    expect(called).toBe(false);
  });

  it('tmuxLabel: прочитан с меткой, прочитан без метки (null), не прочитан (undefined)', async () => {
    expect(await tmuxLabel(ENV, answer('0\tstreet\t✳ x\n'))).toEqual({ text: 'street', private: false });
    expect(await tmuxLabel(ENV, answer('1\tnode\t✳ Claude Code\n'))).toBeNull();
    expect(await tmuxLabel(ENV, answer('мусор'))).toBeUndefined();
  });
});
