const fs=require("fs"),path=require("path");class JsonStorage{constructor(filePath){const dir=path.dirname(filePath);fs.existsSync(dir)||fs.mkdirSync(dir,{recursive:!0}),this.filePath=filePath,this.data={},this.load()}load(){try{if(fs.existsSync(this.filePath)){const data=fs.readFileSync(this.filePath,"utf8");return this.data=JSON.parse(data),!0}return this.data={},this.save(),!0}catch(error){return this.data={},!1}}reload(){this.load()}save(){try{return fs.writeFileSync(this.filePath,JSON.stringify(this.data,null,2),"utf8"),!0}catch(error){return!1}}async saveAsync(){return new Promise(resolve=>{fs.writeFile(this.filePath,JSON.stringify(this.data,null,2),"utf8",error=>{resolve(!error)})})}set(key,value,save=!0){const pathArray=Array.isArray(key)?key:key.split(".");let current=this.data;for(let i=0;i<pathArray.length-1;i++){const segment=pathArray[i];current[segment]&&"object"==typeof current[segment]||(current[segment]={}),current=current[segment]}return current[pathArray[pathArray.length-1]]=value,save&&this.save(),this}get(key,defaultValue=null){const pathArray=Array.isArray(key)?key:key.split(".");let current=this.data;for(const segment of pathArray){if(null==current||"object"!=typeof current||!(segment in current))return defaultValue;current=current[segment]}return void 0!==current?current:defaultValue}has(key){const pathArray=Array.isArray(key)?key:key.split(".");let current=this.data;for(const segment of pathArray){if(null==current||"object"!=typeof current||!(segment in current))return!1;current=current[segment]}return!0}delete(key,save=!0){const pathArray=Array.isArray(key)?key:key.split(".");if(1===pathArray.length){const keyName=pathArray[0];return keyName in this.data&&(delete this.data[keyName],save&&this.save(),!0)}let current=this.data;for(let i=0;i<pathArray.length-1;i++){const segment=pathArray[i];if(!current[segment]||"object"!=typeof current[segment])return!1;current=current[segment]}const lastKey=pathArray[pathArray.length-1];return lastKey in current&&(delete current[lastKey],save&&this.save(),!0)}clear(save=!0){this.data={},save&&this.save()}getAll(){return{...this.data}}merge(obj,save=!0){return this._deepMerge(this.data,obj),save&&this.save(),this}_deepMerge(target,source){for(const key of Object.keys(source))source[key]instanceof Object&&!Array.isArray(source[key])?(key in target||(target[key]={}),this._deepMerge(target[key],source[key])):target[key]=source[key]}}module.exports=JsonStorage;