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95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
import { createQueryHook } from '@/hooks/use-query';
import { backendApi } from '@/lib/api-client';
import { pipedreamKeys } from './keys';
import type {
  PipedreamProfile,
  CreateProfileRequest,
  UpdateProfileRequest,
  ProfileConnectionResponse,
  ProfileConnectionsResponse
} from '@/components/agents/pipedream/pipedream-types';

export interface CreateConnectionTokenRequest {
  app?: string;
}

export interface ConnectionTokenResponse {
  success: boolean;
  link?: string;
  token?: string;
  external_user_id: string;
  app?: string;
  expires_at?: string;
  error?: string;
}

export interface ConnectionResponse {
  success: boolean;
  connections: Connection[];
  count: number;
  error?: string;
}

export interface Connection {
  id: string;
  app: string;
  name: string;
  status: 'connected' | 'disconnected' | 'error';
  created_at: string;
  updated_at: string;
  [key: string]: any;
}

export interface PipedreamHealthCheckResponse {
  status: 'healthy' | 'unhealthy';
  project_id: string;
  environment: string;
  has_access_token: boolean;
  error?: string;
}

export interface TriggerWorkflowRequest {
  workflow_id: string;
  payload: Record<string, any>;
}

export interface TriggerWorkflowResponse {
  success: boolean;
  workflow_id: string;
  run_id?: string;
  status?: string;
  error?: string;
}

export interface WorkflowRun {
  id: string;
  workflow_id: string;
  status: 'running' | 'completed' | 'failed' | 'cancelled';
  started_at: string;
  completed_at?: string;
  error?: string;
  [key: string]: any;
}

export interface PipedreamConfigStatus {
  success: boolean;
  project_id: string;
  environment: string;
  has_client_id: boolean;
  has_client_secret: boolean;
  base_url: string;
}

export interface PipedreamApp {
  id: string;
  name: string;
  name_slug: string;
  auth_type: string;
  description: string;
  img_src: string;
  custom_fields_json: string;
  categories: string[];
  featured_weight: number;
  connect: {
    allowed_domains: string[] | null;
    base_proxy_target_url: string;
    proxy_enabled: boolean;
  };
}

export interface PipedreamAppResponse {
  success: boolean;
  apps: PipedreamApp[];
  page_info: {
    total_count: number;
    count: number;
    has_more: boolean;
    start_cursor?: string;
    end_cursor?: string;
  };
  total_count: number;
  error?: string;
  search_query?: string;
}

export interface PipedreamTool {
  name: string;
  description: string;
  inputSchema: any;
}

export interface PipedreamAppWithTools {
  app_name: string;
  app_slug: string;
  tools: PipedreamTool[];
  tool_count: number;
}

export interface PipedreamToolsResponse {
  success: boolean;
  apps: PipedreamAppWithTools[];
  total_apps: number;
  total_tools: number;
  user_id?: string;
  timestamp?: number;
  error?: string;
}

export interface AppIconResponse {
  success: boolean;
  app_slug: string;
  icon_url: string;
}

export const usePipedreamConnections = createQueryHook(
  pipedreamKeys.connections(),
  async (): Promise<ConnectionResponse> => {
    return await pipedreamApi.getConnections();
  },
  {
    staleTime: 10 * 60 * 1000,
    gcTime: 15 * 60 * 1000,
    refetchOnWindowFocus: false,
    refetchOnMount: false,
    refetchInterval: false,
  }
);

export const pipedreamApi = {
  async createConnectionToken(request: CreateConnectionTokenRequest = {}): Promise<ConnectionTokenResponse> {
    const result = await backendApi.post<ConnectionTokenResponse>(
      '/pipedream/connection-token',
      request,
      {
        errorContext: { operation: 'create connection token', resource: 'Pipedream connection' },
      }
    );

    if (!result.success) {
      throw new Error(result.error?.message || 'Failed to create connection token');
    }

    return result.data!;
  },

  async getConnections(): Promise<ConnectionResponse> {
    const result = await backendApi.get<ConnectionResponse>(
      '/pipedream/connections',
      {
        errorContext: { operation: 'load connections', resource: 'Pipedream connections' },
      }
    );

    if (!result.success) {
      throw new Error(result.error?.message || 'Failed to get connections');
    }

    return result.data!;
  },

  async getApps(after?: string, search?: string): Promise<PipedreamAppResponse> {
    const params = new URLSearchParams();
    
    if (after) {
      params.append('after', after);
    }
    
    if (search) {
      params.append('q', search);
    }
    
    const result = await backendApi.get<PipedreamAppResponse>(
      `/pipedream/apps${params.toString() ? `?${params.toString()}` : ''}`,
      {
        errorContext: { operation: 'load apps', resource: 'Pipedream apps' },
      }
    );

    if (!result.success) {
      throw new Error(result.error?.message || 'Failed to get apps');
    }
    const data = result.data!;
    if (!data.success && data.error) {
      throw new Error(data.error);
    }
    return data;
  },

  async getPopularApps(): Promise<PipedreamAppResponse> {
    const result = await backendApi.get<PipedreamAppResponse>(
      '/pipedream/apps/popular',
      {
        errorContext: { operation: 'load popular apps', resource: 'Pipedream popular apps' },
      }
    );
    console.log('result', result);
    if (!result.success) {
      throw new Error(result.error?.message || 'Failed to get popular apps');
    }
    const data = result.data!;
    if (!data.success && data.error) {
      throw new Error(data.error);
    }
    return data;
  },

  async getAvailableTools(): Promise<PipedreamToolsResponse> {
    const result = await backendApi.get<PipedreamToolsResponse>(
      '/pipedream/mcp/available-tools',
      {
        errorContext: { operation: 'load available tools', resource: 'Pipedream tools' },
      }
    );
    if (!result.success) {
      throw new Error(result.error?.message || 'Failed to get available tools');
    }

    return result.data!;
  },

  async healthCheck(): Promise<PipedreamHealthCheckResponse> {
    const result = await backendApi.get<PipedreamHealthCheckResponse>(
      '/pipedream/health',
      {
        errorContext: { operation: 'health check', resource: 'Pipedream service' },
      }
    );

    if (!result.success) {
      throw new Error(result.error?.message || 'Health check failed');
    }

    return result.data!;
  },

  async discoverMCPServers(externalUserId: string, appSlug?: string): Promise<any> {
    const request = {
      external_user_id: externalUserId,
      app_slug: appSlug
    };
    
    const result = await backendApi.post<any>(
      '/pipedream/mcp/discover-profile',
      request,
      {
        errorContext: { operation: 'discover MCP servers', resource: 'Pipedream MCP' },
      }
    );

    if (!result.success) {
      throw new Error(result.error?.message || 'Failed to discover MCP servers');
    }

    return result.data?.mcp_servers || [];
  },

  // Credential Profile Methods
  async createProfile(request: CreateProfileRequest): Promise<PipedreamProfile> {
    const result = await backendApi.post<PipedreamProfile>(
      '/pipedream/profiles',
      request,
      {
        errorContext: { operation: 'create profile', resource: 'Pipedream credential profile' },
      }
    );

    if (!result.success) {
      throw new Error(result.error?.message || 'Failed to create profile');
    }

    return result.data!;
  },

  async getProfiles(params?: { app_slug?: string; is_active?: boolean }): Promise<PipedreamProfile[]> {
    const queryParams = new URLSearchParams();
    if (params?.app_slug) queryParams.append('app_slug', params.app_slug);
    if (params?.is_active !== undefined) queryParams.append('is_active', params.is_active.toString());

    const result = await backendApi.get<PipedreamProfile[]>(
      `/pipedream/profiles${queryParams.toString() ? `?${queryParams.toString()}` : ''}`,
      {
        errorContext: { operation: 'get profiles', resource: 'Pipedream credential profiles' },
      }
    );

    if (!result.success) {
      throw new Error(result.error?.message || 'Failed to get profiles');
    }

    return result.data!;
  },

  async getProfile(profileId: string): Promise<PipedreamProfile> {
    const result = await backendApi.get<PipedreamProfile>(
      `/pipedream/profiles/${profileId}`,
      {
        errorContext: { operation: 'get profile', resource: 'Pipedream credential profile' },
      }
    );

    if (!result.success) {
      throw new Error(result.error?.message || 'Failed to get profile');
    }

    return result.data!;
  },

  async updateProfile(profileId: string, request: UpdateProfileRequest): Promise<PipedreamProfile> {
    const result = await backendApi.put<PipedreamProfile>(
      `/pipedream/profiles/${profileId}`,
      request,
      {
        errorContext: { operation: 'update profile', resource: 'Pipedream credential profile' },
      }
    );

    if (!result.success) {
      throw new Error(result.error?.message || 'Failed to update profile');
    }

    return result.data!;
  },

  async deleteProfile(profileId: string): Promise<void> {
    const result = await backendApi.delete(
      `/pipedream/profiles/${profileId}`,
      {
        errorContext: { operation: 'delete profile', resource: 'Pipedream credential profile' },
      }
    );

    if (!result.success) {
      throw new Error(result.error?.message || 'Failed to delete profile');
    }
  },

  async connectProfile(profileId: string, app?: string): Promise<ProfileConnectionResponse> {
    const queryParams = app ? `?app=${encodeURIComponent(app)}` : '';
    const result = await backendApi.post<ProfileConnectionResponse>(
      `/pipedream/profiles/${profileId}/connect${queryParams}`,
      {},
      {
        errorContext: { operation: 'connect profile', resource: 'Pipedream credential profile' },
      }
    );

    if (!result.success) {
      throw new Error(result.error?.message || 'Failed to connect profile');
    }

    return result.data!;
  },

  async getProfileConnections(profileId: string): Promise<ProfileConnectionsResponse> {
    const result = await backendApi.get<ProfileConnectionsResponse>(
      `/pipedream/profiles/${profileId}/connections`,
      {
        errorContext: { operation: 'get profile connections', resource: 'Pipedream profile connections' },
      }
    );

    if (!result.success) {
      throw new Error(result.error?.message || 'Failed to get profile connections');
    }

    return result.data!;
  },

  async getAppIcon(appSlug: string): Promise<AppIconResponse> {
    const result = await backendApi.get<AppIconResponse>(
      `/pipedream/apps/${appSlug}/icon`,
      {
        errorContext: { operation: 'get app icon', resource: 'Pipedream app icon' },
      }
    );
    if (!result.success) {
      throw new Error(result.error?.message || 'Failed to get app icon');
    } 
    return result.data!;
  },
};