import * as fs from 'node:fs';
import * as path from 'node:path';
import { resolveConfigValue } from '../../../infra/config/index.js';
import { resolveCloneBaseDir, } from '../../../infra/task/index.js';
import { syncProjectLocalTaktForRetry } from '../../../infra/task/projectLocalTaktSync.js';
import { isRealPathInside } from '../../../shared/utils/index.js';
function canReuseWorktreePath(projectDir, candidatePath) {
    if (!fs.existsSync(candidatePath)) {
        return false;
    }
    const cloneBaseDir = resolveCloneBaseDir(projectDir);
    const fallbackCloneBaseDir = path.join(projectDir, '.takt', 'worktrees');
    return isRealPathInside(cloneBaseDir, candidatePath) || isRealPathInside(fallbackCloneBaseDir, candidatePath);
}
function shouldSyncProjectLocalTaktOnReuse(task, configuredStartStep, resumePoint, retryNote) {
    if (task.status === 'failed' || task.status === 'pr_failed' || task.status === 'exceeded') {
        return true;
    }
    return configuredStartStep !== undefined
        || resumePoint !== undefined
        || typeof retryNote === 'string';
}
export function resolveReusedWorktreeExecution(projectDir, task, configuredStartStep, resumePoint, retryNote) {
    const worktreePath = task.worktreePath;
    if (!worktreePath || !canReuseWorktreePath(projectDir, worktreePath)) {
        return undefined;
    }
    if (shouldSyncProjectLocalTaktOnReuse(task, configuredStartStep, resumePoint, retryNote)
        && resolveConfigValue(projectDir, 'syncProjectLocalTaktOnRetry')) {
        syncProjectLocalTaktForRetry(projectDir, worktreePath);
    }
    return {
        execCwd: worktreePath,
        branch: task.data?.branch,
        worktreePath,
        isWorktree: true,
    };
}
//# sourceMappingURL=reusedWorktree.js.map