import { describe, test } from 'node:test';
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { mkdtempSync, rmSync, mkdirSync, writeFileSync, copyFileSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { tmpdir } from 'node:os';
import { fileURLToPath } from 'node:url';

// B-S3: SessionStart emits a warn-only "trend signals are N days old" nudge,
// driven by the trend store's newest capturedAt, and ONLY when the store already
// holds captures. session-start is a procedural hook with no exports, so we run
// it as a subprocess with an isolated HOME + LINKEDIN_STUDIO_DATA and inspect the
// additionalContext. Pattern: session-start-remember.test.mjs subprocess harness.
const here = dirname(fileURLToPath(import.meta.url));
const hookPath = join(here, '..', 'session-start.mjs');
const PLUGIN_ROOT = join(here, '..', '..', '..');
const STATE_TEMPLATE = join(PLUGIN_ROOT, 'config', 'state-file.template.md');

const NUDGE = 'Trend signals are';
const isoDaysAgo = (n) => new Date(Date.now() - n * 86400000).toISOString().slice(0, 10);

// Run the hook against an isolated HOME + data root; optionally seed a trend
// store. Returns the additionalContext string the hook injected at session start.
function runHook({ captures }) {
  const home = mkdtempSync(join(tmpdir(), 'lis-ts-home-'));
  const data = mkdtempSync(join(tmpdir(), 'lis-ts-data-'));
  try {
    // The reminders block only runs when the state file already exists; the
    // template is the canonical valid state, so copy it into the isolated HOME.
    mkdirSync(join(home, '.claude'), { recursive: true });
    copyFileSync(STATE_TEMPLATE, join(home, '.claude', 'linkedin-studio.local.md'));

    if (captures) {
      mkdirSync(join(data, 'trends'), { recursive: true });
      writeFileSync(
        join(data, 'trends', 'trends.json'),
        JSON.stringify({ schemaVersion: 1, trends: captures }),
      );
    }

    const stdout = execFileSync('node', [hookPath], {
      input: '',
      env: { ...process.env, HOME: home, USERPROFILE: home, LINKEDIN_STUDIO_DATA: data },
      encoding: 'utf-8',
    });
    return JSON.parse(stdout).hookSpecificOutput.additionalContext;
  } finally {
    rmSync(home, { recursive: true, force: true });
    rmSync(data, { recursive: true, force: true });
  }
}

const trend = (capturedAt) => ({
  id: 't' + capturedAt,
  title: 'Some trend ' + capturedAt,
  url: 'https://example.com/' + capturedAt,
  source: 'tavily',
  capturedAt,
  topics: ['x'],
});

describe('session-start — trend-store staleness nudge (B-S3)', () => {
  test('fires when newest capture is >=7 days old', () => {
    const ctx = runHook({ captures: [trend('2026-01-01'), trend(isoDaysAgo(10))] });
    assert.ok(ctx.includes(NUDGE), 'expected the trend-staleness nudge for a 10-day-old store');
  });

  test('does NOT fire when newest capture is fresh (<7 days)', () => {
    const ctx = runHook({ captures: [trend(isoDaysAgo(2))] });
    assert.ok(!ctx.includes(NUDGE), 'a 2-day-old store must not trigger the nudge');
  });

  test('does NOT fire (and does not crash) when the store is absent/empty', () => {
    const absent = runHook({ captures: null });
    assert.ok(!absent.includes(NUDGE), 'no store => no nudge');
    const empty = runHook({ captures: [] });
    assert.ok(!empty.includes(NUDGE), 'empty store => no nudge (never-scanned user is never nagged)');
  });
});
