import { CLIProvider } from './src/core/llm-provider.js';
import { createWorkspaceManagerTool } from './src/tools/workspace-manager.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 assert(cond, msg) {
  if (!cond) throw new Error(msg || 'Assertion failed');
}

console.log('\n── Dynamic Port Regression ──');

await test('CLIProvider reads the current config port instead of a startup snapshot', async () => {
  const config = { model: 'claude-opus-4-6', port: 3300 };
  const provider = new CLIProvider(config);
  assert(provider.getServerPort() === 3300, 'expected initial port 3300');
  config.port = 3301;
  assert(provider.getServerPort() === 3301, 'provider should see updated config port');
});

await test('WorkspaceManager uses the latest config port at execution time', async () => {
  const config = { port: 3300 };
  const calls = [];
  const originalFetch = global.fetch;
  global.fetch = async (url) => {
    calls.push(url);
    return {
      ok: true,
      async json() {
        return [];
      },
    };
  };

  try {
    const tool = createWorkspaceManagerTool(config);
    config.port = 3301;
    await tool.execute({ action: 'list' });
  } finally {
    global.fetch = originalFetch;
  }

  assert(calls.length === 1, 'expected one fetch call');
  assert(calls[0] === 'http://localhost:3301/api/workspaces', `unexpected URL: ${calls[0]}`);
});

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