import * as fs from 'fs';
import * as path from 'path';

// Only `.obsidian` reliably marks a vault. `.flywheel` (engine state) and
// `.claude` (Claude config) exist in home dirs and most code repos, so treating
// them as vault markers makes findVaultRoot adopt ~/src or ~ as a "vault" and
// wikilink-enrich every markdown file under it. Explicit env config
// (PROJECT_PATH/VAULT_PATH/OBSIDIAN_VAULT) should win before this fallback runs.
const VAULT_MARKERS = ['.obsidian'];

/**
 * Find vault root by walking up the directory tree.
 * Looks for an .obsidian folder as the marker.
 */
export function findVaultRoot(startPath?: string): string {
  let current = path.resolve(startPath || process.cwd());

  while (true) {
    // Check for vault markers
    for (const marker of VAULT_MARKERS) {
      const markerPath = path.join(current, marker);
      if (fs.existsSync(markerPath) && fs.statSync(markerPath).isDirectory()) {
        return current;
      }
    }

    // Move up one directory
    const parent = path.dirname(current);
    if (parent === current) {
      // Reached filesystem root, fall back to start path or cwd
      return startPath || process.cwd();
    }
    current = parent;
  }
}
