'use strict';

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

const APP_ROOT = path.join(__dirname, '..', '..');

function resolveRuntimeConfigPath() {
  if (process.env.CONFIG_PATH) return process.env.CONFIG_PATH;
  const installedConfig = path.join(process.env.ProgramData || 'C:\\ProgramData', 'ARKHON', 'Agent', 'config');
  if (fs.existsSync(installedConfig)) return installedConfig;
  return path.join(APP_ROOT, 'config');
}

function loadDotEnv() {
  const runtimeEnvPath = process.env.ARKHON_ENV_PATH
    || path.join(process.env.ProgramData || 'C:\\ProgramData', 'ARKHON', 'app', '.env');
  if (fs.existsSync(runtimeEnvPath)) require('dotenv').config({ path: runtimeEnvPath });
  else require('dotenv').config();
}

function loadConnectorIdentityFromConfig() {
  const connectorPath = path.join(resolveRuntimeConfigPath(), 'connector.json');
  if (!fs.existsSync(connectorPath)) return;
  try {
    const connector = JSON.parse(fs.readFileSync(connectorPath, 'utf8'));
    const assign = (envKey, ...candidates) => {
      if (process.env[envKey]) return;
      const value = candidates.find((item) => item !== undefined && item !== null && String(item).trim() !== '');
      if (value !== undefined && value !== null) process.env[envKey] = String(value);
    };
    assign('ARKHON_CLOUD_BASE_URL', connector.cloud_url, connector.cloudUrl);
    assign('ARKHON_TENANT_ID', connector.tenant_id, connector.tenantId, connector.workspace_id, connector.workspaceId);
    assign('ARKHON_BRANCH_ID', connector.branch_id, connector.branchId);
    assign('ARKHON_BRANCH_CODE', connector.branch_code, connector.branchCode, connector.branch_name, connector.branchName);
    assign('ARKHON_BRANCH_SLUG', connector.branch_slug, connector.branchSlug);
    assign('ARKHON_BRANCH_NAME', connector.branch_name, connector.branchName);
    assign('ARKHON_CONNECTOR_ID', connector.connector_id, connector.connectorId, connector.agent_id, connector.agentId);
    assign('ARKHON_AGENT_ID', connector.agent_id, connector.agentId, connector.connector_id, connector.connectorId);
    assign('ARKHON_CONNECTOR_KEY_ID', connector.connector_key_id, connector.connectorKeyId, connector.agent_key_id, connector.agentKeyId);
    assign('ARKHON_AGENT_KEY_ID', connector.agent_key_id, connector.agentKeyId, connector.connector_key_id, connector.connectorKeyId);
    assign('ARKHON_DEVICE_ID', connector.device_id, connector.deviceId);
    assign('ARKHON_INSTALL_ID', connector.install_id, connector.installId);
  } catch (error) {
    console.warn('[ARKHON] No se pudo cargar connector.json:', error.message);
  }
}

function ensureJwtSecret() {
  if (process.env.JWT_SECRET) return;
  const secret = crypto.randomBytes(48).toString('hex');
  try {
    fs.appendFileSync(path.join(APP_ROOT, '.env'), `\nJWT_SECRET=${secret}\n`, 'utf8');
    process.env.JWT_SECRET = secret;
    console.log('[ARKHON] JWT_SECRET generado automaticamente y guardado en .env');
  } catch (_) {
    process.env.JWT_SECRET = secret;
    console.warn('[ARKHON] JWT_SECRET generado en memoria (no se pudo escribir .env)');
  }
}

function injectEncryptedCredentials() {
  try {
    const { injectCredentials } = require('../utils/credentialStore');
    const configPath = resolveRuntimeConfigPath();
    for (const filename of ['db.enc', 'connector-secret.enc', 'cloudflare-tunnel.enc']) {
      injectCredentials(path.join(configPath, filename));
    }
  } catch (_) {}
}

function initializeEnvironment() {
  loadDotEnv();
  loadConnectorIdentityFromConfig();
  ensureJwtSecret();
  injectEncryptedCredentials();
}

module.exports = {
  initializeEnvironment,
  resolveRuntimeConfigPath,
  loadConnectorIdentityFromConfig,
};
