#!/usr/bin/env node
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import { createRequire } from 'node:module';
import { runCli } from 'ai-sdd/dist/index.js';
import { runTui } from './tui.js';
import { runWeb } from './web.js';

function getVersion() {
  try {
    const require = createRequire(import.meta.url);
    const pkg = require('../package.json');
    return pkg.version ?? '1.0.0';
  } catch {
    return '1.0.0';
  }
}

const v = getVersion();
const BANNER = String.raw`
  ___ ___  ___      ___ ___
 / __|   \|   \ ___| __| _ \
 \__ \ |) | |) |___| _||  _/
 |___/___/|___/    |_| |_|
 ============================
 :: SDD-FP ::        (v${v})
`;

console.log(BANNER);

const here = fileURLToPath(new URL('.', import.meta.url));
const packageRoot = path.resolve(here, '..');
const execOpts = { templatesRoot: packageRoot };

const args = process.argv.slice(2);
const isInteractive = process.stdin.isTTY && process.stdout.isTTY;

// sdd-fp web [--port N]
if (args.includes('web')) {
  const portIdx = args.indexOf('--port');
  const port = portIdx !== -1 ? parseInt(args[portIdx + 1], 10) : undefined;
  runWeb({ cwd: process.cwd(), port });
} else if (args.length === 0 && isInteractive) {
  // Default: open web portal when run with no arguments
  runWeb({ cwd: process.cwd() });
} else {
  const exitCode = await runTui(runCli, execOpts, v);
  if (Number.isInteger(exitCode)) process.exit(exitCode);
}
