/**
 * @module utils/version
 * @description Resolves the running `@soulcraft/brainy` package version. Brainy 8.0
 * targets Node-like runtimes only (Node.js, Bun, Deno — all expose `node:fs`), so the
 * version is read **synchronously** from `package.json` on first call and cached.
 *
 * The synchronous read is load-bearing: `loadPlugins()` is the first step of `init()`
 * and reads the version to drive the brainy↔provider version-coupling guard
 * (`plugin.ts` → `pluginRangeSatisfies`). A deferred/async value would return a stale
 * default on that first synchronous call and spuriously reject a correctly-matched
 * native provider (e.g. cor 3.x declaring `>=8.0.0`). Reading synchronously removes
 * that window entirely.
 */

import { readFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { isNode } from './environment.js'

/**
 * Last-resort sentinel, returned only if `package.json` cannot be read at all
 * (a non-Node runtime, or a genuinely broken install). It is intentionally an
 * "unknown" `0.0.0` rather than a plausible-looking release, so a real read
 * failure can never masquerade as a valid version and silently satisfy a
 * coupling range — it will fail loud instead.
 */
const UNKNOWN_VERSION = '0.0.0'

let cachedVersion: string | null = null

/**
 * Synchronously read `version` from the package's own `package.json`. The path
 * `../../package.json` resolves to the package root from both `src/utils/` (dev)
 * and `dist/utils/` (published).
 */
function readVersionSync(): string {
  if (!isNode()) return UNKNOWN_VERSION
  try {
    const here = dirname(fileURLToPath(import.meta.url))
    const pkg = JSON.parse(readFileSync(join(here, '../../package.json'), 'utf8'))
    return typeof pkg.version === 'string' && pkg.version.length > 0
      ? pkg.version
      : UNKNOWN_VERSION
  } catch {
    return UNKNOWN_VERSION
  }
}

/**
 * @description The running Brainy package version, read synchronously from
 * `package.json` and cached. Correct on the **first** call — including the
 * version-coupling check during `init()` — with no async warm-up.
 * @returns The semver version string (e.g. `"8.0.0"`).
 * @example
 * const v = getBrainyVersion() // "8.0.0"
 */
export function getBrainyVersion(): string {
  if (cachedVersion === null) cachedVersion = readVersionSync()
  return cachedVersion
}

/**
 * @description Async accessor retained for API compatibility. The version is
 * resolved synchronously, so this returns the same value as
 * {@link getBrainyVersion} — there is no longer any deferred state.
 * @returns A promise resolving to the version string.
 */
export async function getBrainyVersionAsync(): Promise<string> {
  return getBrainyVersion()
}

/**
 * @description Build the version-metadata object stamped onto augmentation /
 * provenance records.
 * @param service - The augmentation or service name to record.
 * @returns `{ augmentation, version }` carrying the current package version.
 * @example
 * getAugmentationVersion('aggregation') // { augmentation: 'aggregation', version: '8.0.0' }
 */
export function getAugmentationVersion(service: string): { augmentation: string; version: string } {
  return {
    augmentation: service,
    version: getBrainyVersion()
  }
}
