#!/usr/bin/env node

import path from 'node:path';
import process from 'node:process';
import { fileURLToPath } from 'node:url';

import { resolveLiveSmokeOrchestratorCliPath } from './lib/live-smoke-runtime.mjs';
import {
  exitForSkippedPreflight,
  preflightOpenCodeLiveEnvironment,
} from './lib/opencode-live-preflight.mjs';
import { spawnSyncWithWindowsShell } from './lib/windows-shell-spawn.mjs';

const scriptDir = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(scriptDir, '..');

const env = {
  ...process.env,
  OPENCODE_E2E: '1',
  OPENCODE_E2E_TEAM_PROVISIONING: '1',
  OPENCODE_E2E_PROJECT_PATH: process.env.OPENCODE_E2E_PROJECT_PATH?.trim() || repoRoot,
  OPENCODE_E2E_MODEL: process.env.OPENCODE_E2E_MODEL?.trim() || 'opencode/big-pickle',
  OPENCODE_DISABLE_AUTOUPDATE: process.env.OPENCODE_DISABLE_AUTOUPDATE ?? '1',
};

if (!env.CLAUDE_AGENT_TEAMS_ORCHESTRATOR_CLI_PATH?.trim()) {
  env.CLAUDE_AGENT_TEAMS_ORCHESTRATOR_CLI_PATH = resolveLiveSmokeOrchestratorCliPath({
    env,
    repoRoot,
  });
}

console.log('Running OpenCode team provisioning live smoke');
console.log(`Model: ${env.OPENCODE_E2E_MODEL}`);
console.log(`Project: ${env.OPENCODE_E2E_PROJECT_PATH}`);
console.log(`Orchestrator CLI: ${env.CLAUDE_AGENT_TEAMS_ORCHESTRATOR_CLI_PATH}`);

const preflight = await preflightOpenCodeLiveEnvironment({ repoRoot });
exitForSkippedPreflight(preflight);

const result = spawnSyncWithWindowsShell(
  'pnpm',
  [
    'exec',
    'vitest',
    'run',
    '--maxWorkers=1',
    'test/main/services/team/OpenCodeTeamProvisioning.live.test.ts',
  ],
  {
    cwd: repoRoot,
    env,
    stdio: 'inherit',
  }
);

if (result.error) {
  console.error(`Failed to run OpenCode team provisioning smoke: ${result.error.message}`);
  process.exit(1);
}

process.exit(result.status ?? 1);
