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';

// N13 (A1-10 / A1-11 surfacing): the week's picture — which editions are in
// flight and which publishing slots are still empty — must be readable at
// session start without opening a file. 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-trends-staleness.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 WIP_HEADER = '## Editions in Flight';
const SLOTS_HEADER = '## Publishing Slots';
const NEXT_OPEN = 'Next open slot:';

const DAY_KEYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
const isoDaysAhead = (n) => new Date(Date.now() + n * 86400000).toISOString().slice(0, 10);
const isoDaysAgo = (n) => new Date(Date.now() - n * 86400000).toISOString().slice(0, 10);
const weekdayOf = (isoDate) => DAY_KEYS[new Date(`${isoDate}T12:00:00Z`).getUTCDay()];

// Seed an isolated data root, run the hook, return the injected context.
function runHook({ slots, queue, editions, trends } = {}) {
  const home = mkdtempSync(join(tmpdir(), 'lis-sl-home-'));
  const data = mkdtempSync(join(tmpdir(), 'lis-sl-data-'));
  try {
    // The status/reminders branch only runs when the state file exists; the
    // template is the canonical valid state.
    mkdirSync(join(home, '.claude'), { recursive: true });
    copyFileSync(STATE_TEMPLATE, join(home, '.claude', 'linkedin-studio.local.md'));

    if (slots) {
      mkdirSync(join(data, 'profile'), { recursive: true });
      writeFileSync(
        join(data, 'profile', 'publishing-slots.json'),
        JSON.stringify({ schemaVersion: 1, slots }),
      );
    }
    if (queue) {
      mkdirSync(join(data, 'drafts'), { recursive: true });
      writeFileSync(join(data, 'drafts', 'queue.json'), JSON.stringify({ version: 1, queue }));
    }
    if (editions) {
      mkdirSync(join(data, 'editions'), { recursive: true });
      writeFileSync(
        join(data, 'editions', 'register.json'),
        JSON.stringify({ schemaVersion: 1, editions }),
      );
    }
    if (trends) {
      mkdirSync(join(data, 'trends'), { recursive: true });
      writeFileSync(join(data, 'trends', 'trends.json'), JSON.stringify({ schemaVersion: 1, trends }));
    }

    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 activeRow = (over = {}) => ({
  series: 'serien',
  editionId: '05',
  title: 'En utgave',
  path: '/series/serien',
  currentPhase: 'draft',
  nextAction: 'Step 4 - full draft',
  slot: null,
  startedAt: new Date(Date.now() - 3 * 86400000).toISOString(),
  updatedAt: new Date().toISOString(),
  completedAt: null,
  status: 'active',
  ...over,
});

describe('session-start — editions in flight (N13/A1-11)', () => {
  test('surfaces active editions with phase, next action and days in flight', () => {
    const ctx = runHook({ editions: [activeRow()] });
    assert.ok(ctx.includes(WIP_HEADER), 'expected the in-flight roll-up');
    assert.ok(ctx.includes('serien #05'), 'expected the edition identity');
    assert.ok(ctx.includes('draft'), 'expected the current phase');
    assert.ok(ctx.includes('Step 4 - full draft'), 'expected the next action');
    assert.ok(/3d in flight/.test(ctx), 'expected measured days in flight');
  });

  test('completed editions drop out — the view is work in progress, not history', () => {
    const ctx = runHook({
      editions: [activeRow({ editionId: '04', status: 'complete', completedAt: new Date().toISOString() })],
    });
    assert.ok(!ctx.includes(WIP_HEADER), 'a register with no active rows must not print the block');
  });

  test('no register at all is silence, not an error', () => {
    const ctx = runHook({});
    assert.ok(!ctx.includes(WIP_HEADER), 'an unused register must not print anything');
  });
});

describe('session-start — publishing-slot vacancy (N13/A1-10)', () => {
  test('names the next open slot when the grid has an uncovered day', () => {
    const target = isoDaysAhead(3);
    const ctx = runHook({ slots: [{ day: weekdayOf(target), time: '12:00', label: 'long-form' }] });
    assert.ok(ctx.includes(SLOTS_HEADER), 'expected the slots block');
    assert.ok(ctx.includes(NEXT_OPEN), 'expected the next open slot to be named');
    assert.ok(ctx.includes('long-form'), 'expected the operator label to carry through');
  });

  test('an unconfigured grid says nothing at all — no default schedule is imposed', () => {
    const ctx = runHook({ editions: [activeRow()] });
    assert.ok(!ctx.includes(SLOTS_HEADER), 'no slots config => no slots block');
  });

  test('a queue entry on the slot date covers it', () => {
    const today = new Date().toISOString().slice(0, 10);
    const day = weekdayOf(today);
    // A weekly slot has exactly two occurrences in a 14-day window from today.
    const ctx = runHook({
      slots: [{ day, time: '08:30' }],
      queue: [
        { id: 'a', scheduled_date: today, scheduled_time: '08:30', status: 'scheduled' },
        { id: 'b', scheduled_date: isoDaysAhead(7), scheduled_time: '08:30', status: 'scheduled' },
      ],
    });
    assert.ok(ctx.includes(SLOTS_HEADER), 'a configured grid still reports');
    assert.ok(!ctx.includes(NEXT_OPEN), 'a fully covered horizon has no open slot to name');
    assert.ok(/are covered/.test(ctx), 'expected the all-covered confirmation');
  });

  test('a scheduled long-form edition covers its claimed slot', () => {
    const today = new Date().toISOString().slice(0, 10);
    const day = weekdayOf(today);
    const ctx = runHook({
      slots: [{ day, time: '08:30' }],
      editions: [
        activeRow({ slot: `${today} 08:30` }),
        activeRow({ editionId: '06', slot: `${isoDaysAhead(7)} 08:30` }),
      ],
    });
    assert.ok(!ctx.includes(NEXT_OPEN), 'register-claimed slots count as covered');
  });

  test('an imminent empty slot (<=3 days) says how to fill it', () => {
    const target = isoDaysAhead(2);
    const ctx = runHook({ slots: [{ day: weekdayOf(target), time: '09:00' }] });
    assert.ok(/\/linkedin:newsletter/.test(ctx), 'expected the fill-it pointer for an imminent vacancy');
  });
});

describe('session-start — N13 leaves the existing nudges intact', () => {
  test('the trend-staleness (discovery) nudge still fires alongside the new blocks', () => {
    const ctx = runHook({
      slots: [{ day: weekdayOf(isoDaysAhead(3)), time: '12:00' }],
      editions: [activeRow()],
      trends: [
        {
          id: 't1',
          title: 'A trend',
          url: 'https://example.com/1',
          source: 'tavily',
          capturedAt: isoDaysAgo(10),
          topics: ['x'],
        },
      ],
    });
    assert.ok(ctx.includes('Trend signals are'), 'the discovery nudge must survive N13');
    assert.ok(ctx.includes(SLOTS_HEADER) && ctx.includes(WIP_HEADER), 'the new blocks render too');
  });
});
