/**
 * Tests for the skill installer rework (IUV-02-03).
 *
 * We mock `node:child_process` to verify that:
 *   1. syncSkills passes MOSAIC_INSTALL_SKILLS with the exact selected subset
 *   2. When the script exits non-zero, the failure is surfaced to the user
 *   3. When the script is missing, a clear error is shown (not a silent no-op)
 *   4. An empty selection is a no-op (script never called)
 */

import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import type { WizardState } from '../types.js';
import type { ConfigService } from '../config/config-service.js';

// ── spawnSync mock ─────────────────────────────────────────────────────────────

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const spawnSyncMock = vi.fn<any>();

vi.mock('node:child_process', () => ({
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  spawnSync: (...args: any[]) => spawnSyncMock(...args),
}));

// ── platform stub ──────────────────────────────────────────────────────────────

vi.mock('../platform/detect.js', () => ({
  getShellProfilePath: () => null,
}));

import { finalizeStage } from './finalize.js';

// ── Helpers ────────────────────────────────────────────────────────────────────

function makeState(mosaicHome: string, selectedSkills: string[] = []): WizardState {
  return {
    mosaicHome,
    sourceDir: mosaicHome,
    mode: 'quick',
    installAction: 'fresh',
    soul: { agentName: 'TestBot', communicationStyle: 'direct' },
    user: {},
    tools: {},
    runtimes: { detected: [], mcpConfigured: false },
    selectedSkills,
  };
}

function buildPrompter() {
  return {
    intro: vi.fn(),
    outro: vi.fn(),
    note: vi.fn(),
    log: vi.fn(),
    warn: vi.fn(),
    text: vi.fn(),
    confirm: vi.fn(),
    select: vi.fn(),
    multiselect: vi.fn(),
    groupMultiselect: vi.fn(),
    spinner: vi.fn().mockReturnValue({ update: vi.fn(), stop: vi.fn() }),
    separator: vi.fn(),
  };
}

function makeConfigService(): ConfigService {
  return {
    readSoul: vi.fn().mockResolvedValue({}),
    readUser: vi.fn().mockResolvedValue({}),
    readTools: vi.fn().mockResolvedValue({}),
    writeSoul: vi.fn().mockResolvedValue(undefined),
    writeUser: vi.fn().mockResolvedValue(undefined),
    writeTools: vi.fn().mockResolvedValue(undefined),
    syncFramework: vi.fn().mockResolvedValue(undefined),
    get: vi.fn(),
    set: vi.fn(),
    getSection: vi.fn(),
  } as unknown as ConfigService;
}

// ── Tests ──────────────────────────────────────────────────────────────────────

describe('finalizeStage — skill installer', () => {
  let tmp: string;
  let binDir: string;
  let syncScript: string;

  beforeEach(() => {
    tmp = mkdtempSync(join(tmpdir(), 'mosaic-finalize-'));
    binDir = join(tmp, 'bin');
    mkdirSync(binDir, { recursive: true });
    syncScript = join(binDir, 'mosaic-sync-skills');

    // Default: script exists and succeeds
    writeFileSync(syncScript, '#!/usr/bin/env bash\necho ok\n', { mode: 0o755 });
    spawnSyncMock.mockReturnValue({ status: 0, stdout: 'ok', stderr: '' });
  });

  afterEach(() => {
    rmSync(tmp, { recursive: true, force: true });
    vi.clearAllMocks();
  });

  function findSkillsSyncCall() {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    return (spawnSyncMock.mock.calls as any[][]).find(
      (args) =>
        Array.isArray(args[1]) &&
        (args[1] as string[]).some((a) => a.includes('mosaic-sync-skills')),
    );
  }

  it('passes MOSAIC_INSTALL_SKILLS with the selected skill list', async () => {
    const state = makeState(tmp, ['brainstorming', 'lint', 'systematic-debugging']);
    const p = buildPrompter();
    const config = makeConfigService();

    await finalizeStage(p, state, config);

    const call = findSkillsSyncCall();
    expect(call).toBeDefined();
    const opts = call![2] as { env?: Record<string, string> };
    expect(opts.env?.['MOSAIC_INSTALL_SKILLS']).toBe('brainstorming:lint:systematic-debugging');
  });

  it('skips the sync script entirely when no skills are selected', async () => {
    const state = makeState(tmp, []);
    const p = buildPrompter();
    const config = makeConfigService();

    await finalizeStage(p, state, config);

    expect(findSkillsSyncCall()).toBeUndefined();
  });

  it('warns the user when the sync script exits non-zero', async () => {
    spawnSyncMock.mockReturnValue({
      status: 1,
      stdout: '',
      stderr: 'git clone failed: connection refused',
    });

    const state = makeState(tmp, ['brainstorming']);
    const p = buildPrompter();
    const config = makeConfigService();

    await finalizeStage(p, state, config);

    expect(p.warn).toHaveBeenCalledWith(expect.stringContaining('git clone failed'));
    expect(p.warn).toHaveBeenCalledWith(expect.stringContaining('mosaic sync'));
  });

  it('warns the user when the sync script is missing', async () => {
    // Remove the script to simulate a missing installation
    rmSync(syncScript);

    const state = makeState(tmp, ['brainstorming']);
    const p = buildPrompter();
    const config = makeConfigService();

    await finalizeStage(p, state, config);

    // spawnSync should NOT have been called for the skills script
    expect(findSkillsSyncCall()).toBeUndefined();
    expect(p.warn).toHaveBeenCalledWith(expect.stringContaining('not found'));
  });

  it('includes skills count in the summary when install succeeds', async () => {
    const state = makeState(tmp, ['brainstorming', 'lint']);
    const p = buildPrompter();
    const config = makeConfigService();

    await finalizeStage(p, state, config);

    const noteMock = p.note as ReturnType<typeof vi.fn>;
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const summaryCall = (noteMock.mock.calls as any[][]).find(
      ([, title]) => title === 'Installation Summary',
    );
    expect(summaryCall).toBeDefined();
    expect(summaryCall![0] as string).toContain('2 installed');
  });
});
