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b83b49a
 
 
 
 
 
11d88bf
b83b49a
 
 
64137ed
b83b49a
 
 
 
 
11d88bf
b83b49a
 
a7ba805
64137ed
 
b4cf038
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
432b22b
 
 
 
 
 
 
 
 
b4cf038
d53dcb6
 
 
 
 
 
 
98f89fc
59b5a86
98f89fc
 
 
 
 
 
 
d53dcb6
 
59b5a86
 
 
 
 
 
 
 
d53dcb6
3b93905
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
import { Router } from '@angular/router';
import { AuthService } from './auth.service';

// Interfaces
export interface API {
  name: string;
  url: string;
  method: string;
  headers?: any;
  body_template?: any;
  timeout_seconds: number;
  retry?: {
    retry_count: number;
    backoff_seconds: number;
    strategy: string;
  };
  auth?: {
    enabled: boolean;
    token_endpoint?: string;
    response_token_path?: string;
    token_request_body?: any;
    token_refresh_endpoint?: string;
    token_refresh_body?: any;
  };
  response_prompt?: string;
  response_mappings?: ResponseMapping[];  // Yeni alan
  deleted?: boolean;
  last_update_date?: string;
  last_update_user?: string;
}

export interface ResponseMapping {
  variable_name: string;
  type: 'str' | 'int' | 'float' | 'bool' | 'date';
  json_path: string;
  caption: string;
}

export interface IntentParameter {
  name: string;
  caption: string;
  type: 'str' | 'int' | 'float' | 'bool' | 'date';
  required: boolean;
  variable_name: string;
  extraction_prompt?: string;
  validation_regex?: string;
  invalid_prompt?: string;
  type_error_prompt?: string;
}

export interface Intent {
  name: string;
  caption: string;
  locale: string;
  detection_prompt: string;
  examples: string[];
  parameters: IntentParameter[];
  action: string;
  fallback_timeout_prompt?: string;
  fallback_error_prompt?: string;
}

export interface GenerationConfig {
  max_new_tokens: number;
  temperature: number;
  top_p: number;
  top_k?: number;
  repetition_penalty?: number;
  do_sample?: boolean;
  num_beams?: number;
  length_penalty?: number;
  early_stopping?: boolean;
}

export interface LLMConfig {
  repo_id: string;
  generation_config: GenerationConfig;  // any yerine GenerationConfig
  use_fine_tune: boolean;
  fine_tune_zip: string;
}

export interface Version {
  id: number;
  caption?: string;
  description?: string;
  published: boolean;
  general_prompt?: string;
  llm: LLMConfig;  // inline yerine LLMConfig
  intents: Intent[];
  parameters: any[];
  last_update_date?: string;
}

export interface Project {
  id: number;
  name: string;
  caption: string;
  enabled: boolean;
  icon?: string; 
  versions: Version[];
  last_update_date?: string;
  deleted?: boolean;
  created_date?: string;
  created_by?: string;
  last_update_user?: string;
}

export interface ParameterCollectionConfig {
  max_params_per_question: number;
  smart_grouping: boolean;
  retry_unanswered: boolean;
  collection_prompt: string;
}

export interface Environment {
  work_mode: string;
  cloud_token: string;
  spark_endpoint: string;
  internal_prompt?: string;
  tts_engine?: string;
  tts_engine_api_key?: string;
  tts_settings?: TTSSettings;
  stt_engine?: string;
  stt_engine_api_key?: string;
  stt_settings?: STTSettings;
  parameter_collection_config?: ParameterCollectionConfig;
}

export interface STTSettings {
  speech_timeout_ms: number;
  noise_reduction_level: number;
  vad_sensitivity: number;
  language: string;
  model: string;
  use_enhanced: boolean;
  enable_punctuation: boolean;
  interim_results: boolean;
}

export interface TTSSettings {
  use_ssml: boolean;
}

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  private apiUrl = '/api';

  constructor(
    private http: HttpClient,
    private router: Router,
    private authService: AuthService
  ) {}

  // ===================== Auth =====================
  login(username: string, password: string): Observable<any> {
    return this.http.post(`${this.apiUrl}/login`, { username, password }).pipe(
      tap((response: any) => {
        this.authService.setToken(response.token);
        this.authService.setUsername(response.username);
      })
    );
  }

  logout(): void {
    this.authService.logout();
  }

  private getAuthHeaders(): HttpHeaders {
    const token = this.authService.getToken();
    return new HttpHeaders({
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    });
  }

  // ===================== User =====================
  changePassword(currentPassword: string, newPassword: string): Observable<any> {
    return this.http.post(
      `${this.apiUrl}/change-password`,
      { current_password: currentPassword, new_password: newPassword },
      { headers: this.getAuthHeaders() }
    ).pipe(
      catchError(this.handleError)
    );
  }

  // ===================== Environment =====================
  getEnvironment(): Observable<Environment> {
    return this.http.get<Environment>(`${this.apiUrl}/environment`, {
      headers: this.getAuthHeaders()
    }).pipe(
      catchError(this.handleError)
    );
  }

  updateEnvironment(data: Environment): Observable<any> {
    return this.http.put(`${this.apiUrl}/environment`, data, {
      headers: this.getAuthHeaders()
    }).pipe(
      catchError(this.handleError)
    );
  }

  // ===================== Projects =====================
  getProjects(includeDeleted = false): Observable<Project[]> {
    return this.http.get<Project[]>(`${this.apiUrl}/projects`, {
      headers: this.getAuthHeaders(),
      params: { include_deleted: includeDeleted.toString() }
    }).pipe(
      catchError(this.handleError)
    );
  }

  getProject(id: number): Observable<Project> {
    return this.http.get<Project>(`/api/projects/${id}`);
  }
  
  createProject(data: any): Observable<any> {
    return this.http.post(`${this.apiUrl}/projects`, data, {
      headers: this.getAuthHeaders()
    }).pipe(
      catchError(this.handleError)
    );
  }

  updateProject(id: number, data: any): Observable<any> {
    return this.http.put(`${this.apiUrl}/projects/${id}`, data, {
      headers: this.getAuthHeaders()
    }).pipe(
      catchError(this.handleError)
    );
  }

  deleteProject(id: number): Observable<any> {
    return this.http.delete(`${this.apiUrl}/projects/${id}`, {
      headers: this.getAuthHeaders()
    }).pipe(
      catchError(this.handleError)
    );
  }

  toggleProject(id: number): Observable<any> {
    return this.http.patch(`${this.apiUrl}/projects/${id}/toggle`, {}, {
      headers: this.getAuthHeaders()
    }).pipe(
      catchError(this.handleError)
    );
  }

  exportProject(id: number): Observable<any> {
    return this.http.get(`${this.apiUrl}/projects/${id}/export`, {
      headers: this.getAuthHeaders()
    }).pipe(
      catchError(this.handleError)
    );
  }

  importProject(data: any): Observable<any> {
    return this.http.post(`${this.apiUrl}/projects/import`, data, {
      headers: this.getAuthHeaders()
    }).pipe(
      catchError(this.handleError)
    );
  }

  // ===================== Versions =====================
  createVersion(projectId: number, data: any): Observable<any> {
    return this.http.post(`${this.apiUrl}/projects/${projectId}/versions`, data, {
      headers: this.getAuthHeaders()
    }).pipe(
      catchError(this.handleError)
    );
  }

  updateVersion(projectId: number, versionId: number, data: any, force: boolean = false): Observable<any> {
    return this.http.put(
      `${this.apiUrl}/projects/${projectId}/versions/${versionId}${force ? '?force=true' : ''}`, 
      data, 
      { headers: this.getAuthHeaders() }
    ).pipe(
      catchError(this.handleError)
    );
  }

  deleteVersion(projectId: number, versionId: number): Observable<any> {
    return this.http.delete(`${this.apiUrl}/projects/${projectId}/versions/${versionId}`, {
      headers: this.getAuthHeaders()
    }).pipe(
      catchError(this.handleError)
    );
  }

  publishVersion(projectId: number, versionId: number): Observable<any> {
    return this.http.post(`${this.apiUrl}/projects/${projectId}/versions/${versionId}/publish`, {}, {
      headers: this.getAuthHeaders()
    }).pipe(
      catchError(this.handleError)
    );
  }

  // ===================== APIs =====================
  getAPIs(includeDeleted = false): Observable<API[]> {
    return this.http.get<API[]>(`${this.apiUrl}/apis`, {
      headers: this.getAuthHeaders(),
      params: { include_deleted: includeDeleted.toString() }
    }).pipe(
      catchError(this.handleError)
    );
  }

  createAPI(data: any): Observable<any> {
    return this.http.post(`${this.apiUrl}/apis`, data, {
      headers: this.getAuthHeaders()
    }).pipe(
      catchError(this.handleError)
    );
  }

  updateAPI(name: string, data: any): Observable<any> {
    return this.http.put(`${this.apiUrl}/apis/${name}`, data, {
      headers: this.getAuthHeaders()
    }).pipe(
      catchError(this.handleError)
    );
  }

  deleteAPI(name: string): Observable<any> {
    return this.http.delete(`${this.apiUrl}/apis/${name}`, {
      headers: this.getAuthHeaders()
    }).pipe(
      catchError(this.handleError)
    );
  }

  testAPI(data: any): Observable<any> {
    return this.http.post(`${this.apiUrl}/apis/test`, data, {
      headers: this.getAuthHeaders()
    }).pipe(
      catchError(this.handleError)
    );
  }

  // ===================== Spark Integration =====================
  sparkStartup(projectName: string): Observable<any> {
    return this.http.post(`${this.apiUrl}/spark/startup`, 
      { project_name: projectName }, 
      { headers: this.getAuthHeaders() }
    ).pipe(
      catchError(this.handleError)
    );
  }
  
  sparkGetProjects(): Observable<any> {
    return this.http.get(`${this.apiUrl}/spark/projects`, {
      headers: this.getAuthHeaders()
    }).pipe(
      catchError(this.handleError)
    );
  }
  
  sparkEnableProject(projectName: string): Observable<any> {
    return this.http.post(`${this.apiUrl}/spark/project/enable`, 
      { project_name: projectName }, 
      { headers: this.getAuthHeaders() }
    ).pipe(
      catchError(this.handleError)
    );
  }
  
  sparkDisableProject(projectName: string): Observable<any> {
    return this.http.post(`${this.apiUrl}/spark/project/disable`, 
      { project_name: projectName }, 
      { headers: this.getAuthHeaders() }
    ).pipe(
      catchError(this.handleError)
    );
  }
  
  sparkDeleteProject(projectName: string): Observable<any> {
    return this.http.delete(`${this.apiUrl}/spark/project/${projectName}`, {
      headers: this.getAuthHeaders()
    }).pipe(
      catchError(this.handleError)
    );
  }
  
  // ===================== Tests =====================
  runTests(testType: string): Observable<any> {
    return this.http.post(`${this.apiUrl}/test/run-all`, { test_type: testType }, {
      headers: this.getAuthHeaders()
    }).pipe(
      catchError(this.handleError)
    );
  }

  // ===================== Activity Log =====================
  getActivityLog(limit = 50): Observable<any[]> {
    return this.http.get<any[]>(`${this.apiUrl}/activity-log`, {
      headers: this.getAuthHeaders(),
      params: { limit: limit.toString() }
    }).pipe(
      catchError(this.handleError)
    );
  }

  // ===================== Validation =====================
  validateRegex(pattern: string, testValue: string): Observable<any> {
    return this.http.post(`${this.apiUrl}/validate/regex`, 
      { pattern, test_value: testValue }, 
      { headers: this.getAuthHeaders() }
    ).pipe(
      catchError(this.handleError)
    );
  }

  // ===================== Chat =====================
  /* 1️⃣  Proje isimleri (combo’yu doldurmak için) */
  getChatProjects() {
    return this.http.get<string[]>(`${this.apiUrl}/projects/names`);
  }

  /* 2️⃣  Oturum başlat */
  startChat(projectName: string) {
    return this.http.post<{
      session_id: string;
      answer: string;
    }>(`${this.apiUrl}/start_session`, { project_name: projectName });
  }

  /* 3️⃣  Mesaj gönder/al */
  chat(sessionId: string, text: string) {
    const headers = new HttpHeaders().set('X-Session-ID', sessionId);
    return this.http.post<{
      session_id: string;
      answer: string;
    }>(
      `${this.apiUrl}/chat`,
      { user_input: text },
      { headers }
    );
  }

  // ===================== TTS =====================
  generateTTS(text: string, voiceId?: string, modelId?: string, outputFormat: string = 'mp3_44100_128'): Observable<Blob> {
    const body = {
      text,
      voice_id: voiceId,
      model_id: modelId,
      output_format: outputFormat
    };

    return this.http.post(`${this.apiUrl}/tts/generate`, body, {
      headers: this.getAuthHeaders(),
      responseType: 'blob'
    }).pipe(
      catchError(this.handleError)
    );
  }

  // ===================== Locale =====================
  getAvailableLocales(): Observable<any> {
    return this.http.get(`${this.apiUrl}/locales`, { headers: this.getAuthHeaders() });
  }
  
  getLocaleDetails(code: string): Observable<any> {
    return this.http.get(`${this.apiUrl}/locales/${code}`, { headers: this.getAuthHeaders() });
  }
  
  // ===================== Error Handler =====================
  private handleError(error: any) {
    console.error('API Error:', error);
    
    if (error.status === 401) {
      // Token expired or invalid
      this.authService.logout();
    } else if (error.status === 409) {
      // Race condition error
      const message = error.error?.detail || 'Resource was modified by another user';
      
      return throwError(() => ({
        ...error,
        userMessage: message,
        requiresReload: true
      }));
    }
    
    // Ensure error object has proper structure
    const errorResponse = {
      status: error.status,
      error: error.error || { detail: error.message || 'Unknown error' },
      message: error.error?.detail || error.error?.message || error.message || 'Unknown error'
    };
    
    return throwError(() => errorResponse);
  }
}