import { StorageService } from '../services/storageService.js';
import { CopyPasteParams, CopyPasteResult } from '../types/index.js';
/**
* Handler для pattern-based copy/paste операций
*/
export class CopyPasteHandler {
constructor(private storageService: StorageService) {}
async execute(params: CopyPasteParams): Promise<CopyPasteResult> {
try {
await this.validateParams(params);
// Extract content by pattern
const contentToMove = await this.storageService.extractContentByPattern(
params.source.file,
params.source.start_pattern,
params.source.end_pattern,
params.source.line_count
);
let sourceModified = false;
let targetModified = false;
try {
// Insert content by marker
await this.storageService.insertContentByMarker(
params.target.file,
params.target.marker,
contentToMove,
params.target.position,
params.target.replace_pattern
);
targetModified = true;
// Remove from source if cut=true
if (params.cut) {
await this.storageService.removeContentByPattern(
params.source.file,
params.source.start_pattern,
params.source.end_pattern,
params.source.line_count
);
sourceModified = true;
}
return {
success: true,
message: `Successfully ${params.cut ? 'moved' : 'copied'} content`,
contentMoved: contentToMove,
sourceModified,
targetModified
};
} catch (error) {
return {
success: false,
message: `Operation failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
sourceModified,
targetModified
};
}
} catch (error) {
return {
success: false,
message: `Validation failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
sourceModified: false,
targetModified: false
};
}
}
private async validateParams(params: CopyPasteParams): Promise<void> {
// Source validation
if (!params.source?.file) {
throw new Error('Source file path is required');
}
if (!params.source.start_pattern?.trim()) {
throw new Error('Source start_pattern is required and cannot be empty');
}
if (params.source.line_count !== undefined && params.source.line_count < 1) {
throw new Error('Source line_count must be >= 1');
}
// Target validation
if (!params.target?.file) {
throw new Error('Target file path is required');
}
if (!params.target.marker?.trim()) {
throw new Error('Target marker is required and cannot be empty');
}
if (!['before', 'after', 'replace'].includes(params.target.position)) {
throw new Error('Target position must be "before", "after", or "replace"');
}
// File existence check
const sourceExists = await this.storageService.resourceExists(params.source.file);
if (!sourceExists) {
throw new Error(`Source file does not exist: ${params.source.file}`);
}
}
}