// src/constants/chunks/environment.ts
import { existsSync } from "fs";
import { config } from "dotenv";
import * as path from "path";

// src/constants/chunks/sdk-config.ts
var DEFAULT_LIT_NETWORKS = {
  CHIPOTLE: "chipotle"
};
var DEFAULT_LIT_NETWORK = DEFAULT_LIT_NETWORKS.CHIPOTLE;
var VALID_LIT_NETWORKS = [
  DEFAULT_LIT_NETWORKS.CHIPOTLE
];

// src/constants/chunks/environment.ts
var possibleEnvPaths = [
  ".env",
  path.join(__dirname, "../../.env"),
  path.join(__dirname, "../../../.env")
];
var envPathsAttemptedAbs = [];
var envPathsMergedAbs = [];
for (const envPath of possibleEnvPaths) {
  const abs = path.resolve(envPath);
  envPathsAttemptedAbs.push(abs);
  if (!existsSync(abs)) {
    continue;
  }
  try {
    const result = config({ path: abs });
    if (!result.error) {
      envPathsMergedAbs.push(abs);
    }
  } catch {
  }
}
var envDiscoveryLogged = false;
function logEnvDiscoveryOnce() {
  if (envDiscoveryLogged) {
    return;
  }
  envDiscoveryLogged = true;
  if (process.env.DEBUG_SDK !== "true") {
    return;
  }
  console.log("[SDK] .env multi-path load", {
    attempted: envPathsAttemptedAbs,
    mergedFromExistingFiles: envPathsMergedAbs,
    note: "later paths override earlier (dotenv)"
  });
}
logEnvDiscoveryOnce();
function environmentNameFromLitNetwork(_network) {
  return "chipotle";
}
function resolveLitNetworkFromEnv() {
  const env = process.env;
  const raw = env["LIT_NETWORK"];
  if (raw === void 0 || raw === "") {
    return DEFAULT_LIT_NETWORK;
  }
  const network = raw;
  if (!VALID_LIT_NETWORKS.includes(network)) {
    throw new Error(
      `Invalid LIT_NETWORK: "${raw}". Must be one of: ${VALID_LIT_NETWORKS.join(
        ", "
      )}. Omit or leave empty for default "${DEFAULT_LIT_NETWORK}" (production Chipotle).`
    );
  }
  return network;
}
function getCurrentEnvironment() {
  return environmentNameFromLitNetwork(resolveLitNetworkFromEnv());
}
function loadSDKConfig() {
  const env = process.env;
  const litNetwork = resolveLitNetworkFromEnv();
  const environment = environmentNameFromLitNetwork(litNetwork);
  const realLitTesting = env["REAL_LIT_TESTING"] === "true";
  const debugMode = env["DEBUG_SDK"] === "true";
  const runRealIntegrationTests = env["RUN_REAL_INTEGRATION_TESTS"] === "true";
  const litRelayUrl = env["LIT_RELAY_URL"];
  const ethRpcUrl = env["ETH_RPC_URL"];
  const polygonRpcUrl = env["POLYGON_RPC_URL"];
  if (!ethRpcUrl) {
    throw new Error(
      "ETH_RPC_URL environment variable is required for SDK configuration"
    );
  }
  if (!polygonRpcUrl) {
    throw new Error(
      "POLYGON_RPC_URL environment variable is required for SDK configuration"
    );
  }
  const pkpMintPrivateKey = env["PKP_MINT_PRIVATE_KEY"];
  const config2 = {
    environment,
    litNetwork,
    realLitTesting,
    debugMode,
    runRealIntegrationTests,
    ethRpcUrl,
    polygonRpcUrl
  };
  if (litRelayUrl)
    config2.litRelayUrl = litRelayUrl;
  if (pkpMintPrivateKey)
    config2.pkpMintPrivateKey = pkpMintPrivateKey;
  return config2;
}
function envLog(message, ...args) {
  const config2 = loadSDKConfig();
  if (config2.debugMode) {
    console.log(
      `[SDK:${config2.environment.toUpperCase()}] ${message}`,
      ...args
    );
  }
}
function validateSDKEnvironment(requirements) {
  const config2 = loadSDKConfig();
  if (requirements.requiresRealLitTesting && !config2.realLitTesting) {
    throw new Error("REAL_LIT_TESTING=true is required for this operation");
  }
  if (requirements.requiresPrivateKey && !config2.pkpMintPrivateKey) {
    throw new Error(
      "PKP_MINT_PRIVATE_KEY environment variable is required for this operation"
    );
  }
  return config2;
}

// src/constants/chunks/encrypted-provider-params.ts
import * as fs from "fs";
import * as path2 from "path";
var DEFAULT_REGISTRY_PATH = path2.resolve(
  __dirname,
  "../../../config/encrypted-params.sepolia.json"
);
function assertNonEmptyString(value, fieldName, providerName) {
  if (typeof value !== "string" || value.trim().length === 0) {
    const prefix = providerName ? `provider "${providerName}"` : "registry";
    throw new Error(
      `Invalid encrypted params ${prefix}: "${fieldName}" must be a non-empty string`
    );
  }
  return value.trim();
}
function parseRegistry(raw, registryPath) {
  let parsed;
  try {
    parsed = JSON.parse(raw);
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(
      `Failed to parse encrypted params registry at ${registryPath}: ${message}`
    );
  }
  if (!parsed || typeof parsed !== "object") {
    throw new Error(
      `Invalid encrypted params registry at ${registryPath}: expected JSON object`
    );
  }
  const candidate = parsed;
  const network = assertNonEmptyString(candidate.network, "network");
  if (!Array.isArray(candidate.providers) || candidate.providers.length === 0) {
    throw new Error(
      `Invalid encrypted params registry at ${registryPath}: "providers" must be a non-empty array`
    );
  }
  const providers = candidate.providers.map((provider, index) => {
    const p = provider;
    const name = assertNonEmptyString(
      p.name,
      "name",
      `index ${index.toString()}`
    ).toLowerCase();
    const pkpId = assertNonEmptyString(p.pkpId, "pkpId", name);
    const apiKeyEncrypted = assertNonEmptyString(
      p.apiKeyEncrypted,
      "apiKeyEncrypted",
      name
    );
    if (typeof p.version !== "number" || !Number.isFinite(p.version) || p.version < 1) {
      throw new Error(
        `Invalid encrypted params provider "${name}": "version" must be a positive number`
      );
    }
    const updatedAt = assertNonEmptyString(p.updatedAt, "updatedAt", name);
    const normalized = {
      name,
      pkpId,
      apiKeyEncrypted,
      version: p.version,
      updatedAt
    };
    if (p.apiSecretEncrypted !== void 0) {
      normalized.apiSecretEncrypted = assertNonEmptyString(
        p.apiSecretEncrypted,
        "apiSecretEncrypted",
        name
      );
    }
    return normalized;
  });
  return { network, providers };
}
function loadEncryptedProviderRegistry(registryPath = DEFAULT_REGISTRY_PATH) {
  if (!fs.existsSync(registryPath)) {
    throw new Error(`Encrypted params registry file not found: ${registryPath}`);
  }
  const raw = fs.readFileSync(registryPath, "utf8");
  return parseRegistry(raw, registryPath);
}
function getEncryptedPriceProviders(providerNames = ["cryptocompare", "coinmarketcap", "coingecko"], registryPath = DEFAULT_REGISTRY_PATH) {
  const registry = loadEncryptedProviderRegistry(registryPath);
  const desiredNames = providerNames.map((name) => name.trim().toLowerCase());
  const selected = desiredNames.map((name) => {
    const found = registry.providers.find((provider) => provider.name === name);
    if (!found) {
      throw new Error(
        `Encrypted params registry missing provider "${name}" for network "${registry.network}"`
      );
    }
    return {
      name: found.name,
      pkpId: found.pkpId,
      apiKey: found.apiKeyEncrypted,
      apiSecret: found.apiSecretEncrypted
    };
  });
  return selected;
}
export {
  envLog,
  getCurrentEnvironment,
  getEncryptedPriceProviders,
  loadEncryptedProviderRegistry,
  loadSDKConfig,
  resolveLitNetworkFromEnv,
  validateSDKEnvironment
};
