import { mkdirSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { findWorkspaceRoot } from '../config/cwrc.js';

/**
 * Get the database path.
 *
 * - Default: <workspace-root>/.cw/cw.db
 * - Throws if no .cwrc workspace is found
 * - Override via CW_DB_PATH environment variable
 * - For testing, pass ':memory:' as CW_DB_PATH
 */
export function getDbPath(): string {
  const envPath = process.env.CW_DB_PATH;
  if (envPath) {
    return envPath;
  }

  const root = findWorkspaceRoot();
  if (!root) {
    throw new Error(
      'No .cwrc workspace found. Run `cw init` to initialize a workspace.',
    );
  }
  return join(root, '.cw', 'cw.db');
}

/**
 * Ensure the parent directory for the database file exists.
 * No-op for in-memory databases.
 */
export function ensureDbDirectory(dbPath: string): void {
  // Skip for in-memory database
  if (dbPath === ':memory:') {
    return;
  }

  const dir = dirname(dbPath);
  mkdirSync(dir, { recursive: true });
}
