/**
 * .cwrc File Operations
 *
 * Find, read, and write the .cwrc configuration file.
 * The file's presence marks the workspace root directory.
 */

import { readFileSync, writeFileSync, existsSync } from 'node:fs';
import { join, dirname, parse } from 'node:path';
import type { CwConfig } from './types.js';

/** Default filename */
const CWRC_FILENAME = '.cwrc';

/**
 * Walk up from `startDir` looking for a .cwrc file.
 * Returns the absolute path to the directory containing it,
 * or null if the filesystem root is reached.
 */
export function findWorkspaceRoot(startDir: string = process.cwd()): string | null {
  let dir = startDir;

  while (true) {
    const candidate = join(dir, CWRC_FILENAME);
    if (existsSync(candidate)) {
      return dir;
    }

    const parent = dirname(dir);
    if (parent === dir) {
      // Reached filesystem root
      return null;
    }
    dir = parent;
  }
}

/**
 * Read and parse the .cwrc file in the given directory.
 * Returns null if the file doesn't exist.
 * Throws on malformed JSON.
 */
export function readCwrc(dir: string): CwConfig | null {
  const filePath = join(dir, CWRC_FILENAME);
  if (!existsSync(filePath)) {
    return null;
  }

  const raw = readFileSync(filePath, 'utf-8');
  return JSON.parse(raw) as CwConfig;
}

/**
 * Write a .cwrc file to the given directory.
 */
export function writeCwrc(dir: string, config: CwConfig): void {
  const filePath = join(dir, CWRC_FILENAME);
  writeFileSync(filePath, JSON.stringify(config, null, 2) + '\n', 'utf-8');
}

/**
 * Create a default .cwrc config.
 */
export function defaultCwConfig(): CwConfig {
  return { version: 1 };
}
