const fs = require('fs');
const path = require('path');
const os = require('os');

function getLocalIPv4() {
  const nets = os.networkInterfaces();
  let candidate = null;
  for (const name of Object.keys(nets)) {
    for (const net of nets[name] || []) {
      if (net.family === 'IPv4' && !net.internal) {
        // Prefer private ranges
        if (net.address.startsWith('192.168.') || net.address.startsWith('10.') || net.address.startsWith('172.')) {
          return net.address;
        }
        candidate = candidate || net.address;
      }
    }
  }
  return candidate || '127.0.0.1';
}

function main() {
  const host = process.env.CAP_SERVER_HOST || getLocalIPv4();
  const port = process.env.CAP_SERVER_PORT || '8001';
  const pathSuffix = process.env.CAP_SERVER_PATH || '/mobile/';
  const url = `http://${host}:${port}${pathSuffix}`;

  const configPath = path.resolve(__dirname, '..', 'capacitor.config.json');
  if (!fs.existsSync(configPath)) {
    console.error('capacitor.config.json não encontrado:', configPath);
    process.exit(1);
  }

  const json = JSON.parse(fs.readFileSync(configPath, 'utf8'));
  json.server = json.server || {};
  json.server.url = url;
  json.server.cleartext = true;

  fs.writeFileSync(configPath, JSON.stringify(json, null, 2));
  console.log('Servidor remoto configurado para:', url);
}

main();