import picomatch from 'picomatch';
import type { RelayLabels } from '@pixeloffice/core';
import type { AgentLabel, Event } from '@pixeloffice/protocol';
import { expandHome } from '@pixeloffice/validate-maps';
import type { Logger } from './logger.ts';

export type RelayOptions = {
  target: string;
  token: string;
  include: string[];
  labels: RelayLabels; // какие метки агентов уходят в командный офис (спека метки §4.5); по умолчанию public — в схеме конфига
  log: Logger;
  fetchImpl?: typeof fetch;
  now?: () => number;
  maxQueue?: number;
};

const BATCH = 500;
const MAX_BACKOFF_MS = 60_000;
const MAX_ERROR_BODY = 200;

// Индексы отвергнутых событий из ответа /v1/events (issues[].path = «events.<i>…»): только для ошибок,
// привязанных к событию (400 — схема, 403 foreign_source). null — виноватые не названы или это вся пачка.
function rejectedIndexes(status: number, body: string, size: number): number[] | null {
  try {
    const j = JSON.parse(body) as { error?: unknown; issues?: { path?: unknown }[] };
    if (!(status === 400 || (status === 403 && j.error === 'foreign_source')) || !Array.isArray(j.issues)) return null;
    const idx = new Set<number>();
    for (const it of j.issues) {
      const m = typeof it?.path === 'string' ? /^events\.(\d+)(\.|$)/.exec(it.path) : null;
      if (m && Number(m[1]) < size) idx.add(Number(m[1]));
    }
    return idx.size > 0 && idx.size < size ? [...idx].sort((a, b) => b - a) : null;
  } catch {
    return null;
  }
}

// Ретрансляция агентов на командный сервер по glob-фильтру projectDir (спека 4.5).
export class Relay {
  private readonly o: RelayOptions;
  private readonly match: (path: string) => boolean;
  private readonly queue: Event[] = [];
  private readonly maxQueue: number;
  private failures = 0;
  private nextTryAt = 0;
  private overflowWarned = false;
  private inFlight = false;

  constructor(o: RelayOptions) {
    this.o = o;
    this.maxQueue = o.maxQueue ?? 1000;
    this.match = picomatch(o.include.map(expandHome), { dot: true });
  }

  size(): number {
    return this.queue.length;
  }

  // Метка, которую командному офису видеть нельзя, уходит как null, а не вырезается: иначе там осталась бы прежняя
  // метка после того, как вкладке вернули автоматическое имя (спека метки §4.5).
  private hidden(label: AgentLabel): boolean {
    return this.o.labels === 'none' || (this.o.labels === 'public' && label.private);
  }

  // Вызывается из горячего пути приёма событий: сбой ретрансляции не должен ломать локальный приём.
  offer(ev: Event): void {
    try {
      if (ev.type === 'snapshot' || ev.entityId !== undefined || !ev.agent?.projectDir || !this.match(ev.agent.projectDir)) return;
      const { projectDir: _private, ...agent } = ev.agent; // приватный путь на командный сервер не уходит
      const out: Event = { ...ev, agent };
      if (out.type === 'status' && out.label && this.hidden(out.label)) out.label = null;
      this.queue.push(out);
      if (this.queue.length > this.maxQueue) {
        this.queue.splice(0, this.queue.length - this.maxQueue);
        if (!this.overflowWarned) this.o.log.warn(`relay: очередь переполнена (${this.maxQueue}), старые события выброшены`);
        this.overflowWarned = true;
      }
    } catch (e) {
      this.o.log.error(`relay: событие не поставлено в очередь: ${(e as Error).message}`);
    }
  }

  async flush(): Promise<void> {
    const now = (this.o.now ?? Date.now)();
    if (this.inFlight || this.queue.length === 0 || now < this.nextTryAt) return;
    this.inFlight = true;
    const batch = this.queue.slice(0, BATCH);
    try {
      const res = await (this.o.fetchImpl ?? fetch)(this.o.target, {
        method: 'POST',
        headers: { 'content-type': 'application/json', authorization: `Bearer ${this.o.token}` },
        body: JSON.stringify({ events: batch }),
        redirect: 'error', // токен не должен уходить по редиректу на чужой адрес
        signal: AbortSignal.timeout(10_000),
      });
      const transient = res.status === 408 || res.status === 429; // таймаут прокси, лимит — повторяемы, как 5xx
      if (res.ok || (res.status >= 400 && res.status < 500 && !transient)) {
        this.failures = 0;
        this.nextTryAt = 0;
        this.overflowWarned = false;
        if (res.ok) return this.drop(batch);
        const body = await res.text().catch(() => '');
        // Командный сервер отвергает пакет целиком; если он назвал виноватые события — выбрасываем только их,
        // остальные уйдут следующей попыткой. Иначе (401, ошибка без путей) — вся пачка, как раньше.
        const bad = rejectedIndexes(res.status, body, batch.length);
        if (bad) for (const i of bad) this.remove(batch[i]!);
        else this.drop(batch);
        this.o.log.error(`relay: командный сервер отверг ${bad?.length ?? batch.length} из ${batch.length} событий: ${res.status} ${body.slice(0, MAX_ERROR_BODY)}`);
        return;
      }
      this.retryLater(now, `HTTP ${res.status}`);
    } catch (e) {
      this.retryLater(now, (e as Error).message);
    } finally {
      this.inFlight = false;
    }
  }

  // Пока шёл запрос, переполнение могло вытеснить часть пачки: убираем только то, что ещё в очереди.
  private drop(batch: Event[]): void {
    const sent = new Set(batch);
    let n = 0;
    while (n < this.queue.length && sent.has(this.queue[n]!)) n++;
    this.queue.splice(0, n);
  }

  private remove(ev: Event): void {
    const i = this.queue.indexOf(ev);
    if (i >= 0) this.queue.splice(i, 1);
  }

  private retryLater(now: number, why: string): void {
    const delay = Math.min(MAX_BACKOFF_MS, 1000 * 2 ** this.failures++);
    this.nextTryAt = now + delay;
    this.o.log.warn(`relay: ${why}, повтор через ${delay / 1000} с (в очереди ${this.queue.length})`);
  }
}
