import type { ExtensionAPI } from "@oh-my-pi/pi-coding-agent";

/**
 * ECC Observability Hooks — session lifecycle, strategic compaction, usage tracking.
 *
 * Port of ECC session hooks (SessionStart, PostToolUse, Stop) from hooks/hooks.json.
 */

// Track tool-call counts per session for compaction advisory
const toolCallCounts = new WeakMap<object, number>();

function bumpToolCount(ctx: object): number {
  const prev = toolCallCounts.get(ctx) ?? 0;
  const next = prev + 1;
  toolCallCounts.set(ctx, next);
  return next;
}

export function registerObservabilityHooks(pi: ExtensionAPI): void {
  // ── Session start: show welcome banner ────────────────────────────────
  pi.on("session_start", async (_event, ctx) => {
    ctx.ui.notify(
      "ECC: Everything Claude Code — safety hooks, 9 slash commands, 237+ skills active",
      "info",
    );
  });

  // ── Session switch notification ───────────────────────────────────────
  pi.on("session_switch", async (_event, ctx) => {
    ctx.ui.notify("ECC: session switched", "info");
  });

  // ── Tool execution observability ──────────────────────────────────────
  pi.on("tool_execution_start", async (event) => {
    // Placeholder for future metrics/logging
  });

  pi.on("tool_result", async (event, ctx) => {
    const count = bumpToolCount(ctx);
    // At every 50th tool call, suggest compaction if context looks heavy
    if (count > 0 && count % 50 === 0) {
      // Notify but don't block — informational only
      ctx.ui.notify(
        `ECC: ${count}+ tool calls this session. Consider /compact if response quality drops.`,
        "info",
      );
    }
  });

  // ── Auto-compaction lifecycle ─────────────────────────────────────────
  pi.on("auto_compaction_start", async () => {
    // Observability hook — could log compaction events
  });

  pi.on("auto_compaction_end", async () => {
    // Observability hook — could log compaction results
  });

  // ── Session shutdown / final summary ──────────────────────────────────
  pi.on("session_shutdown", async () => {
    // Future: persist usage stats
  });
}
