import { existsSync, mkdirSync, readdirSync, statSync } from 'node:fs';
import { join } from 'node:path';
import { WORKTREE_BASE_DIR } from '../../../../shared/services/daemonPaths.js';
import { createWorktreePath, deriveWorktreePath, parseWorktreeDirectoryName, } from '../../../../modules/worktree-management/entities/worktree/worktree.js';
import { ensureWorktree } from '../../../../modules/worktree-management/usecases/ensureWorktree.usecase.js';
import { removeWorktree } from '../../../../modules/worktree-management/usecases/removeWorktree.usecase.js';
import { writeWorktreeSettings } from '../../../../modules/worktree-management/services/worktreeSettingsWriter.js';
export class WorktreeFileSystemGateway {
    executor;
    baseDirectory;
    constructor(deps) {
        this.executor = deps.executor;
        this.baseDirectory = deps.baseDirectory ?? WORKTREE_BASE_DIR;
    }
    async ensure(request) {
        mkdirSync(this.baseDirectory, { recursive: true });
        return ensureWorktree({
            identity: request.identity,
            sourceBranch: request.sourceBranch,
            source: request.source,
            sourceCheckoutPath: request.sourceCheckoutPath,
        }, {
            executor: this.executor,
            worktreeExists: async (path) => existsSync(path),
            writeWorktreeSettings,
        });
    }
    async remove(request) {
        try {
            return await removeWorktree({
                identity: request.identity,
                sourceCheckoutPath: request.sourceCheckoutPath,
                force: request.force === true,
            }, {
                executor: this.executor,
                worktreeExists: async (path) => existsSync(path),
            });
        }
        catch (error) {
            const message = error instanceof Error ? error.message : String(error);
            return { status: 'failed', warning: message };
        }
    }
    async exists(identity) {
        return existsSync(deriveWorktreePath(identity));
    }
    async list() {
        if (!existsSync(this.baseDirectory)) {
            return [];
        }
        const directories = readdirSync(this.baseDirectory, { withFileTypes: true });
        const entries = [];
        for (const dirent of directories) {
            if (!dirent.isDirectory())
                continue;
            const identity = parseWorktreeDirectoryName(dirent.name);
            if (identity === null)
                continue;
            const path = createWorktreePath(join(this.baseDirectory, dirent.name));
            try {
                const stats = statSync(path);
                entries.push({ identity, path, mtime: stats.mtime });
            }
            catch {
                // ignore worktrees whose stat fails (transient FS errors, race with removal)
            }
        }
        return entries;
    }
}
//# sourceMappingURL=worktree.fileSystem.gateway.js.map