import { execFileSync } from "child_process";
import { execFile } from "child_process";
import { promisify } from "util";
import fs from "fs";
import path from "path";
import { logger } from "./logger.js";
import { isTestbotEnabled } from "./featureFlags.js";
/**
 * Check whether `child` is inside `parent` using resolved paths with
 * a trailing separator to avoid prefix false positives (e.g. /tmp/test-repo2
 * should not match /tmp/test-repo).
 */
export function isInsideDir(child, parent) {
    const resolved = path.resolve(child) + path.sep;
    const resolvedParent = path.resolve(parent) + path.sep;
    return resolved.startsWith(resolvedParent);
}
/**
 * In cross-repo mode, redirects an outputDir to be under the test repo clone
 * if it isn't already. Returns the original path unchanged when testsRepoDir
 * is unset or the path is already inside it.
 */
export function resolveOutputDir(outputDir, testsRepoDir) {
    if (!testsRepoDir || isInsideDir(outputDir, testsRepoDir))
        return outputDir;
    const relative = path.isAbsolute(outputDir)
        ? path.basename(outputDir)
        : outputDir;
    return path.join(testsRepoDir, relative);
}
const execFileAsync = promisify(execFile);
/**
 * Detect the git repository root for a given file or directory path.
 * Returns undefined if detection fails (not inside a git repo).
 */
function detectGitRoot(filePath) {
    if (!path.isAbsolute(filePath))
        return undefined;
    try {
        const dir = fs.statSync(filePath).isDirectory() ? filePath : path.dirname(filePath);
        const stdout = execFileSync("git", ["rev-parse", "--show-toplevel"], { cwd: dir, encoding: "utf8" });
        return stdout.trim() || undefined;
    }
    catch {
        return undefined;
    }
}
/**
 * Stages a file path an MCP tool just wrote into the git index by
 * running `git add -- <path>`.
 *
 * Automatically detects the git root of the target path so that staging
 * works correctly in cross-repo mode (test repo clone separate from the
 * source repo).
 *
 * Gated by the SKYRAMP_FEATURE_TESTBOT=1 env var, which is set only
 * inside a testbot CI run.
 */
export async function stageGeneratedPaths(filePath, cwd) {
    if (!isTestbotEnabled())
        return;
    const effectiveCwd = cwd ?? detectGitRoot(filePath);
    await execFileAsync("git", ["add", "--", filePath], {
        cwd: effectiveCwd,
    });
    logger.info("Staged generated file", { path: filePath, cwd: effectiveCwd });
}
