import d from"fs/promises";var h=class{static generate(t,n="element"){let{selectors:r}=t;if(!r||typeof r!="object")return this.generateFallbackSelector(t,n);let e=[];return r.role&&e.push(this.generateRoleSelector(r.role)),r.attributes&&e.push(this.generateAttributeSelector(r.attributes)),r.partialMatch&&e.push(this.generatePartialMatchSelector(r.partialMatch)),r.structure&&e.push(this.generateStructuralSelector(r.structure)),e.length===0?this.generateFallbackSelector(t,n):e.length===1?`const ${n} = ${e[0]};`:`const ${n} = ${e[0]}
${e.slice(1).map(o=>`  .or(${o})`).join(`
`)};`}static generateRoleSelector(t){let{role:n,name:r}=t;if(!n)return null;if(r){let e=this.escapeRegex(r);return`page.getByRole('${n}', { name: /${e}/i })`}return`page.getByRole('${n}')`}static generateAttributeSelector(t){if(!t||typeof t!="object")return null;let n=Object.entries(t).filter(([e,s])=>s!=null).map(([e,s])=>e==="placeholder"||e==="aria-label"?e==="placeholder"?`page.getByPlaceholder('${this.escapeString(s)}')`:`page.locator('[${e}="${this.escapeString(s)}"]')`:`[${e}="${this.escapeString(s)}"]`);if(t.placeholder)return`page.getByPlaceholder('${this.escapeString(t.placeholder)}')`;let r=n.filter(e=>!e.startsWith("page.")).join("");return r?`page.locator('${r}')`:null}static generatePartialMatchSelector(t){if(!t||typeof t!="object")return null;let n=Object.entries(t).filter(([r,e])=>e!==void 0).map(([r,e])=>{let s=e.replace(/^\^/,"");return`[${r}^="${this.escapeString(s)}"]`});return n.length>0?`page.locator('${n.join("")}')`:null}static generateStructuralSelector(t){return!t||typeof t!="string"?null:`page.locator('${this.escapeString(t)}')`}static generateFallbackSelector(t,n){let{description:r,type:e}=t;if(e==="fill"||e==="type")return`const ${n} = page.locator('input').first();`;if(e==="click"){if(r.toLowerCase().includes("button"))return`const ${n} = page.locator('button').first();`;if(r.toLowerCase().includes("link"))return`const ${n} = page.locator('a').first();`}return`const ${n} = page.locator('body');`}static escapeString(t){return typeof t!="string"?String(t):t.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/"/g,'\\"')}static escapeRegex(t){return typeof t!="string"?String(t):t.replace(/[.*+?^${}()[\]\\]/g,"\\$&")}static generateActionCode(t,n){let{type:r,value:e,description:s,selectors:o}=t,i=`element${n}`,l=this.generate(t,i),a=this.generateActionMethod(r,i,e);return`${l}
${a}`}static generateActionMethod(t,n,r){switch(t){case"fill":case"type":return`await ${n}.fill('${this.escapeString(r||"")}');`;case"click":return`await ${n}.click();`;case"navigate":return`await page.goto('${this.escapeString(r||"")}');`;case"wait":return`await page.waitForTimeout(${parseInt(r)||2e3});`;default:return`// Unknown action type: ${t}`}}static generateAssertionCode(t,n){let{description:r,expected:e,actual:s,passed:o}=t;return r.toLowerCase().includes("url")?`await expect(page).toHaveURL(/${this.escapeRegex(s)}/);`:r.toLowerCase().includes("visible")?"await expect(page.locator('body')).toBeVisible();":`// ${r}`}};var $=class{static async generateFromEvents(t,n,r,e){try{console.log("[TestPostProcessor] \u{1F3AF} Generating test from events.json (100% accurate)");let{readFileSync:s}=await import("fs"),o=JSON.parse(s(n,"utf-8")),i=o.filter(c=>["navigate","type","fill","click","select_option"].includes(c.type)),l=i.filter(c=>c.type!=="navigate");console.log(`[TestPostProcessor] Found ${i.length} action events, ${r.length} trace actions`);let a=`import { ZibbyRuntime } from '@zibby/core';
import { test, expect } from '@playwright/test';

`;a+=`test('${e}', async ({ page }) => {
`,a+=`  const timestamp = Date.now();

`;let p=0;for(let c of i)if(c.type==="navigate")a+=`  await page.goto('${c.data.params.url}');

`;else if(c.type==="type"||c.type==="fill"){let{element:f,text:g}=c.data.params,m=r[p]?.strategies||[];a+=`  await ZibbyRuntime.step(page, ${JSON.stringify({name:f,action:"fill",value:g,strategies:m},null,2)});

`,p++}else if(c.type==="click"){let{element:f}=c.data.params,g=r[p]?.strategies||[];a+=`  await ZibbyRuntime.step(page, ${JSON.stringify({name:f,action:"click",value:"",strategies:g},null,2)});

`,p++}else if(c.type==="select_option"){let{element:f,values:g}=c.data.params,m=r[p]?.strategies||[],w={name:f,action:"selectOption",value:Array.isArray(g)?g[0]:g,strategies:m};a+=`  await ZibbyRuntime.step(page, ${JSON.stringify(w,null,2)});

`,p++}a+=`});
`;let{dirname:u}=await import("path"),{mkdirSync:y}=await import("fs");return y(u(t),{recursive:!0}),await d.writeFile(t,a,"utf-8"),console.log(`[TestPostProcessor] \u2705 Generated test with ${o.filter(c=>["type","fill","click","select_option"].includes(c.type)).length} actions`),!0}catch(s){return console.warn("[TestPostProcessor] Failed to generate from events:",s.message),!1}}static async enhanceSelectorsWithTrace(t,n,r){try{console.log("[TestPostProcessor] \u{1F6E1}\uFE0F Applying Zibby Safe Action Wrappers...");let e=await d.readFile(t,"utf-8");e.includes("ZibbyRuntime")||(e=`import { ZibbyRuntime } from '@zibby/core';
${e}`);for(let s=0;s<n.length;s++){let o=n[s],i=`element${s}`,l=new RegExp(`const ${i}\\b\\s*=\\s*page\\.[^;]+;(\\s*await ${i}\\.waitFor\\([^)]*\\);)?\\s*await ${i}\\.(click|fill|type|selectOption|pressSequentially)\\(([^)]*)\\);`,"s"),a=e.match(l);if(!a)continue;let p={name:o.name||`Action ${s}`,action:o.method==="type"?"fill":o.method,value:a[3].trim().replace(/^['"]|['"]$/g,""),strategies:o.strategies||[]},u=`await ZibbyRuntime.step(page, ${JSON.stringify(p,null,2)});`;e=e.replace(a[0],u)}return await d.writeFile(t,e,"utf-8"),console.log("[TestPostProcessor] \u2705 Successfully converted test to Resilient Zibby format"),!0}catch(e){return console.warn("[TestPostProcessor] Failed to apply safe wrappers:",e.message),!1}}static async enhanceSelectors(t,n){try{let{actions:r=[]}=n;if(!r.length)return!1;let e=await d.readFile(t,"utf-8"),s=this.buildSelectorMap(r);return e=this.replaceSimpleSelectors(e,s),await d.writeFile(t,e,"utf-8"),!0}catch(r){return console.warn("Failed to enhance selectors:",r),!1}}static buildSelectorMap(t){let n=new Map;for(let r=0;r<t.length;r++){let e=t[r];if(!e.selectors||e.type==="navigate")continue;let s=`element${r}`,i=h.generate(e,s).match(/= (.+);/s);if(i){let l=i[1].trim(),a=`${e.type}:${this.normalizeDescription(e.description)}`;n.set(a,l),e.selectors.role&&n.set(`role:${e.selectors.role.name}`,l),e.selectors.attributes?.placeholder&&n.set(`placeholder:${e.selectors.attributes.placeholder}`,l)}}return n}static replaceSimpleSelectors(t,n){let r=t,e=[/await page\.(getByRole|getByPlaceholder|getByText|getByLabel|locator)\([^)]+\)\.(fill|click|type)\([^)]*\)/g];for(let s of e)r=r.replace(s,o=>{for(let[i,l]of n.entries())if(o.includes(i.split(":")[1])){let a=o.match(/\.(fill|click|type)\(([^)]*)\)/);if(a){let[,p,u]=a,y="element";return`const ${y} = ${l};
    await ${y}.${p}(${u})`}}return o});return r}static normalizeDescription(t){return t?t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim():""}},R=$;export{$ as TestPostProcessor,R as default};
