File size: 25,468 Bytes
42e8706
390f720
8648eb1
42e8706
 
 
 
 
 
390f720
 
42e8706
 
 
 
 
 
 
 
 
390f720
 
 
 
42e8706
 
 
c0cb4d0
42e8706
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
abea6d7
42e8706
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
abea6d7
 
 
 
 
42e8706
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
636c3f7
 
42e8706
636c3f7
a0f9d12
 
2269987
636c3f7
42e8706
a0f9d12
636c3f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0f9d12
 
 
636c3f7
a0f9d12
abea6d7
 
42e8706
2269987
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42e8706
 
bca1df7
42e8706
 
 
 
bca1df7
 
42e8706
 
 
 
bca1df7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42e8706
 
59136fb
 
 
 
 
 
 
42e8706
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
390f720
42e8706
bca1df7
 
 
42e8706
 
 
 
bca1df7
 
 
 
 
42e8706
 
 
 
bca1df7
42e8706
 
bca1df7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42e8706
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbec022
 
42e8706
bbec022
42e8706
 
c0cb4d0
2888e07
c0cb4d0
2888e07
c0cb4d0
2888e07
c0cb4d0
42e8706
2888e07
42e8706
 
2888e07
 
 
 
42e8706
2888e07
42e8706
2888e07
 
 
 
 
 
 
 
 
bbec022
 
2888e07
 
 
 
 
bbec022
2888e07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42e8706
2888e07
 
42e8706
2888e07
42e8706
 
 
 
 
06b847d
7193183
 
 
 
 
 
bca1df7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42e8706
390f720
bca1df7
0c17bf3
f487b76
42e8706
06b847d
 
bca1df7
c72fcba
0c17bf3
bca1df7
 
2269987
0c17bf3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bca1df7
 
1e38a52
c72fcba
1e38a52
42e8706
f487b76
42e8706
 
bca1df7
42e8706
abea6d7
 
42e8706
1e38a52
 
 
 
 
 
42e8706
bca1df7
 
42e8706
bca1df7
 
c72fcba
2269987
 
c72fcba
 
 
 
 
 
 
 
 
42e8706
 
0c17bf3
2269987
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42e8706
 
 
 
 
 
 
 
 
 
390f720
42e8706
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
390f720
42e8706
 
 
 
 
 
 
390f720
42e8706
390f720
42e8706
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
390f720
42e8706
 
390f720
42e8706
 
 
 
 
390f720
42e8706
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
390f720
42e8706
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
390f720
42e8706
 
 
 
390f720
42e8706
 
bb05395
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42e8706
bb05395
390f720
42e8706
390f720
 
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
import { Component, Inject, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormArray, FormsModule } from '@angular/forms';  
import { MatDialogRef, MAT_DIALOG_DATA, MatDialogModule, MatDialog } from '@angular/material/dialog';
import { MatTabsModule } from '@angular/material/tabs';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { MatTableModule } from '@angular/material/table';
import { MatChipsModule } from '@angular/material/chips';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatDividerModule } from '@angular/material/divider';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatListModule } from '@angular/material/list';
import { ApiService, Project, Version } from '../../services/api.service';
import ConfirmDialogComponent from '../confirm-dialog/confirm-dialog.component';

@Component({
  selector: 'app-version-edit-dialog',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    FormsModule,
    MatDialogModule,
    MatTabsModule,
    MatFormFieldModule,
    MatInputModule,
    MatSelectModule,
    MatCheckboxModule,
    MatButtonModule,
    MatIconModule,
    MatSnackBarModule,
    MatTableModule,
    MatChipsModule,
    MatExpansionModule,
    MatDividerModule,
    MatProgressBarModule,
    MatListModule
  ],
  templateUrl: './version-edit-dialog.component.html',
  styleUrls: ['./version-edit-dialog.component.scss']
})
export default class VersionEditDialogComponent implements OnInit {
  project: Project;
  versions: Version[] = [];
  selectedVersion: Version | null = null;
  versionForm!: FormGroup;
  
  loading = false;
  saving = false;
  publishing = false;
  creating = false;
  isDirty = false;
  
  selectedTabIndex = 0;
  testUserMessage = '';
  testResult: any = null;
  testing = false;

  constructor(
    private fb: FormBuilder,
    private apiService: ApiService,
    private snackBar: MatSnackBar,
    private dialog: MatDialog,
    public dialogRef: MatDialogRef<VersionEditDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any
  ) {
    this.project = data.project;
    this.versions = [...this.project.versions].sort((a, b) => b.id - a.id);
  }

  ngOnInit() {
    this.initializeForm();
    
    // Select the latest unpublished version or the latest version
    const unpublished = this.versions.find(v => !v.published);
    this.selectedVersion = unpublished || this.versions[0] || null;
    
    if (this.selectedVersion) {
      this.loadVersion(this.selectedVersion);
    }

    this.versionForm.valueChanges.subscribe(() => {
      this.isDirty = true;
    });

  }

  initializeForm() {
    this.versionForm = this.fb.group({
      id: [{value: '', disabled: true}],
      caption: ['', Validators.required],
      published: [{value: false, disabled: true}],
      general_prompt: ['', Validators.required],
      llm: this.fb.group({
        repo_id: ['', Validators.required],
        generation_config: this.fb.group({
          max_new_tokens: [256, [Validators.required, Validators.min(1), Validators.max(2048)]],
          temperature: [0.2, [Validators.required, Validators.min(0), Validators.max(2)]],
          top_p: [0.8, [Validators.required, Validators.min(0), Validators.max(1)]],
          repetition_penalty: [1.1, [Validators.required, Validators.min(1), Validators.max(2)]]
        }),
        use_fine_tune: [false],
        fine_tune_zip: ['']
      }),
      intents: this.fb.array([]),
      last_update_date: ['']
    });

    // Watch for fine-tune toggle
    this.versionForm.get('llm.use_fine_tune')?.valueChanges.subscribe(useFineTune => {
      const fineTuneControl = this.versionForm.get('llm.fine_tune_zip');
      if (useFineTune) {
        fineTuneControl?.setValidators([Validators.required]);
      } else {
        fineTuneControl?.clearValidators();
        fineTuneControl?.setValue('');
      }
      fineTuneControl?.updateValueAndValidity();
    });
  }

  loadVersion(version: Version) {
    this.selectedVersion = version;
    
    // Form değerlerini set et
    this.versionForm.patchValue({
      id: version.id,
      caption: version.caption || '',
      published: version.published || false,
      general_prompt: (version as any).general_prompt || '', // Backend'den gelen general_prompt
      last_update_date: version.last_update_date || ''
    });
  
    // LLM config'i ayrı set et
    if (version.llm) {
      this.versionForm.patchValue({
        llm: {
          repo_id: version.llm.repo_id || '',
          generation_config: version.llm.generation_config || {
            max_new_tokens: 512,
            temperature: 0.7,
            top_p: 0.95,
            repetition_penalty: 1.1
          },
          use_fine_tune: version.llm.use_fine_tune || false,
          fine_tune_zip: version.llm.fine_tune_zip || ''
        }
      });
    }
  
    // Clear and rebuild intents
    this.intents.clear();
    (version.intents || []).forEach(intent => {
      this.intents.push(this.createIntentFormGroup(intent));
    });

    this.isDirty = false;
  }
  
  async loadVersions() {
    this.loading = true;
    try {
      const project = await this.apiService.getProject(this.project.id).toPromise();
      if (project) {
        this.project = project;
        this.versions = [...project.versions].sort((a, b) => b.id - a.id);
        
        // Re-select current version if it still exists
        if (this.selectedVersion) {
          const currentVersion = this.versions.find(v => v.id === this.selectedVersion!.id);
          if (currentVersion) {
            this.loadVersion(currentVersion);
          } else if (this.versions.length > 0) {
            this.loadVersion(this.versions[0]);
          }
        } else if (this.versions.length > 0) {
          this.loadVersion(this.versions[0]);
        }
      }
    } catch (error) {
      this.snackBar.open('Failed to reload versions', 'Close', { duration: 3000 });
    } finally {
      this.loading = false;
    }
  }

  createIntentFormGroup(intent: any = {}): FormGroup {
    const group = this.fb.group({
      name: [intent.name || '', [Validators.required, Validators.pattern(/^[a-zA-Z0-9-]+$/)]],
      caption: [intent.caption || ''],
      locale: [intent.locale || 'tr-TR'],
      detection_prompt: [intent.detection_prompt || '', Validators.required],
      examples: this.fb.array([]),
      parameters: this.fb.array([]),
      action: [intent.action || '', Validators.required],
      fallback_timeout_prompt: [intent.fallback_timeout_prompt || ''],
      fallback_error_prompt: [intent.fallback_error_prompt || '']
    });
  
    // Examples ve parameters'ı ayrı olarak ekle
    if (intent.examples && Array.isArray(intent.examples)) {
      const examplesArray = group.get('examples') as FormArray;
      intent.examples.forEach((example: string) => {
        examplesArray.push(this.fb.control(example));
      });
    }
  
    if (intent.parameters && Array.isArray(intent.parameters)) {
      const parametersArray = group.get('parameters') as FormArray;
      intent.parameters.forEach((param: any) => {
        parametersArray.push(this.createParameterFormGroup(param));
      });
    }
  
    return group;
  }

  private populateIntentParameters(intentFormGroup: FormGroup, parameters: any[]) {
    const parametersArray = intentFormGroup.get('parameters') as FormArray;
    parameters.forEach(param => {
      parametersArray.push(this.createParameterFormGroup(param));
    });
  }  

  createParameterFormGroup(param: any = {}): FormGroup {
    return this.fb.group({
      name: [param.name || '', [Validators.required, Validators.pattern(/^[a-zA-Z0-9_]+$/)]],
      caption: [param.caption || ''],
      type: [param.type || 'str', Validators.required],
      required: [param.required !== false],
      variable_name: [param.variable_name || '', Validators.required],
      extraction_prompt: [param.extraction_prompt || ''],
      validation_regex: [param.validation_regex || ''],
      invalid_prompt: [param.invalid_prompt || ''],
      type_error_prompt: [param.type_error_prompt || '']
    });
  }

  get intents() {
    return this.versionForm.get('intents') as FormArray;
  }

  getIntentParameters(intentIndex: number): FormArray {
    return this.intents.at(intentIndex).get('parameters') as FormArray;
  }

  getIntentExamples(intentIndex: number): FormArray {
    return this.intents.at(intentIndex).get('examples') as FormArray;
  }

  addIntent() {
    this.intents.push(this.createIntentFormGroup());
  }

  removeIntent(index: number) {
    const intent = this.intents.at(index).value;
    const dialogRef = this.dialog.open(ConfirmDialogComponent, {
      width: '400px',
      data: {
        title: 'Delete Intent',
        message: `Are you sure you want to delete intent "${intent.name}"?`,
        confirmText: 'Delete',
        confirmColor: 'warn'
      }
    });

    dialogRef.afterClosed().subscribe(confirmed => {
      if (confirmed) {
        this.intents.removeAt(index);
      }
    });
  }

  async editIntent(intentIndex: number) {
    const { default: IntentEditDialogComponent } = await import('../intent-edit-dialog/intent-edit-dialog.component');
    
    const intent = this.intents.at(intentIndex);
    const currentValue = intent.value;
    
    // Intent verilerini dialog'a gönder
    const dialogRef = this.dialog.open(IntentEditDialogComponent, {
      width: '90vw',
      maxWidth: '1000px',
      data: { 
        intent: {
          ...currentValue,
          examples: currentValue.examples || [],
          parameters: currentValue.parameters || []
        },
        project: this.project,
        apis: await this.getAvailableAPIs()
      }
    });
  
    dialogRef.afterClosed().subscribe(result => {
      if (result) {
        // FormArray'leri yeniden oluştur
        intent.patchValue({
          name: result.name,
          caption: result.caption,
          locale: result.locale,
          detection_prompt: result.detection_prompt,
          action: result.action,
          fallback_timeout_prompt: result.fallback_timeout_prompt,
          fallback_error_prompt: result.fallback_error_prompt
        });
  
        // Examples'ı güncelle
        const examplesArray = intent.get('examples') as FormArray;
        examplesArray.clear();
        (result.examples || []).forEach((example: string) => {
          examplesArray.push(this.fb.control(example));
        });
  
        // Parameters'ı güncelle
        const parametersArray = intent.get('parameters') as FormArray;
        parametersArray.clear();
        (result.parameters || []).forEach((param: any) => {
          parametersArray.push(this.createParameterFormGroup(param));
        });
      }
    });
  }

  addParameter(intentIndex: number) {
    const parameters = this.getIntentParameters(intentIndex);
    parameters.push(this.createParameterFormGroup());
  }

  removeParameter(intentIndex: number, paramIndex: number) {
    const parameters = this.getIntentParameters(intentIndex);
    parameters.removeAt(paramIndex);
  }

  addExample(intentIndex: number, example: string) {
    if (example.trim()) {
      const examples = this.getIntentExamples(intentIndex);
      examples.push(this.fb.control(example));
    }
  }

  removeExample(intentIndex: number, exampleIndex: number) {
    const examples = this.getIntentExamples(intentIndex);
    examples.removeAt(exampleIndex);
  }

  async createVersion() {
    const publishedVersions = this.versions.filter(v => v.published);
    
    const dialogRef = this.dialog.open(ConfirmDialogComponent, {
      width: '500px',
      data: {
        title: 'Create New Version',
        message: 'Which published version would you like to use as a base for the new version?',
        showDropdown: true,
        dropdownOptions: publishedVersions.map(v => ({  // ✅ publishedVersions kullan
          value: v.id,
          label: `Version ${v.id} - ${v.caption || 'No description'}`
        })),
        dropdownPlaceholder: 'Select published version (or leave empty for blank)',
        confirmText: 'Create',
        cancelText: 'Cancel'
      }
    });
  
    dialogRef.afterClosed().subscribe(async (result) => {
      if (result?.confirmed) {
        this.loading = true;
        try {
          let newVersionData;
          
          if (result.selectedValue) {
            // Copy from selected version
            const sourceVersion = this.versions.find(v => v.id === result.selectedValue);
            if (sourceVersion) {
              newVersionData = {
                ...sourceVersion,
                id: undefined,
                published: false,
                last_update_date: undefined,
                caption: `Copy of version ${sourceVersion.id}`,
                description: sourceVersion.caption ? `Copy of ${sourceVersion.caption}` : `Copy of version ${sourceVersion.id}`
              };
            }
          } else {
            // Create blank version
            newVersionData = {
              caption: `Version ${this.versions.length + 1}`,
              description: 'New version',
              default_api: '',
              published: false,
              llm: {
                repo_id: '',
                generation_config: {
                  max_new_tokens: 512,
                  temperature: 0.7,
                  top_p: 0.95,
                  top_k: 50,
                  repetition_penalty: 1.1
                },
                use_fine_tune: false,
                fine_tune_zip: ''
              },
              intents: [],
              parameters: []
            };
          }
  
          if (newVersionData) {
            await this.apiService.createVersion(this.project.id, newVersionData).toPromise();
            await this.loadVersions();
            this.snackBar.open('Version created successfully!', 'Close', { duration: 3000 });
          }
        } catch (error) {
          this.snackBar.open('Failed to create version', 'Close', { duration: 3000 });
        } finally {
          this.loading = false;
        }
      }
    });
  }

  async saveVersion() {
    if (!this.selectedVersion) {
      this.snackBar.open('No version selected', 'Close', { duration: 3000 });
      return;
    }
    
    if (this.versionForm.invalid) {
      const invalidFields: string[] = [];
      Object.keys(this.versionForm.controls).forEach(key => {
        const control = this.versionForm.get(key);
        if (control && control.invalid) {
          invalidFields.push(key);
        }
      });
      
      this.intents.controls.forEach((intent, index) => {
        if (intent.invalid) {
          invalidFields.push(`Intent ${index + 1}`);
        }
      });
  
      this.snackBar.open(`Please fix validation errors in: ${invalidFields.join(', ')}`, 'Close', { 
        duration: 5000 
      });
      return;
    }
  
    const currentVersion = this.selectedVersion!;
  
    this.saving = true;
    
    try {
      const formValue = this.versionForm.getRawValue();
      
      // updateData'yı backend'in beklediği formatta hazırla
      const updateData = {
        caption: formValue.caption,
        general_prompt: formValue.general_prompt || '', // Bu alan eksikti
        llm: formValue.llm,
        intents: formValue.intents.map((intent: any) => ({
          name: intent.name,
          caption: intent.caption,
          locale: intent.locale,
          detection_prompt: intent.detection_prompt,
          examples: Array.isArray(intent.examples) ? intent.examples.filter((ex: any) => ex) : [],
          parameters: Array.isArray(intent.parameters) ? intent.parameters.map((param: any) => ({
            name: param.name,
            caption: param.caption,
            type: param.type,
            required: param.required,
            variable_name: param.variable_name,
            extraction_prompt: param.extraction_prompt,
            validation_regex: param.validation_regex,
            invalid_prompt: param.invalid_prompt,
            type_error_prompt: param.type_error_prompt
          })) : [],
          action: intent.action,
          fallback_timeout_prompt: intent.fallback_timeout_prompt,
          fallback_error_prompt: intent.fallback_error_prompt
        })),
        last_update_date: currentVersion.last_update_date || ''
      };
  
      console.log('Saving version data:', JSON.stringify(updateData, null, 2));
  
      const result = await this.apiService.updateVersion(
        this.project.id, 
        currentVersion.id, 
        updateData
      ).toPromise();
  
      this.snackBar.open('Version saved successfully', 'Close', { duration: 3000 });

      this.isDirty = false;
      
      if (result) {
        this.selectedVersion = result;
        this.versionForm.patchValue({
          last_update_date: result.last_update_date
        });
      }
      
      await this.loadVersions();
      
    } catch (error: any) {
      console.error('Save error:', error);
      
      if (error.status === 409) {
        // Race condition handling için ayrı metod çağır
        await this.handleRaceCondition(currentVersion);
      } else {
        const errorMessage = error.error?.detail || error.message || 'Failed to save version';
        this.snackBar.open(errorMessage, 'Close', { 
          duration: 5000,
          panelClass: 'error-snackbar'
        });
      }
    } finally {
      this.saving = false;
    }
  }
  
  // Race condition handling için ayrı metod
  private async handleRaceCondition(currentVersion: Version) {
    const formValue = this.versionForm.getRawValue();
    
    const retryUpdateData = {
      caption: formValue.caption,
      general_prompt: formValue.general_prompt || '',
      llm: formValue.llm,
      intents: formValue.intents.map((intent: any) => ({
        name: intent.name,
        caption: intent.caption,
        locale: intent.locale,
        detection_prompt: intent.detection_prompt,
        examples: Array.isArray(intent.examples) ? intent.examples.filter((ex: any) => ex) : [],
        parameters: Array.isArray(intent.parameters) ? intent.parameters : [],
        action: intent.action,
        fallback_timeout_prompt: intent.fallback_timeout_prompt,
        fallback_error_prompt: intent.fallback_error_prompt
      })),
      last_update_date: currentVersion.last_update_date || ''
    };
  
    const dialogRef = this.dialog.open(ConfirmDialogComponent, {
      width: '500px',
      data: {
        title: 'Version Modified',
        message: 'This version was modified by another user. Do you want to reload and lose your changes, or force save?',
        confirmText: 'Force Save',
        cancelText: 'Reload',
        confirmColor: 'warn'
      }
    });
  
    dialogRef.afterClosed().subscribe(async (forceSave) => {
      if (forceSave) {
        try {
          await this.apiService.updateVersion(
            this.project.id, 
            currentVersion.id, 
            retryUpdateData,
            true
          ).toPromise();
          this.snackBar.open('Version force saved', 'Close', { duration: 3000 });
          await this.loadVersions();
        } catch (err: any) {
          this.snackBar.open(err.error?.detail || 'Force save failed', 'Close', { 
            duration: 5000,
            panelClass: 'error-snackbar'
          });
        }
      } else {
        await this.loadVersions();
      }
    });
  }  
  
  async publishVersion() {
    if (!this.selectedVersion) return;

    const dialogRef = this.dialog.open(ConfirmDialogComponent, {
      width: '500px',
      data: {
        title: 'Publish Version',
        message: `Are you sure you want to publish version "${this.selectedVersion.caption}"? This will unpublish all other versions.`,
        confirmText: 'Publish',
        confirmColor: 'primary'
      }
    });

    dialogRef.afterClosed().subscribe(async (confirmed) => {
      if (confirmed && this.selectedVersion) {
        this.publishing = true;
        try {
          await this.apiService.publishVersion(
            this.project.id,
            this.selectedVersion.id
          ).toPromise();

          this.snackBar.open('Version published successfully', 'Close', { duration: 3000 });
          
          // Reload to get updated data
          await this.reloadProject();
          
        } catch (error: any) {
          this.snackBar.open(error.error?.detail || 'Failed to publish version', 'Close', { 
            duration: 5000,
            panelClass: 'error-snackbar'
          });
        } finally {
          this.publishing = false;
        }
      }
    });
  }

  async deleteVersion() {
    if (!this.selectedVersion || this.selectedVersion.published) return;

    const dialogRef = this.dialog.open(ConfirmDialogComponent, {
      width: '400px',
      data: {
        title: 'Delete Version',
        message: `Are you sure you want to delete version "${this.selectedVersion.caption}"?`,
        confirmText: 'Delete',
        confirmColor: 'warn'
      }
    });

    dialogRef.afterClosed().subscribe(async (confirmed) => {
      if (confirmed && this.selectedVersion) {
        try {
          await this.apiService.deleteVersion(
            this.project.id,
            this.selectedVersion.id
          ).toPromise();

          this.snackBar.open('Version deleted successfully', 'Close', { duration: 3000 });
          
          // Reload and select another version
          await this.reloadProject();
          
          if (this.versions.length > 0) {
            this.loadVersion(this.versions[0]);
          } else {
            this.selectedVersion = null;
          }
          
        } catch (error: any) {
          this.snackBar.open(error.error?.detail || 'Failed to delete version', 'Close', { 
            duration: 5000,
            panelClass: 'error-snackbar'
          });
        }
      }
    });
  }

  async testIntentDetection() {
    if (!this.testUserMessage.trim()) {
      this.snackBar.open('Please enter a test message', 'Close', { duration: 3000 });
      return;
    }

    this.testing = true;
    this.testResult = null;

    // Simulate intent detection test
    setTimeout(() => {
      // This is a mock - in real implementation, this would call the Spark service
      const intents = this.versionForm.get('intents')?.value || [];
      
      // Simple matching for demo
      let detectedIntent = null;
      let confidence = 0;

      for (const intent of intents) {
        for (const example of intent.examples || []) {
          if (this.testUserMessage.toLowerCase().includes(example.toLowerCase())) {
            detectedIntent = intent.name;
            confidence = 0.95;
            break;
          }
        }
        if (detectedIntent) break;
      }

      // Random detection for demo
      if (!detectedIntent && intents.length > 0) {
        const randomIntent = intents[Math.floor(Math.random() * intents.length)];
        detectedIntent = randomIntent.name;
        confidence = 0.65;
      }

      this.testResult = {
        success: true,
        intent: detectedIntent,
        confidence: confidence,
        parameters: detectedIntent ? this.extractTestParameters(detectedIntent) : []
      };

      this.testing = false;
    }, 1500);
  }

  private extractTestParameters(intentName: string): any[] {
    // Mock parameter extraction
    const intent = this.intents.value.find((i: any) => i.name === intentName);
    if (!intent) return [];

    return intent.parameters.map((param: any) => ({
      name: param.name,
      value: param.type === 'date' ? '2025-06-15' : 'test_value',
      extracted: Math.random() > 0.3
    }));
  }

  async getAvailableAPIs(): Promise<any[]> {
    try {
      return await this.apiService.getAPIs().toPromise() || [];
    } catch {
      return [];
    }
  }

  private async reloadProject() {
    this.loading = true;
    try {
      const projects = await this.apiService.getProjects().toPromise() || [];
      const updatedProject = projects.find(p => p.id === this.project.id);
      
      if (updatedProject) {
        this.project = updatedProject;
        this.versions = [...updatedProject.versions].sort((a, b) => b.id - a.id);
      }
    } catch (error) {
      console.error('Failed to reload project:', error);
    } finally {
      this.loading = false;
    }
  }

  async compareVersions() {
    if (this.versions.length < 2) {
      this.snackBar.open('Need at least 2 versions to compare', 'Close', { duration: 3000 });
      return;
    }
  
    const { default: VersionCompareDialogComponent } = await import('../version-compare-dialog/version-compare-dialog.component');
    
    this.dialog.open(VersionCompareDialogComponent, {
      width: '90vw',
      maxWidth: '1000px',
      maxHeight: '80vh',
      data: {
        versions: this.versions,
        selectedVersion: this.selectedVersion
      }
    });
  }
    
  close() {
    this.dialogRef.close(true);
  }
}