import { sweepStaleWorktrees } from '../../modules/worktree-management/usecases/sweepStaleWorktrees.usecase.js';
const TWENTY_FOUR_HOURS_IN_MILLISECONDS = 86_400_000;
export function startWorktreeSweepScheduler(dependencies) {
    const { worktreeGateway, trackingGateway, getRepositories, logger, now } = dependencies;
    let lastSummary = null;
    let runningSince = null;
    const startedAt = now();
    async function runSweepInternal() {
        const ranAt = now();
        runningSince = ranAt;
        try {
            const summary = await sweepStaleWorktrees({
                listEntries: () => worktreeGateway.list(),
                removeWorktree: async (identity) => {
                    const repositories = getRepositories();
                    const firstEnabled = repositories.find(repository => repository.enabled);
                    const sourceCheckoutPath = firstEnabled?.localPath ?? '';
                    return worktreeGateway.remove({ identity, sourceCheckoutPath });
                },
                trackingGateway,
                getRepositories,
                now,
            });
            const result = { ranAt, ...summary };
            lastSummary = result;
            if (summary.removed > 0 || summary.failures > 0) {
                logger.info({ ...summary }, 'Worktree sweep completed');
            }
            return result;
        }
        finally {
            runningSince = null;
        }
    }
    async function runScheduledSweep() {
        try {
            await runSweepInternal();
        }
        catch (error) {
            logger.error({ error }, 'Worktree sweep failed');
        }
    }
    void runScheduledSweep();
    const intervalId = setInterval(() => {
        void runScheduledSweep();
    }, TWENTY_FOUR_HOURS_IN_MILLISECONDS);
    return {
        stop: () => clearInterval(intervalId),
        getLastSweep: () => lastSummary,
        getNextSweepEta: () => {
            const reference = lastSummary?.ranAt ?? startedAt;
            return new Date(reference.getTime() + TWENTY_FOUR_HOURS_IN_MILLISECONDS);
        },
        runSweepNow: async () => {
            if (runningSince !== null) {
                return { status: 'conflict', startedAt: runningSince };
            }
            try {
                const summary = await runSweepInternal();
                return { status: 'ok', summary };
            }
            catch (error) {
                logger.error({ error }, 'Manual worktree sweep failed');
                const reason = error instanceof Error ? error.message : 'unknown';
                return { status: 'error', reason };
            }
        },
    };
}
//# sourceMappingURL=worktreeSweepScheduler.js.map