import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { projectRoot } from './env.js';

function bool(name, fallback = false) {
  const raw = process.env[name];
  if (raw == null || raw === '') return fallback;
  return ['1', 'true', 'yes', 'on', 'evet'].includes(String(raw).trim().toLowerCase());
}

function integer(name, fallback) {
  const value = Number.parseInt(process.env[name] ?? '', 10);
  return Number.isFinite(value) ? value : fallback;
}

const dataDir = path.resolve(projectRoot, process.env.DATA_DIR || 'data');
const installLockPath = path.join(dataDir, 'installed.json');
const installed = fs.existsSync(installLockPath);
const environment = process.env.NODE_ENV || (installed ? 'production' : 'installation');
const isProduction = installed && environment === 'production';
const ephemeralSecret = crypto.randomBytes(48).toString('base64url');

export const config = Object.freeze({
  rootDir: projectRoot,
  appVersion: process.env.APP_VERSION || '1.1.0',
  host: process.env.HOST || '0.0.0.0',
  port: integer('PORT', 8787),
  appOrigin: process.env.APP_ORIGIN || `http://127.0.0.1:${integer('PORT', 8787)}`,
  dataDir,
  dbPath: path.join(dataDir, environment === 'test' ? 'onlycoin-test.db' : 'onlycoin.db'),
  installLockPath,
  installTokenPath: path.join(dataDir, 'install.token'),
  authSecret: process.env.AUTH_SECRET || ephemeralSecret,
  telegramBotToken: process.env.TELEGRAM_BOT_TOKEN || '',
  telegramWebhookSecret: process.env.TELEGRAM_WEBHOOK_SECRET || '',
  evmRpcUrl: process.env.EVM_RPC_URL || '',
  bitcoinRpcUrl: process.env.BITCOIN_RPC_URL || '',
  bitcoinRpcUser: process.env.BITCOIN_RPC_USER || '',
  bitcoinRpcPassword: process.env.BITCOIN_RPC_PASSWORD || '',
  environment,
  installed,
  trustProxy: bool('TRUST_PROXY', false),
  isProduction
});

if (config.isProduction) {
  if (config.authSecret.length < 43 || /dev|demo|change|test/i.test(config.authSecret)) {
    throw new Error('AUTH_SECRET must be a cryptographically random production value of at least 43 characters.');
  }
  if (!/^https:\/\//i.test(config.appOrigin) && !['127.0.0.1', 'localhost'].includes(new URL(config.appOrigin).hostname)) {
    throw new Error('APP_ORIGIN must use HTTPS in production.');
  }
}
