import { buildStructuredPatch, StructuredApplyPatchError } from '../structured.js';
import { asString } from '../validation/shared.js';
export function resolvePathAlias(record, fileFields) {
    for (const field of fileFields) {
        const value = asString(record[field]);
        if (value) {
            return value;
        }
    }
    return undefined;
}
function safeBuildStructuredPatch(payload) {
    try {
        return { patchText: buildStructuredPatch(payload) };
    }
    catch (error) {
        if (!(error instanceof StructuredApplyPatchError)) {
            throw error;
        }
        return { failureReason: error.reason || 'structured_apply_patch_error' };
    }
}
export function buildPatchFromChangesArray(changesArray) {
    if (!changesArray.length || !changesArray.some((change) => typeof change.kind === 'string')) {
        return {};
    }
    const payload = {
        changes: changesArray
    };
    return safeBuildStructuredPatch(payload);
}
export function buildPatchFromStructuredPayload(payload) {
    if (!payload) {
        return {};
    }
    return safeBuildStructuredPatch(payload);
}
export function extractConflictPatchAsStructuredReplace(filePath, conflictText) {
    const safeFilePath = typeof filePath === 'string' ? filePath.trim() : '';
    const safeText = typeof conflictText === 'string' ? conflictText : '';
    if (!safeFilePath || !safeText) {
        return {};
    }
    const lines = safeText.replace(/\r\n/g, '\n').replace(/\r/g, '\n').split('\n');
    let start = -1;
    let middle = -1;
    let end = -1;
    for (let index = 0; index < lines.length; index += 1) {
        const line = lines[index] ?? '';
        if (start < 0) {
            if (line.startsWith('<<<<<<<')) {
                start = index;
            }
            continue;
        }
        if (middle < 0) {
            if (line.startsWith('=======')) {
                middle = index;
            }
            continue;
        }
        if (line.startsWith('>>>>>>>')) {
            end = index;
            break;
        }
    }
    if (start < 0 || middle <= start || end <= middle) {
        return {};
    }
    const original = lines.slice(start + 1, middle).join('\n');
    const updated = lines.slice(middle + 1, end).join('\n');
    if (!original.trim() || !updated.trim()) {
        return {};
    }
    return safeBuildStructuredPatch({
        file: safeFilePath,
        changes: [
            {
                kind: 'replace',
                target: original,
                lines: updated
            }
        ]
    });
}
