const n="coral-library-data",s="coral-library-lock";function f(){return`tx-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}async function m(t,r=1){try{const e=(await chrome.storage.local.get(s))[s];if(e&&Date.now()-e.timestamp<5e3)return r<3?(await new Promise(u=>setTimeout(u,100*r)),m(t,r+1)):!1;const o={timestamp:Date.now(),transactionId:t};return await chrome.storage.local.set({[s]:o}),(await chrome.storage.local.get(s))[s].transactionId===t}catch(a){return console.error("[Transaction] Error acquiring lock:",a),!1}}async function p(t){try{const a=(await chrome.storage.local.get(s))[s];a&&a.transactionId===t&&await chrome.storage.local.remove(s)}catch(r){console.error("[Transaction] Error releasing lock:",r)}}async function b(t,r={}){const a=f(),e=r.operationName||"transaction";let o=!1,c={word_lists:[],prompts:[],sequences:[],templates:[]};try{if(`${e}${a}`,o=await m(a),!o)return{success:!1,error:"Failed to acquire lock - another transaction is in progress"};c=(await chrome.storage.local.get(n))[n]||{word_lists:[],prompts:[],sequences:[],templates:[]},r.skipBackup||await g(c,a);const{data:i,newLibrary:u}=await t(c);if(!k(u))throw new Error("Invalid library data structure");return await chrome.storage.local.set({[n]:u}),`${e}`,{success:!0,data:i}}catch(l){console.error(`[Transaction] Error in ${e}:`,l);try{await chrome.storage.local.set({[n]:c}),`${e}`}catch(i){console.error("[Transaction] Rollback failed:",i)}return{success:!1,error:l instanceof Error?l.message:"Unknown error"}}finally{o&&await p(a)}}function k(t){if(!t||typeof t!="object")return!1;const r=["word_lists","prompts","sequences","templates"];for(const a of r)if(!Array.isArray(t[a]))return!1;return!0}async function g(t,r){try{const a=`coral-library-backup-${r}`,e={data:t,timestamp:Date.now(),transactionId:r};await chrome.storage.local.set({[a]:e}),await w()}catch(a){console.warn("[Transaction] Failed to create backup:",a)}}async function w(){try{const t=await chrome.storage.local.get(null),r=Object.keys(t).filter(a=>a.startsWith("coral-library-backup-"));if(r.length>5){const a=r.map(o=>({key:o,timestamp:t[o].timestamp||0}));a.sort((o,c)=>o.timestamp-c.timestamp);const e=a.slice(0,a.length-5).map(o=>o.key);await chrome.storage.local.remove(e)}}catch(t){console.warn("[Transaction] Failed to cleanup old backups:",t)}}async function y(){try{const t=await chrome.storage.local.get(null),r=Object.keys(t).filter(o=>o.startsWith("coral-library-backup-"));if(r.length===0)return null;let a=null,e=0;for(const o of r){const c=t[o];c.timestamp>e&&(e=c.timestamp,a=c)}return a?a.data:null}catch(t){return console.error("[Transaction] Error getting latest backup:",t),null}}async function T(t){try{if(t){const r=`coral-library-backup-${t}`,e=(await chrome.storage.local.get(r))[r];if(e&&e.data)return await chrome.storage.local.set({[n]:e.data}),`${t}`,!0}else{const r=await y();if(r)return await chrome.storage.local.set({[n]:r}),!0}return!1}catch(r){return console.error("[Transaction] Error restoring from backup:",r),!1}}export{b as executeTransaction,y as getLatestBackup,T as restoreFromBackup};
