// config/env.ts
// Copyright (C) 2026 Rob Colbert <rob.colbert@openplatform.us>
// Licensed under the Apache License, Version 2.0

import path, { dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { loadGadgetDroneConfig, resolvePath } from "@gadget/config";
import type PackageJson from "../../package.json";
import { GadgetLog, GadgetLogFile } from "@gadget/api";

const __dirname = dirname(fileURLToPath(import.meta.url));

// INSTALL_DIR: where the package is installed (for loading assets, etc.)
export const INSTALL_DIR = path.resolve(__dirname, "..", "..");

// Load YAML configuration
const yamlConfig = loadGadgetDroneConfig();

// Validate required fields
if (!yamlConfig.platform?.baseUrl) {
  throw new Error(
    "Configuration error: platform.baseUrl is required in gadget-drone.yaml\n" +
      "See documentation: ./docs/configuration.md",
  );
}
if (!yamlConfig.platform?.gadgetKey) {
  throw new Error(
    "Configuration error: platform.gadgetKey is required in gadget-drone.yaml\n" +
      "See documentation: ./docs/configuration.md",
  );
}

async function readJsonFile<T>(filePath: string): Promise<T> {
  const fs = await import("node:fs");
  const file = await fs.promises.readFile(filePath);
  return JSON.parse(file.toString("utf-8")) as T;
}

/* eslint-disable no-process-env */
export default {
  NODE_ENV: process.env.NODE_ENV || "develop",
  timezone: yamlConfig.timezone || "America/New_York",
  installDir: INSTALL_DIR,
  pkg: await readJsonFile<typeof PackageJson>(
    path.join(INSTALL_DIR, "package.json"),
  ),
  platform: {
    baseUrl: yamlConfig.platform.baseUrl,
    gadgetKey: yamlConfig.platform.gadgetKey,
  },
  google: {
    cse: {
      apiKey: yamlConfig.google?.cse?.apiKey,
      engineId: yamlConfig.google?.cse?.engineId,
    },
  },
  log: {
    console: {
      enabled: yamlConfig.logging?.console?.enabled === true,
    },
    file: {
      enabled: yamlConfig.logging?.file?.enabled === true,
      path: yamlConfig.logging?.file?.path
        ? resolvePath(yamlConfig.logging.file.path)
        : path.join(INSTALL_DIR, "logs"),
      name: yamlConfig.logging?.file?.name || "gadget-drone",
      maxWritesPerFile: yamlConfig.logging?.file?.maxWritesPerFile || 10000,
      maxFiles: yamlConfig.logging?.file?.maxFiles || 10,
    },
    levels: {
      debug: yamlConfig.logging?.levels?.debug === true,
      info: yamlConfig.logging?.levels?.info === true,
      warn: yamlConfig.logging?.levels?.warn === true,
    },
  },
};

// Configure GadgetLog for this package
GadgetLog.consoleEnabled = yamlConfig.logging?.console?.enabled === true;
if (yamlConfig.logging?.file?.enabled === true) {
  const logFileOptions = {
    basePath: yamlConfig.logging.file.path
      ? resolvePath(yamlConfig.logging.file.path)
      : path.join(INSTALL_DIR, "logs"),
    name: yamlConfig.logging.file.name || "gadget-drone",
    maxWritesPerFile: yamlConfig.logging.file.maxWritesPerFile || 10000,
    maxFiles: yamlConfig.logging.file.maxFiles || 10,
  };
  const defaultLogFile = new GadgetLogFile(logFileOptions);
  defaultLogFile.open();
  GadgetLog.defaultFile = defaultLogFile;
}

/* eslint-enable no-process-env */
