import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { mkdtempSync, rmSync, existsSync, readFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { scaffoldCaseSpace, removeSpaceDirs, defaultAgentsMd } from './scaffold.js';

describe('scaffoldCaseSpace', () => {
  let root: string;
  beforeEach(() => { root = mkdtempSync(join(tmpdir(), 'scaffold-')); });
  afterEach(() => { rmSync(root, { recursive: true, force: true }); });

  it('creates folder + workspace skeleton with an AGENTS.md and mcp.json', () => {
    const dataRoot = join(root, 'data');
    const wt = join(root, 'wt');
    scaffoldCaseSpace({ dataRoot, worktreeDir: wt, id: 'sp1', title: '案件A' });

    expect(existsSync(join(dataRoot, 'spaces', 'sp1', 'AGENTS.md'))).toBe(true);
    expect(existsSync(join(dataRoot, 'spaces', 'sp1', 'pieces'))).toBe(true);
    expect(existsSync(join(dataRoot, 'spaces', 'sp1', 'memory'))).toBe(true);
    expect(existsSync(join(dataRoot, 'spaces', 'sp1', 'mcp.json'))).toBe(true);
    expect(existsSync(join(wt, 'space', 'sp1', 'files'))).toBe(true);
    expect(existsSync(join(wt, 'space', 'sp1', 'files', 'input'))).toBe(true);
    expect(existsSync(join(wt, 'space', 'sp1', 'files', 'output'))).toBe(true);
    expect(existsSync(join(wt, 'space', 'sp1', 'logs'))).toBe(true);
    expect(JSON.parse(readFileSync(join(dataRoot, 'spaces', 'sp1', 'mcp.json'), 'utf-8'))).toEqual({ mcpServers: {} });
  });

  it('default AGENTS.md embeds the title and the core feature guidance', () => {
    const md = defaultAgentsMd('案件A');
    expect(md).toContain('# 案件A');
    // 実機能への導線が最初から織り込まれていること
    expect(md).toContain('AGENTS.md を育てる');
    expect(md).toContain('UpdateUserMemory');
    expect(md).toContain('AddCalendarEvent');
    expect(md).toContain('ReadSkill');
    expect(md).toContain('workspace-apps');
  });

  it('removeSpaceDirs cleans both data and workspace dirs (rollback)', () => {
    const dataRoot = join(root, 'data');
    const wt = join(root, 'wt');
    scaffoldCaseSpace({ dataRoot, worktreeDir: wt, id: 'sp2', title: 'x' });
    removeSpaceDirs({ dataRoot, worktreeDir: wt, id: 'sp2' });
    expect(existsSync(join(dataRoot, 'spaces', 'sp2'))).toBe(false);
    expect(existsSync(join(wt, 'space', 'sp2'))).toBe(false);
  });
});
