import{aW as w,d7 as D,bV as Q,d8 as K,d3 as O,r as l,a$ as y,j as U}from"./index-CfKY7XrC.js";import{a as N}from"./sortable.esm-CHIiExJi.js";function M(r,s){return s.find(d=>d.providerId===r)?.name??r}function B(r,s){const d=(r?.installedProviders??[]).map(o=>o.providerId),u=new Map;for(const o of r?.authProfiles??[])u.has(o.provider)||u.set(o.provider,o);const f=[...d];for(const o of u.keys())f.includes(o)||f.push(o);return f.map(o=>{const i=u.get(o),h=s.find(e=>e.providerId===o);return{providerId:o,authType:i?.authType??h?.authType??"api-key",credential:"",modelPreference:r?.providerModelPreferences?.[o]??"",existingProfile:i}})}function F(r,s,d,u){return u?.trim()?u.trim():d?d.length<=8?`${r} (${s})`:`${r} ${d.slice(0,4)}...${d.slice(-4)}`:`${r} (${s})`}function V(r,s){return r.credential.trim()||s?.systemAvailable?!0:r.existingProfile?.authType===r.authType}function W(r,s,d){const u=new Map((s.installedProviders??[]).map(e=>[e.providerId,e])),f=new Map(d.map(e=>[e.providerId,e])),o=r.map(e=>{const t=u.get(e.providerId);return{providerId:e.providerId,installedAt:t?.installedAt??Date.now(),...t?.config?{config:t.config}:{}}}),i=Object.fromEntries(r.map(e=>[e.providerId,e.modelPreference.trim()]).filter(([e,t])=>{if(t.length===0)return!1;const v=f.get(e),g=r.find(m=>m.providerId===e);return g?V(g,v):!1}));return{authProfiles:r.map(e=>{const t=e.credential.trim(),v=e.existingProfile;if(!t)return v?.authType===e.authType?v:null;const g=M(e.providerId,d);return{id:v?.id??crypto.randomUUID(),provider:e.providerId,model:v?.model??"*",credential:t,label:F(g,e.authType,t,v?.label),authType:e.authType,...v?.metadata?{metadata:v.metadata}:{},createdAt:v?.createdAt??Date.now()}}).filter(e=>e!==null),installedProviders:o,providerModelPreferences:Object.keys(i).length>0?i:void 0}}function x(r){const s=r[0];return!!s&&s.modelPreference.trim().length===0}const R=l.createContext(null);function H({agentId:r,children:s}){const d=w(),{slug:u}=D(),{data:f,isLoading:o}=Q(r),{data:i,isLoading:h}=K(r),e=O(r),t=l.useMemo(()=>f?B(f,i?.catalog??[]):[],[f,i]),[v,g]=l.useState(null),m=v??t,k=l.useCallback((p,n)=>{g(a=>(a??t).map(c=>c.providerId===p?{...c,...n}:c))},[t]),P=l.useCallback(async(p,n)=>{if(!f)return y.error("Still loading agent settings — try again in a moment"),!1;if(x(p))return y.error("Pick a model for the primary provider before saving"),!1;try{const a=W(p,f,i?.catalog??[]);return await e.mutateAsync(a),y.success(n),!0}catch(a){return y.error(a instanceof Error?a.message:"Failed to save providers"),!1}},[f,i?.catalog,e]),T=l.useCallback((p,n)=>{g(a=>{const c=a??t,C=c.findIndex(b=>b.providerId===p),A=c.findIndex(b=>b.providerId===n);if(C<0||A<0||C===A)return c;const I=N(c,C,A);if(x(I)){const b=M(I[0]?.providerId??"",i?.catalog??[]);return y.error(`Pick a model for ${b} before making it primary`),c}return P(I,"Provider order updated"),I})},[P,i?.catalog,t]),E=l.useCallback(p=>{g(n=>(n??t).filter(a=>a.providerId!==p))},[t]),$=l.useCallback(async p=>{const n=m.filter(a=>a.providerId!==p);if(n.length>0&&x(n)){const a=M(n[0]?.providerId??"",i?.catalog??[]);return y.error(`Pick a model for ${a} before removing this provider`),!1}return g(n),P(n,"Provider removed")},[P,i?.catalog,m]),S=l.useCallback(p=>{const n=i?.catalog.find(a=>a.providerId===p);n&&g(a=>{const c=a??t;return c.some(C=>C.providerId===n.providerId)?c:[...c,{providerId:n.providerId,authType:n.authType,credential:"",modelPreference:""}]})},[i?.catalog,t]),j=l.useCallback(async()=>{await Promise.all([d.invalidateQueries({queryKey:["agent-config"]}).catch(()=>{}),d.invalidateQueries({queryKey:["agent-provider-catalog"]}).catch(()=>{}),d.invalidateQueries({queryKey:["agent"]}).catch(()=>{})])},[d]),L=l.useCallback(async()=>{await P(m,"Providers saved")},[P,m]),q=l.useMemo(()=>({agentId:r,slug:u??"",providerRows:m,catalog:i,isLoading:o||h,isSaving:e.isPending,addProvider:S,removeProvider:E,removeProviderAndSave:$,reorderProviders:T,updateProviderRow:k,saveProviders:L,refreshProviderAuthState:j,primaryModelMissing:x(m)}),[S,r,h,o,T,i,m,j,E,$,L,u,e.isPending,k]);return U.jsx(R.Provider,{value:q,children:s})}function J(){const r=l.useContext(R);if(!r)throw new Error("useAgentProviderEditor must be used within AgentProviderEditorProvider");return r}export{H as A,V as c,J as u};
