import fs from 'node:fs';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import process from 'node:process';

/**
 * vite :: src/load-config.mjs.
 *
 * Vite-based build/dev tooling for Vettvangur projects.
 *
 * These docs are generated from inline JSDoc in the repo and are intended for contributors.
 *
 * @generated
 * @module vite
 */


/**
 * Assert a required config field exists.
 * @param {string} name - Human-friendly field path for error messages.
 * @param {unknown} val - Value to validate.
 * @returns {any} The validated value.
 */
function req(name, val) {
  if (val === undefined || val === null) {
    throw new Error(`[vettvangur-vite :: load-config] Missing required config field: ${name}`)
  }
  return val
}

const /**
   * Cfg File.
   *
   * @generated
   * @example
   * console.log(cfgFile)
   */
  cfgFile = path.resolve(process.cwd(), 'vettvangur.config.mjs');
const /**
   * Mod.
   *
   * @generated
   * @example
   * console.log(mod)
   */
  mod = await import(pathToFileURL(cfgFile).href);
const /**
   * Config.
   *
   * @generated
   * @example
   * console.log(config)
   */
  config = mod.default ?? mod;

const /**
   * Root.
   *
   * @generated
   * @example
   * console.log(root)
   */
  root = process.cwd();

/**
 * Paths.
 *
 * @example
 * console.log(paths)
 */
const paths = {
  root,
  dest: path.resolve(root, req('dest', config.dest)),
  public: path.resolve(root, req('public', config.public)),
  assets: path.resolve(root, req('assets', config.assets)),
  styles: path.resolve(root, req('styles.path', config.styles.path)),
  styleEntries: req('styles.entries', config.styles.entries).map((p) =>
    path.isAbsolute(p) ? p : path.resolve(root, p)
  ),
  scripts: path.resolve(root, req('scripts.path', config.scripts.path)),
  scriptEntries: req('scripts.entries', config.scripts.entries).map((p) =>
    path.isAbsolute(p) ? p : path.resolve(root, p)
  ),
  views: path.resolve(root, req('views', config.views)),
  watch: config.watch,
};

function normalizeBase(v) {
  if (v === undefined || v === null) {
    return null
  }
  if (typeof v !== 'string') {
    throw new Error(`[vettvangur-vite :: load-config] Expected config.base to be a string, got: ${typeof v}`)
  }

  let s = v.trim();
  if (!s) {
    return '/'
  }

  s = s.replace(/\\/g, '/');

  if (!s.startsWith('/')) {
    s = `/${s}`;
  }
  if (!s.endsWith('/')) {
    s = `${s}/`;
  }
  return s
}

function inferBaseFromPaths(publicDir, destDir) {
  const rel = path.relative(publicDir, destDir);
  if (!rel || rel === '.') {
    return '/'
  }
  // Only infer if dest is inside public
  if (rel.startsWith('..') || path.isAbsolute(rel)) {
    return null
  }
  return normalizeBase(rel)
}

function inferBaseFromDestBasename(destDir) {
  const base = path.basename(destDir);
  if (!base) {
    return null
  }
  return normalizeBase(base)
}

/**
 * URL base (path prefix) for built assets.
 * - Default: inferred from `public` + `dest` when possible; otherwise from dest basename; otherwise `/build/`.
 * - Override via `base` in `vettvangur.config.mjs`.
 */
const buildBase =
  normalizeBase(config.base) ??
  inferBaseFromPaths(paths.public, paths.dest) ??
  inferBaseFromDestBasename(paths.dest) ??
  '/build/';

// ---- HTTPS (safe, never throws) --------------------------------------------
/**
 * Make https cfg.
 *
 * @param cfg - Value.
 * @returns Result of the operation.
 *
 * @generated
 * @example
 * // vite (src/tools/javascript/vite/src/load-config.mjs)
 * // import { makeHttpsCfg } from '@vettvangur/vite'
 *
 * makeHttpsCfg(cfg)
 */
function makeHttpsCfg(cfg) {
  const ds = cfg?.devserver ?? {};
  const h = ds.https;

  // Explicit off
  if (h === false) {
    return false
  }

  // Preferred shape: https = { key, cert } (buffers) or { keyfile, certfile } (paths)
  if (h && typeof h === 'object') {
    // already-provided buffers
    if (h.key && h.cert) {
      return { key: h.key, cert: h.cert }
    }

    if (h.keyfile && h.certfile) {
      try {
        if (fs.existsSync(h.keyfile) && fs.existsSync(h.certfile)) {
          return {
            key: fs.readFileSync(h.keyfile),
            cert: fs.readFileSync(h.certfile),
          }
        }
      } catch {
        /* swallow */
      }
      return false
    }
  }

  // Legacy shape: devserver.keyfile / devserver.certfile
  if (ds.keyfile && ds.certfile) {
    try {
      if (fs.existsSync(ds.keyfile) && fs.existsSync(ds.certfile)) {
        return {
          key: fs.readFileSync(ds.keyfile),
          cert: fs.readFileSync(ds.certfile),
        }
      }
    } catch {
      /* swallow */
    }
  }

  // Default: no HTTPS
  return false
}

/**
 * Https Cfg.
 *
 * @example
 * console.log(httpsCfg)
 */
const httpsCfg = makeHttpsCfg(config);

// ---- flags -----------------------------------------------------------------
/**
 * Flags.
 *
 * @example
 * console.log(flags)
 */
const flags = {
  useSass: config.styles?.type === 'sass',
  useTailwind: config.styles?.type === 'tailwind',
};

export { buildBase, config as default, flags, httpsCfg, paths };
//# sourceMappingURL=load-config.js.map
