#!/usr/bin/env node
/**
 * session-learn — Stop event hook for autonomous learning.
 *
 * Fires at session end. Nudges agent to process buffered observations
 * before context is lost. Cleans up buffer if too small for analysis.
 *
 * @tier efficiency
 * @event Stop
 * @scope user
 */
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import process from 'node:process';
import { createHook } from './_runtime.mjs';

const bufferPath = path.join(os.tmpdir(), `aikit-obs-${process.ppid}.jsonl`);
const MIN_OBSERVATIONS = 10;

const getLineCount = (filePath) => {
  try {
    return fs.readFileSync(filePath, 'utf8').split('\n').filter(Boolean).length;
  } catch {
    return 0;
  }
};

const cleanup = () => {
  try {
    fs.unlinkSync(bufferPath);
  } catch {}
};

/** Nudges end-of-session lesson extraction and cleans up small buffers. */
export const sessionLearn = async (context) => {
  if (context.event !== 'Stop') return { decision: 'allow' };

  const count = getLineCount(bufferPath);
  if (count < MIN_OBSERVATIONS) {
    cleanup();
    return { decision: 'allow' };
  }

  return {
    additionalContext: [
      `[Observer] Session ending with ${count} observations buffered.`,
      'Run knowledge({ action: "lesson", subAction: "auto-observe" }) to extract learning patterns.',
    ].join(' '),
  };
};

createHook(sessionLearn);
