// engine/spec-migrator/git-aware-fs.ts — SPEC-715: git-aware file removal helper
import { unlink } from 'node:fs/promises';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { existsSync } from 'node:fs';
import { join, relative } from 'node:path';
const execFileAsync = promisify(execFile);
/**
 * Remove a file from the filesystem. If the project has a `.git` directory,
 * the deletion is staged in git automatically (via `git rm`). Otherwise
 * falls back to a regular `unlink`.
 *
 * Idempotent: safe to call on a file that no longer exists.
 * Safe for untracked files: `--ignore-unmatch` prevents errors when the file
 * is not tracked by git.
 */
export async function safeUnlink(projectPath, filePath) {
    const gitDir = join(projectPath, '.git');
    const hasGit = existsSync(gitDir);
    if (hasGit) {
        try {
            const relPath = relative(projectPath, filePath);
            await execFileAsync('git', ['rm', '-f', '--ignore-unmatch', relPath], {
                cwd: projectPath,
            });
            return;
        }
        catch (err) {
            // Fall through to unlink — git may have failed for other reasons
            console.error('[planu] safeUnlink: git rm failed, falling back to unlink', err);
        }
    }
    try {
        await unlink(filePath);
    }
    catch (err) {
        if (err.code !== 'ENOENT') {
            throw err;
        }
    }
}
//# sourceMappingURL=git-aware-fs.js.map