#!/usr/bin/env node
import*as m from'fs';import*as h from'path';import*as R from'js-yaml';import {execFileSync}from'child_process';var G=["node_modules",".git","dist","build","coverage",".paradigm","vendor","__pycache__",".next","target"];function S(e){let t=h.join(e,"portal.yaml");if(!m.existsSync(t))return null;try{let n=m.readFileSync(t,"utf-8");return R.load(n)}catch{return null}}function C(e){let t=new Set;if(e.gates)for(let n of Object.keys(e.gates)){let s=n.startsWith("^")?n.slice(1):n;t.add(s);}if(e.routes)for(let n of Object.values(e.routes)){let s=Array.isArray(n)?n:n.gates||[];for(let o of s){let a=o.startsWith("^")?o.slice(1):o;t.add(a);}}return Array.from(t)}function B(e){let t=new Set;if(e.routes)for(let n of Object.values(e.routes)){let s=Array.isArray(n)?n:n.gates||[];for(let o of s){let a=o.startsWith("^")?o.slice(1):o;t.add(a);}}return t}function E(e,t){let n={encoding:"utf-8",maxBuffer:10485760,stdio:["ignore","pipe","pipe"]};try{let i=["-n","--no-ignore-vcs",...G.flatMap(u=>["--glob",`!${u}/**`]),"--engine","auto",t,e];return execFileSync("rg",i,n)}catch{}let o=["-rn",...G.map(a=>`--exclude-dir=${a}`),"-E",t,"--",e];try{return execFileSync("grep",o,n)}catch(a){return a?.code===1||a?.status===1,""}}var P=["**/.purpose","**/portal.yaml","**/.paradigm/**/*.yaml","**/.paradigm/**/*.yml"];function x(e){let t=[];for(let o of P){h.join(e,o);let i;try{i=execFileSync("find",[e,"-path","*/node_modules","-prune","-o","-path","*/.git","-prune","-o","(","-name",".purpose","-o","-name","portal.yaml",")","-print"],{encoding:"utf-8",maxBuffer:5242880}).split(`
`).filter(Boolean);}catch{i=[];}for(let u of i)try{let p=m.readFileSync(u,"utf-8").split(`
`);for(let l=0;l<p.length;l++){let d=p[l],g=d.matchAll(/\^([a-z][a-z0-9-]+)/g);for(let c of g)t.push({gate:c[1],file:h.relative(e,u),line:l+1,context:d.trim().slice(0,100),matchType:"symbol"});}}catch{}}let s=[{pattern:`checkGate\\s*\\(['"]([^'"]+)['"]`,type:"function"},{pattern:`requireGate\\s*\\(['"]([^'"]+)['"]`,type:"function"},{pattern:`@Gate\\s*\\(['"]?([^'"\\)]+)['"]?\\)`,type:"function"}];for(let{pattern:o,type:a}of s){let i=E(e,o);for(let u of i.split(`
`).filter(Boolean)){let f=u.match(/^(.+?):(\d+):(.*)$/);if(f){let[,p,l,d]=f,g=d.match(new RegExp(o));if(g&&g[1]){let c=g[1].startsWith("^")?g[1].slice(1):g[1];t.push({gate:c,file:h.relative(e,p),line:parseInt(l,10),context:d.trim().slice(0,100),matchType:a});}}}}return t}function $(e){return [...new Set(e.map(t=>t.gate))]}async function w(e){let t=S(e);if(!t){let r=x(e),U=$(r);return U.length===0?{status:"compliant",declaredButUnused:[],routeAttachedUnused:[],orphanUnused:[],usedButUndeclared:[],properlyDeclared:[],suggestions:["No portal.yaml found, and no gate references detected in code."],references:[]}:{status:"violations",declaredButUnused:[],routeAttachedUnused:[],orphanUnused:[],usedButUndeclared:U,properlyDeclared:[],suggestions:["Gate references found in code but no portal.yaml exists.","Create a portal.yaml file to declare these gates:",...U.map(b=>`  - ^${b}`),"","Run: paradigm portal init"],references:r}}let n=C(t),s=B(t),o=x(e),a=$(o),i=new Set(n),u=new Set(a),f=n.filter(r=>!u.has(r)),p=f.filter(r=>s.has(r)),l=f.filter(r=>!s.has(r)),d=a.filter(r=>!i.has(r)),g=n.filter(r=>u.has(r)),c=[];if(p.length>0){c.push("Gates documented on routes but no checkGate/requireGate in code:");for(let r of p)c.push(`  - ^${r} (documented on routes; if enforced by middleware, this may be intentional)`);c.push("");}if(l.length>0){c.push("Orphan gates (declared but never on a route or in code):");for(let r of l)c.push(`  - ^${r} (add to a route or remove from portal.yaml)`);c.push("");}if(d.length>0){c.push("Gates used in code but not declared in portal.yaml:");for(let r of d)c.push(`  - ^${r} (add to portal.yaml with proper definition)`);c.push("");}let y="compliant";return d.length>0?y="violations":f.length>0&&(y="warnings"),{status:y,declaredButUnused:f,routeAttachedUnused:p,orphanUnused:l,usedButUndeclared:d,properlyDeclared:g,suggestions:c,references:o}}function _(e){let t=[],n=e.status==="compliant"?"\u2713":e.status==="warnings"?"\u26A0":"\u2717";if(t.push(`Portal Compliance: ${n} ${e.status.toUpperCase()}`),t.push(""),t.push(`Properly Declared: ${e.properlyDeclared.length}`),e.routeAttachedUnused.length>0&&t.push(`Route-Attached, No Code: ${e.routeAttachedUnused.length}`),e.orphanUnused.length>0&&t.push(`Orphan Gates: ${e.orphanUnused.length}`),e.usedButUndeclared.length>0&&t.push(`Used but Undeclared: ${e.usedButUndeclared.length}`),t.push(""),e.properlyDeclared.length>0){t.push("Gates in Use:");for(let s of e.properlyDeclared)t.push(`  \u2713 ^${s}`);t.push("");}if(e.routeAttachedUnused.length>0){t.push("Route-Attached (no checkGate/requireGate in code):");for(let s of e.routeAttachedUnused)t.push(`  \u26A0 ^${s}`);t.push("");}if(e.orphanUnused.length>0){t.push("Orphan Gates (declared but never on route or in code):");for(let s of e.orphanUnused)t.push(`  \u26A0 ^${s}`);t.push("");}if(e.usedButUndeclared.length>0){t.push("Undeclared Gates (used but not in portal.yaml):");for(let s of e.usedButUndeclared){t.push(`  \u2717 ^${s}`);let o=e.references.filter(a=>a.gate===s).slice(0,3);for(let a of o)t.push(`      at ${a.file}:${a.line}`);}t.push("");}if(e.suggestions.length>0&&e.status!=="compliant"){t.push("Suggestions:");for(let s of e.suggestions)s&&t.push(`  ${s}`);}return t.join(`
`)}function k(e){if(e.status==="compliant")return {status:"ok",message:`${e.properlyDeclared.length} gates properly declared`};if(e.status==="warnings"){let t=[];return e.routeAttachedUnused.length>0&&t.push(`${e.routeAttachedUnused.length} route-attached`),e.orphanUnused.length>0&&t.push(`${e.orphanUnused.length} orphan`),{status:"warn",message:t.length>0?t.join(", ")+" gate(s)":`${e.declaredButUnused.length} unused gates`}}return {status:"error",message:`${e.usedButUndeclared.length} gates used but not declared`}}export{S as a,C as b,x as c,w as d,_ as e,k as f};