"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;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getHashes = getHashes;
exports.saveHashes = saveHashes;
exports.md5Hash = md5Hash;
exports.checkNoFilesChanged = checkNoFilesChanged;
exports.saveAllFileHashes = saveAllFileHashes;
exports.hasFileChangedSinceUpload = hasFileChangedSinceUpload;
exports.saveUploadHash = saveUploadHash;
exports.isLocalFileMatchingDownloadHash = isLocalFileMatchingDownloadHash;
exports.saveDownloadHash = saveDownloadHash;
exports.computeSHA256Base64 = computeSHA256Base64;
exports.isLocalFileMatchingRemote = isLocalFileMatchingRemote;
const fs_1 = __importDefault(require("fs"));
const crypto = __importStar(require("crypto"));
const utils_1 = require("./utils");
const conversion_1 = require("./conversion");
async function getHashes() {
    try {
        const hashes = JSON.parse(await (0, utils_1.readFile)(".knowhow/.hashes.json", "utf8"));
        return hashes;
    }
    catch (err) {
        if (err.code === "ENOENT") {
            return {};
        }
        throw err;
    }
}
async function saveHashes(hashes) {
    const target = ".knowhow/.hashes.json";
    const tmp = `${target}.tmp.${process.pid}`;
    try {
        fs_1.default.writeFileSync(tmp, JSON.stringify(hashes, null, 2));
        fs_1.default.renameSync(tmp, target);
    }
    catch (err) {
        try {
            fs_1.default.unlinkSync(tmp);
        }
        catch (_) { }
        throw err;
    }
}
async function md5Hash(str) {
    return crypto.createHash("md5").update(str).digest("hex");
}
async function checkNoFilesChanged(files, promptHash, hashes) {
    for (const file of files) {
        if (!fs_1.default.existsSync(file)) {
            return false;
        }
        const fileContent = await (0, conversion_1.convertToText)(file);
        const fileHash = crypto.createHash("md5").update(fileContent).digest("hex");
        if (!hashes[file]) {
            return false;
        }
        if (hashes[file].promptHash === promptHash &&
            hashes[file].fileHash === fileHash) {
            return true;
        }
        if (hashes[file][promptHash] === fileHash) {
            return true;
        }
        return false;
    }
    return true;
}
async function saveAllFileHashes(files, promptHash) {
    const hashes = await getHashes();
    for (const file of files) {
        const fileContent = await (0, conversion_1.convertToText)(file);
        const fileHash = crypto.createHash("md5").update(fileContent).digest("hex");
        if (!hashes[file]) {
            hashes[file] = {
                fileHash,
                promptHash,
            };
        }
        hashes[file][promptHash] = fileHash;
    }
    await saveHashes(hashes);
}
const UPLOAD_KEY = "upload";
const DOWNLOAD_KEY = "download";
async function hasFileChangedSinceUpload(localPath, hashes) {
    if (!fs_1.default.existsSync(localPath))
        return true;
    const content = fs_1.default.readFileSync(localPath);
    const currentHash = crypto.createHash("md5").update(content).digest("hex");
    return hashes[localPath]?.[UPLOAD_KEY] !== currentHash;
}
async function saveUploadHash(localPath, hashes) {
    const standalone = !hashes;
    if (standalone)
        hashes = await getHashes();
    const content = fs_1.default.readFileSync(localPath);
    const currentHash = crypto.createHash("md5").update(content).digest("hex");
    if (!hashes[localPath]) {
        hashes[localPath] = { fileHash: currentHash, promptHash: "" };
    }
    hashes[localPath][UPLOAD_KEY] = currentHash;
    if (standalone)
        await saveHashes(hashes);
}
async function isLocalFileMatchingDownloadHash(localPath, hashes) {
    if (!fs_1.default.existsSync(localPath))
        return false;
    const storedHash = hashes[localPath]?.[DOWNLOAD_KEY];
    if (!storedHash)
        return false;
    const content = fs_1.default.readFileSync(localPath);
    const currentHash = crypto.createHash("sha256").update(content).digest("base64");
    return storedHash === currentHash;
}
async function saveDownloadHash(localPath, hashes) {
    const standalone = !hashes;
    if (standalone)
        hashes = await getHashes();
    const content = fs_1.default.readFileSync(localPath);
    const currentHash = crypto.createHash("sha256").update(content).digest("base64");
    if (!hashes[localPath]) {
        hashes[localPath] = { fileHash: currentHash, promptHash: "" };
    }
    hashes[localPath][DOWNLOAD_KEY] = currentHash;
    if (standalone)
        await saveHashes(hashes);
}
function computeSHA256Base64(filePath) {
    const content = fs_1.default.readFileSync(filePath);
    return crypto.createHash("sha256").update(content).digest("base64");
}
function isLocalFileMatchingRemote(localPath, remoteChecksumSHA256) {
    if (!remoteChecksumSHA256)
        return false;
    if (!fs_1.default.existsSync(localPath))
        return false;
    const localChecksum = computeSHA256Base64(localPath);
    return localChecksum === remoteChecksumSHA256;
}
//# sourceMappingURL=hashes.js.map