import node_assert from "node:assert";
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { isDeepStrictEqual } from "node:util";
import { getMidsceneRunSubDir } from "@midscene/shared/common";
import { MIDSCENE_CACHE_MAX_FILENAME_LENGTH, globalConfigManager } from "@midscene/shared/env";
import { getDebug } from "@midscene/shared/logger";
import { generateHashId, ifInBrowser, ifInWorker, replaceIllegalPathCharsAndSpace } from "@midscene/shared/utils";
import js_yaml from "js-yaml";
import semver from "semver";
import { getMidsceneVersion } from "./utils.mjs";
function _define_property(obj, key, value) {
    if (key in obj) Object.defineProperty(obj, key, {
        value: value,
        enumerable: true,
        configurable: true,
        writable: true
    });
    else obj[key] = value;
    return obj;
}
const DEFAULT_CACHE_MAX_FILENAME_LENGTH = 200;
const debug = getDebug('cache');
const lowestSupportedMidsceneVersion = '0.16.10';
const cacheFileExt = '.cache.yaml';
class TaskCache {
    matchCache(prompt, type) {
        if (!this.isCacheResultUsed) return;
        const promptStr = 'string' == typeof prompt ? prompt : JSON.stringify(prompt);
        for(let i = 0; i < this.cacheOriginalLength; i++){
            const item = this.cache.caches[i];
            const key = `${type}:${promptStr}:${i}`;
            if (item.type === type && isDeepStrictEqual(item.prompt, prompt) && !this.matchedCacheIndices.has(key)) {
                if ('locate' === item.type) {
                    const locateItem = item;
                    if (!locateItem.cache && Array.isArray(locateItem.xpaths)) locateItem.cache = {
                        xpaths: locateItem.xpaths
                    };
                    if ('xpaths' in locateItem) locateItem.xpaths = void 0;
                }
                this.matchedCacheIndices.add(key);
                debug('cache found and marked as used, type: %s, prompt: %s, index: %d', type, prompt, i);
                return {
                    cacheContent: item,
                    updateFn: (cb)=>{
                        debug('will call updateFn to update cache, type: %s, prompt: %s, index: %d', type, prompt, i);
                        cb(item);
                        if (this.readOnlyMode) return void debug('read-only mode, cache updated in memory but not flushed to file');
                        debug('cache updated, will flush to file, type: %s, prompt: %s, index: %d', type, prompt, i);
                        this.flushCacheToFile();
                    }
                };
            }
        }
        debug('no unused cache found, type: %s, prompt: %s', type, prompt);
    }
    matchPlanCache(prompt) {
        return this.matchCache(prompt, 'plan');
    }
    matchLocateCache(prompt) {
        return this.matchCache(prompt, 'locate');
    }
    appendCache(cache) {
        debug('will append cache', cache);
        this.cache.caches.push(cache);
        if (this.readOnlyMode) return void debug('read-only mode, cache appended to memory but not flushed to file');
        this.flushCacheToFile();
    }
    loadCacheFromFile() {
        const cacheFile = this.cacheFilePath;
        node_assert(cacheFile, 'cache file path is required');
        if (!existsSync(cacheFile)) return void debug('no cache file found, path: %s', cacheFile);
        const jsonTypeCacheFile = cacheFile.replace(cacheFileExt, '.json');
        if (existsSync(jsonTypeCacheFile) && this.isCacheResultUsed) return void console.warn(`An outdated cache file from an earlier version of Midscene has been detected. Since version 0.17, we have implemented an improved caching strategy. Please delete the old file located at: ${jsonTypeCacheFile}.`);
        try {
            const data = readFileSync(cacheFile, 'utf8');
            const jsonData = js_yaml.load(data);
            const version = getMidsceneVersion();
            if (!version) return void debug('no midscene version info, will not read cache from file');
            if (semver.lt(jsonData.midsceneVersion, lowestSupportedMidsceneVersion) && !jsonData.midsceneVersion.includes('beta')) return void console.warn(`You are using an old version of Midscene cache file, and we cannot match any info from it. Starting from Midscene v0.17, we changed our strategy to use xpath for cache info, providing better performance.\nPlease delete the existing cache and rebuild it. Sorry for the inconvenience.\ncache file: ${cacheFile}`);
            debug('cache loaded from file, path: %s, cache version: %s, record length: %s', cacheFile, jsonData.midsceneVersion, jsonData.caches.length);
            jsonData.midsceneVersion = getMidsceneVersion();
            return jsonData;
        } catch (err) {
            debug('cache file exists but load failed, path: %s, error: %s', cacheFile, err);
            return;
        }
    }
    flushCacheToFile(options) {
        const version = getMidsceneVersion();
        if (!version) return void debug('no midscene version info, will not write cache to file');
        if (!this.cacheFilePath) return void debug('no cache file path, will not write cache to file');
        if (options?.cleanUnused) if (this.isCacheResultUsed) {
            const originalLength = this.cache.caches.length;
            const usedIndices = new Set();
            for (const key of this.matchedCacheIndices){
                const parts = key.split(':');
                const index = Number.parseInt(parts[parts.length - 1], 10);
                if (!Number.isNaN(index)) usedIndices.add(index);
            }
            this.cache.caches = this.cache.caches.filter((_, index)=>{
                const isUsed = usedIndices.has(index);
                const isNew = index >= this.cacheOriginalLength;
                return isUsed || isNew;
            });
            const removedCount = originalLength - this.cache.caches.length;
            removedCount > 0 ? debug('cleaned %d unused cache record(s)', removedCount) : debug('no unused cache to clean');
        } else debug('skip cleaning: cache is not used for reading');
        try {
            const dir = dirname(this.cacheFilePath);
            if (!existsSync(dir)) {
                mkdirSync(dir, {
                    recursive: true
                });
                debug('created cache directory: %s', dir);
            }
            const sortedCaches = [
                ...this.cache.caches
            ].sort((a, b)=>{
                if ('plan' === a.type && 'locate' === b.type) return -1;
                if ('locate' === a.type && 'plan' === b.type) return 1;
                return 0;
            });
            const cacheToWrite = {
                ...this.cache,
                caches: sortedCaches
            };
            const yamlData = js_yaml.dump(cacheToWrite);
            writeFileSync(this.cacheFilePath, yamlData);
            debug('cache flushed to file: %s', this.cacheFilePath);
        } catch (err) {
            debug('write cache to file failed, path: %s, error: %s', this.cacheFilePath, err);
        }
    }
    updateOrAppendCacheRecord(newRecord, cachedRecord) {
        if (cachedRecord) if ('plan' === newRecord.type) cachedRecord.updateFn((cache)=>{
            cache.yamlWorkflow = newRecord.yamlWorkflow;
        });
        else cachedRecord.updateFn((cache)=>{
            const locateCache = cache;
            locateCache.cache = newRecord.cache;
            if ('xpaths' in locateCache) locateCache.xpaths = void 0;
        });
        else this.appendCache(newRecord);
    }
    constructor(cacheId, isCacheResultUsed, cacheFilePath, options = {}){
        _define_property(this, "cacheId", void 0);
        _define_property(this, "cacheFilePath", void 0);
        _define_property(this, "cache", void 0);
        _define_property(this, "isCacheResultUsed", void 0);
        _define_property(this, "cacheOriginalLength", void 0);
        _define_property(this, "readOnlyMode", void 0);
        _define_property(this, "writeOnlyMode", void 0);
        _define_property(this, "matchedCacheIndices", new Set());
        node_assert(cacheId, 'cacheId is required');
        let safeCacheId = replaceIllegalPathCharsAndSpace(cacheId);
        const cacheMaxFilenameLength = globalConfigManager.getEnvConfigValueAsNumber(MIDSCENE_CACHE_MAX_FILENAME_LENGTH) ?? DEFAULT_CACHE_MAX_FILENAME_LENGTH;
        if (Buffer.byteLength(safeCacheId, 'utf8') > cacheMaxFilenameLength) {
            const prefix = safeCacheId.slice(0, 32);
            const hash = generateHashId(void 0, safeCacheId);
            safeCacheId = `${prefix}-${hash}`;
        }
        this.cacheId = safeCacheId;
        this.cacheFilePath = ifInBrowser || ifInWorker ? void 0 : cacheFilePath || join(getMidsceneRunSubDir('cache'), `${this.cacheId}${cacheFileExt}`);
        const readOnlyMode = Boolean(options?.readOnly);
        const writeOnlyMode = Boolean(options?.writeOnly);
        if (readOnlyMode && writeOnlyMode) throw new Error('TaskCache cannot be both read-only and write-only');
        this.isCacheResultUsed = writeOnlyMode ? false : isCacheResultUsed;
        this.readOnlyMode = readOnlyMode;
        this.writeOnlyMode = writeOnlyMode;
        let cacheContent;
        if (this.cacheFilePath && !this.writeOnlyMode) cacheContent = this.loadCacheFromFile();
        if (!cacheContent) cacheContent = {
            midsceneVersion: getMidsceneVersion(),
            cacheId: this.cacheId,
            caches: []
        };
        this.cache = cacheContent;
        this.cacheOriginalLength = this.isCacheResultUsed ? this.cache.caches.length : 0;
    }
}
export { TaskCache, cacheFileExt, debug };

//# sourceMappingURL=task-cache.mjs.map