import type { HookConfig } from './config.ts';
import { loadHookConfig } from './config.ts';
import { pickLabel } from './label.ts';
import { agentOf, askEvents, statusEvent } from './map.ts';
import { QUESTION_RULE, questionOf } from './question.ts';
import { send } from './send.ts';
import { tmuxWindowLabel } from './tmux.ts';
import { textOf, type PiApi, type PiContext } from './types.ts';
import type { AgentLabel, AgentStatus, Event } from '@pixeloffice/protocol';

// pixeloffice-pi — расширение pi (адаптер статусов в PixelOffice, аналог claude-hook, спека 6.1).
// Живёт внутри процесса pi, поэтому главное — не мешать: сеть и tmux с таймаутами, ошибки проглатываются,
// обработчики не бросают. Статусы шлёт только диалоговым сессиям (tui, rpc): print-прогон из панели tmux
// наследует её TMUX_PANE и мигнул бы working/offline на живом персонаже панели.
// События pi → статусы:
//   session_start → idle          agent_settled → idle (ход с меткой «**Вопрос:**» — needs_input + облачко)
//   before_agent_start → working  ui_prompt_start → needs_input + облачко с заголовком диалога
//   turn_end → working            ui_prompt_end → working в ходе, idle вне хода (диалог команды)
//   session_shutdown → offline    session_info_changed → переотправить статус: имя сессии стало меткой
// Метка агента: ручное имя окна tmux, запасной — имя сессии pi (label.ts). Правило о метке вопроса
// кладётся в системный промпт сессией section-ом `pixeloffice` — идемпотентно, перезаписью.

export type Io = {
  env: Record<string, string | undefined>;
  now(): Date;
  fetch: typeof fetch;
  tmux(env: Record<string, string | undefined>): Promise<AgentLabel | null | undefined>;
  config(env: Record<string, string | undefined>): HookConfig | null;
};

export const defaultIo: Io = {
  env: process.env,
  now: () => new Date(),
  fetch,
  tmux: tmuxWindowLabel,
  config: loadHookConfig,
};

// Предписание обработчика; emit достраивает время, метку и адрес агента.
type Plan = { kind: 'status'; status: AgentStatus } | { kind: 'ask'; text: string };

const debug = (io: Io) => io.env['PIXELOFFICE_HOOK_DEBUG'] === '1';

export default function pixelofficePi(pi: PiApi, io: Io = defaultIo): void {
  let runActive = false; // идёт ход (до agent_settled): решает, working или idle после диалога
  let promptDepth = 0; // открытые блокирующие диалоги: вложенные не переоткрывают needs_input
  let lastAssistant: string | undefined; // текст последнего ответа — вопрос на settle ищется в нём
  let lastStatus: AgentStatus = 'idle'; // что уже отправлено: переотправляется при смене имени сессии
  let sessionName: string | undefined; // имя сессии из события — оно свежее getSessionName к моменту чтения

  const labelOf = async (ctx: PiContext): Promise<AgentLabel | null | undefined> =>
    pickLabel(!io.env['TMUX_PANE'], await io.tmux(io.env), sessionName ?? ctx.sessionManager.getSessionName());

  const dialogSession = (ctx: PiContext): boolean => ctx.mode === 'tui' || ctx.mode === 'rpc';

  const emit = async (ctx: PiContext, plans: Plan[]): Promise<void> => {
    const cfg = io.config(io.env);
    const agent = agentOf(ctx.sessionManager.getCwd(), io.env, ctx.sessionManager.getSessionId());
    if (!cfg || !agent || !dialogSession(ctx) || plans.length === 0) return;
    const at = io.now().toISOString();
    const label = await labelOf(ctx);
    const events: Event[] = plans.flatMap((p) => (p.kind === 'status' ? [statusEvent(agent, p.status, at, label)] : askEvents(agent, p.text, at, label)));
    const last = plans.at(-1)!;
    lastStatus = last.kind === 'status' ? last.status : 'needs_input';
    try {
      const results = await send(events, cfg, io.fetch);
      if (debug(io))
        for (const r of results)
          console.error(`pixeloffice-pi: ${plans.map((p) => (p.kind === 'status' ? p.status : 'ask')).join(',')} → ${r.url} ${r.status ?? `ошибка: ${r.error}`}`);
    } catch {
      // сервер недоступен — молча: сессия pi важнее офиса
    }
  };

  pi.on('session_start', (_e, ctx) => {
    runActive = false;
    promptDepth = 0;
    lastAssistant = undefined;
    return emit(ctx, [{ kind: 'status', status: 'idle' }]);
  });

  pi.on('session_shutdown', (_e, ctx) => emit(ctx, [{ kind: 'status', status: 'offline' }]));

  pi.on('before_agent_start', (e, ctx) => {
    // Правило о метке вопроса — только диалоговым сессиям с настроенным офисом; идемпотентно: перезапись section
    if (dialogSession(ctx) && io.config(io.env)) e.systemPromptOptions.sections['pixeloffice'] = QUESTION_RULE;
    runActive = true;
    return emit(ctx, [{ kind: 'status', status: 'working' }]);
  });

  pi.on('turn_end', (_e, ctx) => emit(ctx, [{ kind: 'status', status: 'working' }])); // освежает ttl длинного хода

  pi.on('message_end', (e) => {
    if (e.message.role === 'assistant') lastAssistant = textOf(e.message.content);
  });

  pi.on('ui_prompt_start', (e, ctx) => {
    if (promptDepth++ > 0) return; // вложенный диалог — статус уже needs_input
    return emit(ctx, [{ kind: 'ask', text: e.title ?? '' }]);
  });

  pi.on('ui_prompt_end', (_e, ctx) => {
    if (--promptDepth > 0) return;
    promptDepth = 0;
    return emit(ctx, [{ kind: 'status', status: runActive ? 'working' : 'idle' }]);
  });

  pi.on('agent_settled', (e, ctx) => {
    runActive = false;
    // Прерванный ход (Escape) вопроса не задал — текст последнего ответа мог остаться от прошлых ходов
    const q = e.aborted ? null : questionOf(lastAssistant);
    return emit(ctx, q ? [{ kind: 'ask', text: q }] : [{ kind: 'status', status: 'idle' }]);
  });

  pi.on('session_info_changed', (e, ctx) => {
    sessionName = e.name;
    if (lastStatus === 'offline') return;
    return emit(ctx, [{ kind: 'status', status: lastStatus }]); // имя сессии стало меткой — обновить её
  });
}
