import type { Status } from '@pixeloffice/protocol';
import type { OfficeRuntime } from './runtime.ts';

const MIN = 60_000;

function ago(ms: number): string {
  if (ms < MIN) return '<1 мин';
  if (ms < 60 * MIN) return `${Math.floor(ms / MIN)} мин`;
  if (ms < 48 * 60 * MIN) return `${Math.floor(ms / (60 * MIN))} ч`;
  return `${Math.floor(ms / (24 * 60 * MIN))} дн`;
}

// Одна строка статусов: что сервер знает о каждой сущности (спека хостинга 5.6).
export type StatusRow = {
  id: string;
  kind: 'human' | 'agent';
  name: string;
  label: string; // подпись над персонажем
  status: Status;
  meetingId?: string;
  source: string | null; // нет статуса — null
  at: string | null; // время статуса, ISO; нет статуса — null
  expiresAt?: string; // когда статус протухнет (TTL от приёма), ISO
  question?: string; // вопрос ждущего агента
};

const isoOf = (ms: number) => new Date(ms).toISOString();

// Все сущности со статусами, включая offline-агентов: для GET /v1/admin/status и таблицы CLI status.
export function statusRows(rt: OfficeRuntime, _now: number): StatusRow[] {
  const questions = rt.world.questions();
  return rt.registry.all().map((e) => {
    const s = rt.store.get(e.id);
    const row: StatusRow = {
      id: e.id,
      kind: e.kind,
      name: e.name,
      label: rt.entityView(e).label,
      status: s?.status ?? 'offline',
      source: s?.source ?? null,
      at: s ? isoOf(s.at) : null,
    };
    if (s?.meetingId) row.meetingId = s.meetingId;
    if (s && s.ttlSec !== undefined && s.status !== 'offline') row.expiresAt = isoOf(s.receivedAt + s.ttlSec * 1000);
    const q = questions[e.id];
    if (q) row.question = q.text; // questions() после адресных сообщений всегда отдаёт объекты с текстом
    return row;
  });
}

// Таблица «кто с каким статусом» для команды status: люди все, агенты в offline — только с all (их копится много).
// У ждущего ответа агента — текст вопроса из облачка.
export function statusTable(rt: OfficeRuntime, opts: { now: number; all?: boolean }): string {
  const rows: string[][] = [['ID', 'ПОДПИСЬ', 'СТАТУС', 'ДАВНО', 'ИСТОЧНИК']];
  let hidden = 0;
  for (const r of statusRows(rt, opts.now)) {
    if (r.kind === 'agent' && r.status === 'offline' && !opts.all) {
      hidden++;
      continue;
    }
    rows.push([
      r.id,
      r.label,
      r.meetingId ? `${r.status} ${r.meetingId}` : r.status,
      r.at ? ago(opts.now - Date.parse(r.at)) : '—',
      r.source ?? '—',
      ...(r.question ? [`«${r.question}»`] : []),
    ]);
  }
  const width = (i: number) => Math.max(...rows.map((r) => r[i]?.length ?? 0));
  const widths = rows[0]!.map((_, i) => width(i));
  const lines = rows.map((r) => r.map((c, i) => (i < r.length - 1 ? c.padEnd(widths[i]!) : c)).join('  '));
  if (hidden) lines.push(`агентов offline скрыто: ${hidden} (--all — показать)`);
  return lines.join('\n');
}
