// Notifications natives sur front montant d'une session vers `waiting` (doublonne utilement le Web
// Push, ici dans l'éditeur). Suit l'activité précédente par session pour ne notifier qu'à la transition,
// pas à chaque mise à jour. Actions : ouvrir le terminal, ou répondre Yes/No via la commande WS `answer`.
import * as vscode from 'vscode';
import type { SessionSummary } from '@arboretum/shared';
import type { Store } from './state/store.js';

export interface NotificationHooks {
  notifyEnabled(): boolean;
  openTerminal(session: SessionSummary): void;
  answer(session: SessionSummary, action: 'confirm' | 'deny'): void;
}

export class WaitingNotifier implements vscode.Disposable {
  /** dernière activité connue par session → détection du front montant vers 'waiting'. */
  private readonly lastActivity = new Map<string, string | null | undefined>();
  private readonly unsubscribe: () => void;

  constructor(
    private readonly store: Store,
    private readonly hooks: NotificationHooks,
  ) {
    this.unsubscribe = store.onDidChange(() => this.check());
  }

  private check(): void {
    const sessions = this.store.allSessions();
    const seen = new Set<string>();
    for (const s of sessions) {
      seen.add(s.id);
      const prev = this.lastActivity.get(s.id);
      const cur = s.live ? s.activity : null;
      this.lastActivity.set(s.id, cur);
      if (cur === 'waiting' && prev !== 'waiting' && prev !== undefined && this.hooks.notifyEnabled()) {
        this.notify(s);
      }
      // prev === undefined : première observation (au seed) → on n'annonce pas l'historique.
    }
    for (const id of [...this.lastActivity.keys()]) if (!seen.has(id)) this.lastActivity.delete(id);
  }

  private notify(session: SessionSummary): void {
    const title = session.title?.trim() || session.command;
    const detail = session.waitingFor ? ` · ${session.waitingFor}` : '';
    void vscode.window
      .showInformationMessage(`Arboretum: "${title}" is waiting for input${detail}`, 'Open Terminal', 'Yes', 'No')
      .then((choice) => {
        if (choice === 'Open Terminal') this.hooks.openTerminal(session);
        else if (choice === 'Yes') this.hooks.answer(session, 'confirm');
        else if (choice === 'No') this.hooks.answer(session, 'deny');
      });
  }

  dispose(): void {
    this.unsubscribe();
  }
}
