import os from 'os';
import path from 'path';
import { isTestWorkspacePath, resolveGenerationProjectDir, inferProjectName, sanitizeProjectName, shouldDefaultToTestProject } from './src/tools/vl-generate.js';

let passed = 0;
let failed = 0;

function test(name, fn) {
  return Promise.resolve()
    .then(fn)
    .then(() => {
      console.log(`  ✓ ${name}`);
      passed++;
    })
    .catch((err) => {
      console.log(`  ✗ ${name}: ${err.message}`);
      failed++;
    });
}

function assertEqual(actual, expected, msg) {
  if (actual !== expected) {
    throw new Error(msg || `Expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`);
  }
}

console.log('\n── VLGenerate Targeting Regression ──');

const home = os.homedir();
const testWorkspace = path.join(home, 'Documents', 'VLProjects', '_tests', 'CampusApp');
const prodWorkspace = path.join(home, 'Documents', 'VLProjects', 'CampusApp');

await test('test workspace detection recognizes _tests paths', async () => {
  assertEqual(isTestWorkspacePath(testWorkspace), true);
  assertEqual(isTestWorkspacePath(prodWorkspace), false);
});

await test('generation stays inside the current test workspace when projectName matches', async () => {
  const resolved = resolveGenerationProjectDir({
    currentWorkDir: testWorkspace,
    projectName: 'CampusApp',
    isTest: null,
  });
  assertEqual(resolved, testWorkspace);
});

await test('generation inherits _tests parent for new projects when current workspace is a test project', async () => {
  const resolved = resolveGenerationProjectDir({
    currentWorkDir: testWorkspace,
    projectName: 'NewCampusApp',
    isTest: null,
  });
  assertEqual(resolved, path.join(home, 'Documents', 'VLProjects', '_tests', 'NewCampusApp'));
});

await test('explicit production target overrides inferred test parent', async () => {
  const resolved = resolveGenerationProjectDir({
    currentWorkDir: testWorkspace,
    projectName: 'CampusApp',
    isTest: false,
  });
  assertEqual(resolved, prodWorkspace);
});

await test('sanitizeProjectName converts mixed text into PascalCase English-only names', async () => {
  assertEqual(sanitizeProjectName('campus app demo'), 'CampusAppDemo');
  assertEqual(sanitizeProjectName('Campus-App'), 'CampusApp');
});

await test('inferProjectName extracts English names from mixed-language prompts', async () => {
  assertEqual(inferProjectName('做一个 CampusFlow 项目用于测试'), 'CampusFlow');
  assertEqual(inferProjectName('Create a StudyHub app for teachers'), 'StudyHub');
});

await test('shouldDefaultToTestProject detects demo/test requests', async () => {
  assertEqual(shouldDefaultToTestProject('做一个测试 demo 应用', ''), true);
  assertEqual(shouldDefaultToTestProject('创建正式生产项目', ''), false);
});

console.log(`\n── Results ──\n\n  ${passed} passed, ${failed} failed\n`);
process.exit(failed > 0 ? 1 : 0);
