#!/usr/bin/env node
import { existsSync, readFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { join, resolve } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';

const __dirname = fileURLToPath(new URL('.', import.meta.url));

// Check for versioned install
const AIKIT_HOME = join(homedir(), '.aikit');
const CURRENT_VERSION_FILE = join(AIKIT_HOME, 'current-version.json');

let cliPath;
if (existsSync(CURRENT_VERSION_FILE)) {
  try {
    const { version } = JSON.parse(readFileSync(CURRENT_VERSION_FILE, 'utf-8'));
    const verDir = join(AIKIT_HOME, 'versions', `v${version}`);
    cliPath = join(verDir, 'packages', 'cli', 'dist', 'index.js');
    if (!existsSync(cliPath)) {
      // Fallback to bundled path if version dir is incomplete
      cliPath = resolve(__dirname, '..', 'packages', 'cli', 'dist', 'index.js');
    }
  } catch {
    // Fallback to bundled path on any parse error
    cliPath = resolve(__dirname, '..', 'packages', 'cli', 'dist', 'index.js');
  }
} else {
  // Fallback to bundled path
  cliPath = resolve(__dirname, '..', 'packages', 'cli', 'dist', 'index.js');
}

const cli = await import(pathToFileURL(cliPath).href);
await cli.run(process.argv.slice(2));
