import { describe, expect, it } from 'vitest';
import { execFileSync } from 'child_process';
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import { commitWorkspaceChanges, ensureWorkspaceGitRepo } from './workspace-manager.js';

describe('workspace-manager', () => {
  it('initializes and commits a local workspace without a remote', async () => {
    const root = mkdtempSync(join(tmpdir(), 'workspace-manager-test-'));
    try {
      mkdirSync(join(root, 'output'), { recursive: true });
      mkdirSync(join(root, 'input'), { recursive: true });
      writeFileSync(join(root, 'output', 'report.md'), '# report\n', 'utf-8');
      writeFileSync(join(root, 'input', 'source.txt'), 'secret\n', 'utf-8');

      await ensureWorkspaceGitRepo(root);
      const result = await commitWorkspaceChanges({
        workspacePath: root,
        branchName: 'main',
        commitMessage: 'agent: update task #1',
        ignoreEntries: ['input/', 'logs/'],
      });

      expect(result.changed).toBe(true);
      expect(result.committed).toBe(true);
      expect(result.pushed).toBe(false);

      const tracked = execFileSync('git', ['ls-files'], { cwd: root, encoding: 'utf-8' });
      expect(tracked).toContain('output/report.md');
      expect(tracked).not.toContain('input/source.txt');

      const excludePath = join(root, '.git', 'info', 'exclude');
      expect(readFileSync(excludePath, 'utf-8')).toContain('input/');
    } finally {
      rmSync(root, { recursive: true, force: true });
    }
  });
});
