#!/usr/bin/env node

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

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const packageJson = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));

function printHelp() {
  const lines = [
    'mcp-oracle-custom',
    '',
    'Servidor MCP Oracle via stdio.',
    '',
    'Uso:',
    '  mcp-oracle-custom',
    '  mcp-oracle-custom --env-file /caminho/para/.env',
    '  mcp-oracle-custom --help',
    '  mcp-oracle-custom --version',
    '',
    'Opcoes:',
    '  --env-file <arquivo>  Informa um arquivo .env externo para o servidor.',
    '  --help                Exibe esta ajuda.',
    '  --version             Exibe a versao do pacote.'
  ];

  process.stdout.write(lines.join('\n') + '\n');
}

function fail(message) {
  process.stderr.write(String(message || 'Falha ao iniciar o MCP Oracle.') + '\n');
  process.exit(1);
}

function resolveCliEnvFile(value) {
  const normalized = String(value || '').trim();
  if (!normalized) {
    return '';
  }

  return path.resolve(process.cwd(), normalized);
}

const args = process.argv.slice(2);

for (let index = 0; index < args.length; index += 1) {
  const current = args[index];

  if (current == '--help' || current == '-h') {
    printHelp();
    process.exit(0);
  }

  if (current == '--version' || current == '-v') {
    process.stdout.write(String(packageJson.version || '0.0.0') + '\n');
    process.exit(0);
  }

  if (current == '--env-file') {
    const nextValue = args[index + 1];
    if (!nextValue) {
      fail('Informe o caminho apos --env-file.');
    }

    process.env.MCP_ORACLE_ENV_FILE = resolveCliEnvFile(nextValue);
    index += 1;
    continue;
  }

  fail('Opcao nao suportada: ' + current);
}

await import('./server.mjs');