import { writeFileSync, readFileSync, existsSync, mkdirSync, unlinkSync, readdirSync, statSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { buildAgentInstructions } from '../../../../modules/review-execution/services/agentInstructionsBuilder.js';
export class ReviewContextFileSystemGateway {
    getFilePath(localPath, mergeRequestId) {
        return join(localPath, '.claude', 'reviews', 'logs', `${mergeRequestId}.json`);
    }
    create(input) {
        const filePath = this.getFilePath(input.localPath, input.mergeRequestId);
        mkdirSync(dirname(filePath), { recursive: true });
        const agentInstructions = buildAgentInstructions(filePath);
        const content = {
            version: '1.0',
            mergeRequestId: input.mergeRequestId,
            platform: input.platform,
            projectPath: input.projectPath,
            mergeRequestNumber: input.mergeRequestNumber,
            createdAt: new Date().toISOString(),
            threads: input.threads ?? [],
            actions: [],
            progress: {
                phase: 'pending',
                currentStep: null,
                ...(input.agents ? { agents: input.agents } : {}),
            },
            agentInstructions,
            ...(input.diffMetadata ? { diffMetadata: input.diffMetadata } : {}),
        };
        writeFileSync(filePath, JSON.stringify(content, null, 2));
        return { success: true, filePath };
    }
    delete(localPath, mergeRequestId) {
        const filePath = this.getFilePath(localPath, mergeRequestId);
        if (!existsSync(filePath)) {
            return { success: true, deleted: false };
        }
        unlinkSync(filePath);
        return { success: true, deleted: true };
    }
    read(localPath, mergeRequestId) {
        const filePath = this.getFilePath(localPath, mergeRequestId);
        if (!existsSync(filePath)) {
            return null;
        }
        const content = readFileSync(filePath, 'utf-8');
        return JSON.parse(content);
    }
    exists(localPath, mergeRequestId) {
        const filePath = this.getFilePath(localPath, mergeRequestId);
        return existsSync(filePath);
    }
    appendAction(localPath, mergeRequestId, action) {
        const context = this.read(localPath, mergeRequestId);
        if (!context) {
            return { success: false };
        }
        context.actions.push(action);
        const filePath = this.getFilePath(localPath, mergeRequestId);
        writeFileSync(filePath, JSON.stringify(context, null, 2));
        return { success: true };
    }
    updateProgress(localPath, mergeRequestId, progress) {
        const context = this.read(localPath, mergeRequestId);
        if (!context) {
            return { success: false };
        }
        context.progress = {
            ...progress,
            agents: progress.agents ?? context.progress.agents,
            updatedAt: new Date().toISOString(),
        };
        const filePath = this.getFilePath(localPath, mergeRequestId);
        writeFileSync(filePath, JSON.stringify(context, null, 2));
        return { success: true };
    }
    setResult(localPath, mergeRequestId, result) {
        const context = this.read(localPath, mergeRequestId);
        if (!context) {
            return { success: false };
        }
        context.result = result;
        const filePath = this.getFilePath(localPath, mergeRequestId);
        writeFileSync(filePath, JSON.stringify(context, null, 2));
        return { success: true };
    }
    listAll(localPath) {
        const logsDir = join(localPath, '.claude', 'reviews', 'logs');
        if (!existsSync(logsDir)) {
            return [];
        }
        return collectJsonFiles(logsDir).flatMap((path) => {
            try {
                return [JSON.parse(readFileSync(path, 'utf-8'))];
            }
            catch (error) {
                const message = error instanceof Error ? error.message : String(error);
                process.stderr.write(`[reviewContextGateway] malformed JSON skipped at ${path}: ${message}\n`);
                return [];
            }
        });
    }
}
function collectJsonFiles(directory) {
    const entries = readdirSync(directory);
    return entries.flatMap((entry) => {
        const fullPath = join(directory, entry);
        if (statSync(fullPath).isDirectory()) {
            return collectJsonFiles(fullPath);
        }
        return entry.endsWith('.json') ? [fullPath] : [];
    });
}
//# sourceMappingURL=reviewContext.fileSystem.gateway.js.map