"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.readJsonWithTmpFallback = readJsonWithTmpFallback;
exports.validateGraphStructure = validateGraphStructure;
const fs = __importStar(require("fs"));
const logger_1 = require("../lib/logger");
const log = (0, logger_1.createLogger)('graph');
/**
 * Try to read and parse a JSON file, falling back to .tmp if main file
 * is missing or corrupted (recovery from interrupted save).
 */
function readJsonWithTmpFallback(file) {
    const tmp = file + '.tmp';
    // If main file missing but .tmp exists, recover it
    if (!fs.existsSync(file) && fs.existsSync(tmp)) {
        try {
            fs.renameSync(tmp, file);
        }
        catch { /* ignore */ }
    }
    if (fs.existsSync(file)) {
        try {
            return JSON.parse(fs.readFileSync(file, 'utf-8'));
        }
        catch {
            // Main file corrupted — try .tmp as fallback
            if (fs.existsSync(tmp)) {
                try {
                    const data = JSON.parse(fs.readFileSync(tmp, 'utf-8'));
                    log.warn({ file }, 'Recovered from .tmp file');
                    return data;
                }
                catch { /* .tmp also bad */ }
            }
        }
    }
    return null;
}
/**
 * Basic structural validation for Graphology serialized graph data.
 * Ensures the shape matches what graph.import() expects, preventing
 * injection of unexpected properties.
 */
function validateGraphStructure(data) {
    if (data == null || typeof data !== 'object')
        return false;
    const obj = data;
    if (!Array.isArray(obj.nodes))
        return false;
    if (!Array.isArray(obj.edges))
        return false;
    for (const node of obj.nodes) {
        if (node == null || typeof node !== 'object')
            return false;
        const n = node;
        if (typeof n.key !== 'string')
            return false;
        if (n.attributes !== undefined) {
            if (n.attributes == null || typeof n.attributes !== 'object')
                return false;
            if (Object.prototype.hasOwnProperty.call(n.attributes, '__proto__') || Object.prototype.hasOwnProperty.call(n.attributes, 'constructor'))
                return false;
        }
    }
    for (const edge of obj.edges) {
        if (edge == null || typeof edge !== 'object')
            return false;
        const e = edge;
        if (typeof e.source !== 'string' || typeof e.target !== 'string')
            return false;
        if (e.attributes !== undefined) {
            if (e.attributes == null || typeof e.attributes !== 'object')
                return false;
            if (Object.prototype.hasOwnProperty.call(e.attributes, '__proto__') || Object.prototype.hasOwnProperty.call(e.attributes, 'constructor'))
                return false;
        }
    }
    return true;
}
