import { getPrefixedLogger } from "../../../../util/logger.js";
import { getMigration, hasMigrationPath } from "./registry.js";
import { detectVersion } from "./types.js";
const logger = getPrefixedLogger("[context-migration]");
export function migrateContext(record, targetVersion) {
    const currentVersion = detectVersion(record);
    if (currentVersion === 0) {
        logger.error(`Unrecognized context format, cannot determine version. Deleting context.`);
        return {
            success: false,
            deleted: true,
            reason: "Unrecognized context format",
        };
    }
    if (currentVersion === targetVersion) {
        logger.debug(`Context already at version ${targetVersion}, no migration needed`);
        return {
            success: true,
            record: record,
        };
    }
    // Downgrade case: saved version is newer than expected, not supported
    if (currentVersion > targetVersion) {
        logger.error(`Context version ${currentVersion} is newer than expected version ${targetVersion}. ` +
            `Downgrade is not supported. Deleting context.`);
        return {
            success: false,
            deleted: true,
            reason: `Downgrade not supported: ${currentVersion} > ${targetVersion}`,
        };
    }
    if (!hasMigrationPath(currentVersion, targetVersion)) {
        logger.error(`No migration path from version ${currentVersion} to ${targetVersion}. Deleting context.`);
        return {
            success: false,
            deleted: true,
            reason: `No migration path from ${currentVersion} to ${targetVersion}`,
        };
    }
    logger.debug(`Migrating context from version ${currentVersion} to ${targetVersion}`);
    let migrated = record;
    for (let v = currentVersion; v < targetVersion; v++) {
        const migration = getMigration(v, v + 1);
        try {
            migrated = migration.migrate(migrated);
        }
        catch (err) {
            logger.error(`Migration v${v} → v${v + 1} failed: ${err}. Deleting context.`);
            return {
                success: false,
                deleted: true,
                reason: `Migration v${v} → v${v + 1} failed: ${err}`,
            };
        }
    }
    return {
        success: true,
        record: migrated,
    };
}
//# sourceMappingURL=runner.js.map