import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync, unlinkSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { pendingReviewRequestGuard } from '../../../../modules/review-execution/entities/pendingReviewRequest/pendingReviewRequest.guard.js';
import { sanitizeJobId } from '../../../../shared/services/mcpJobContext.js';
function defaultRootDir() {
    return join(homedir(), '.claude-review', 'pending');
}
export class PendingReviewRequestFileSystemGateway {
    rootDir;
    constructor(options = {}) {
        this.rootDir = options.rootDir ?? defaultRootDir();
    }
    ensureRootDir() {
        if (!existsSync(this.rootDir)) {
            mkdirSync(this.rootDir, { recursive: true });
        }
    }
    filePath(pendingReviewRequestId) {
        return join(this.rootDir, `${sanitizeJobId(pendingReviewRequestId)}.json`);
    }
    async save(pending) {
        this.ensureRootDir();
        writeFileSync(this.filePath(pending.pendingReviewRequestId), `${JSON.stringify(pending, null, 2)}\n`);
    }
    async load(pendingReviewRequestId) {
        const filePath = this.filePath(pendingReviewRequestId);
        if (!existsSync(filePath)) {
            return null;
        }
        try {
            const raw = readFileSync(filePath, 'utf-8');
            const parsed = JSON.parse(raw);
            const result = pendingReviewRequestGuard.safeParse(parsed);
            if (!result.success) {
                return null;
            }
            return result.data;
        }
        catch {
            return null;
        }
    }
    async listAll() {
        if (!existsSync(this.rootDir)) {
            return [];
        }
        const entries = readdirSync(this.rootDir);
        const collected = [];
        for (const entry of entries) {
            if (!entry.endsWith('.json'))
                continue;
            try {
                const raw = readFileSync(join(this.rootDir, entry), 'utf-8');
                const parsed = JSON.parse(raw);
                const result = pendingReviewRequestGuard.safeParse(parsed);
                if (result.success) {
                    collected.push(result.data);
                }
            }
            catch {
                // Skip unreadable / invalid files; the file system gateway is forgiving.
            }
        }
        return collected;
    }
    async delete(pendingReviewRequestId) {
        const filePath = this.filePath(pendingReviewRequestId);
        if (!existsSync(filePath)) {
            return false;
        }
        try {
            unlinkSync(filePath);
            return true;
        }
        catch {
            return false;
        }
    }
}
//# sourceMappingURL=pendingReviewRequest.fileSystem.gateway.js.map