File size: 11,061 Bytes
9f79da5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c6054f
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
import { Component, Inject, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormBuilder, FormGroup, FormArray, Validators, ReactiveFormsModule, FormsModule } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA, MatDialogModule } from '@angular/material/dialog';
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 { MatChipsModule } from '@angular/material/chips';
import { MatTableModule } from '@angular/material/table';
import { MatTabsModule } from '@angular/material/tabs';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatListModule } from '@angular/material/list';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { MatDialog } from '@angular/material/dialog';

// Interfaces for multi-language support
interface LocalizedExample {
  locale_code: string;
  example: string;
}

interface LocalizedCaption {
  locale_code: string;
  caption: string;
}

interface ParameterWithLocalizedCaption {
  name: string;
  caption: LocalizedCaption[];
  type: string;
  required: boolean;
  variable_name: string;
  extraction_prompt?: string;
  validation_regex?: string;
  invalid_prompt?: string;
  type_error_prompt?: string;
}

@Component({
  selector: 'app-intent-edit-dialog',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    FormsModule,
    MatDialogModule,
    MatFormFieldModule,
    MatInputModule,
    MatSelectModule,
    MatCheckboxModule,
    MatButtonModule,
    MatIconModule,
    MatChipsModule,
    MatTableModule,
    MatTabsModule,
    MatExpansionModule,
    MatListModule,
    MatSnackBarModule
  ],
  templateUrl: './intent-edit-dialog.component.html',
  styleUrls: ['./intent-edit-dialog.component.scss']
})
export default class IntentEditDialogComponent implements OnInit {
  form!: FormGroup;
  availableAPIs: any[] = [];
  parameterTypes = ['str', 'int', 'float', 'bool', 'date'];
  
  // Multi-language support
  supportedLocales: string[] = [];
  selectedExampleLocale: string = '';
  examples: LocalizedExample[] = [];
  
  newExample = '';

  constructor(

    private fb: FormBuilder,

    private snackBar: MatSnackBar,

    private dialog: MatDialog,

    public dialogRef: MatDialogRef<IntentEditDialogComponent>,

    @Inject(MAT_DIALOG_DATA) public data: any

  ) {
    this.availableAPIs = data.apis || [];
    this.supportedLocales = data.project?.supported_locales || data.supportedLocales || ['tr'];
    this.selectedExampleLocale = data.project?.default_locale || data.defaultLocale || this.supportedLocales[0] || 'tr';
  }

  ngOnInit() {
    this.initializeForm();
    if (this.data.intent) {
      this.populateForm(this.data.intent);
    }
  }

  initializeForm() {
    this.form = this.fb.group({
      name: ['', [Validators.required, Validators.pattern(/^[a-zA-Z0-9-]+$/)]],
      caption: ['', Validators.required],
      detection_prompt: ['', Validators.required],
      parameters: this.fb.array([]),
      action: ['', Validators.required],
      fallback_timeout_prompt: [''],
      fallback_error_prompt: ['']
    });
  }

  populateForm(intent: any) {
    // Populate basic fields
    this.form.patchValue({
      name: intent.name || '',
      caption: intent.caption || '',
      detection_prompt: intent.detection_prompt || '',
      action: intent.action || '',
      fallback_timeout_prompt: intent.fallback_timeout_prompt || '',
      fallback_error_prompt: intent.fallback_error_prompt || ''
    });

    // Populate localized examples
    if (intent.examples && Array.isArray(intent.examples)) {
      if (intent.examples.length > 0 && typeof intent.examples[0] === 'object' && 'locale_code' in intent.examples[0]) {
        // New format with LocalizedExample
        this.examples = [...intent.examples];
      } else if (typeof intent.examples[0] === 'string') {
        // Old format - convert to new format using default locale
        this.examples = intent.examples.map((ex: string) => ({
          locale_code: this.selectedExampleLocale,
          example: ex
        }));
      }
    }

    // Populate parameters with localized captions
    if (intent.parameters && Array.isArray(intent.parameters)) {
      const paramsArray = this.form.get('parameters') as FormArray;
      paramsArray.clear();
      
      intent.parameters.forEach((param: any) => {
        paramsArray.push(this.createParameterFormGroup(param));
      });
    }
  }

  createParameterFormGroup(param?: any): FormGroup {
    // Convert old caption format to new if needed
    let captionArray: LocalizedCaption[] = [];
    if (param?.caption) {
      if (Array.isArray(param.caption)) {
        captionArray = param.caption;
      } else if (typeof param.caption === 'string') {
        // Old format - convert to new
        captionArray = [{
          locale_code: this.selectedExampleLocale,
          caption: param.caption
        }];
      }
    }

    return this.fb.group({
      name: [param?.name || '', Validators.required],
      caption: [captionArray],
      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 parameters() {
    return this.form.get('parameters') as FormArray;
  }

  addParameter() {
    this.parameters.push(this.createParameterFormGroup());
  }

  removeParameter(index: number) {
    this.parameters.removeAt(index);
  }

  // Multi-language example management
  getExamplesForCurrentLocale(): LocalizedExample[] {
    return this.examples.filter(ex => ex.locale_code === this.selectedExampleLocale);
  }

  addExample() {
    if (this.newExample.trim()) {
      const existingIndex = this.examples.findIndex(
        ex => ex.locale_code === this.selectedExampleLocale && ex.example === this.newExample.trim()
      );
      
      if (existingIndex === -1) {
        this.examples.push({
          locale_code: this.selectedExampleLocale,
          example: this.newExample.trim()
        });
        this.newExample = '';
      } else {
        this.snackBar.open('This example already exists for this locale', 'Close', { duration: 3000 });
      }
    }
  }

  removeExample(example: LocalizedExample) {
    const index = this.examples.findIndex(
      ex => ex.locale_code === example.locale_code && ex.example === example.example
    );
    if (index !== -1) {
      this.examples.splice(index, 1);
    }
  }

  // Test regex functionality
  testRegex(paramIndex: number) {
    const param = this.parameters.at(paramIndex);
    const regex = param.get('validation_regex')?.value;
    
    if (!regex) {
      this.snackBar.open('No regex pattern to test', 'Close', { duration: 2000 });
      return;
    }

    // Simple test implementation
    const testValue = prompt('Enter a test value:');
    if (testValue !== null) {
      try {
        const pattern = new RegExp(regex);
        const matches = pattern.test(testValue);
        this.snackBar.open(
          matches ? '✓ Pattern matches!' : '✗ Pattern does not match',
          'Close',
          { duration: 3000 }
        );
      } catch (e) {
        this.snackBar.open('Invalid regex pattern', 'Close', { duration: 3000 });
      }
    }
  }

  // Move parameter up or down
  moveParameter(index: number, direction: 'up' | 'down') {
    const newIndex = direction === 'up' ? index - 1 : index + 1;
    
    if (newIndex < 0 || newIndex >= this.parameters.length) {
      return;
    }

    const currentItem = this.parameters.at(index);
    this.parameters.removeAt(index);
    this.parameters.insert(newIndex, currentItem);
  }

  // Parameter caption management
  getCaptionDisplay(captions: LocalizedCaption[]): string {
    if (!captions || captions.length === 0) return '(No caption)';
    
    // Try to find caption for default locale
    const defaultCaption = captions.find(c => c.locale_code === (this.data.project?.default_locale || this.data.defaultLocale || 'tr'));
    if (defaultCaption) return defaultCaption.caption;
    
    // Return first available caption
    return captions[0].caption;
  }

  async openCaptionDialog(paramIndex: number) {
    const param = this.parameters.at(paramIndex);
    const currentCaptions = param.get('caption')?.value || [];
    
    // Import and open caption dialog
    const { default: CaptionDialogComponent } = await import('../caption-dialog/caption-dialog.component');
    
    const dialogRef = this.dialog.open(CaptionDialogComponent, {
      width: '600px',
      data: {
        captions: [...currentCaptions],
        supportedLocales: this.supportedLocales,
        defaultLocale: this.data.project?.default_locale || this.data.defaultLocale
      }
    });

    dialogRef.afterClosed().subscribe(result => {
      if (result) {
        param.patchValue({ caption: result });
      }
    });
  }

  // Locale helpers
  getLocaleName(localeCode: string): string {
    const localeNames: { [key: string]: string } = {
      'tr': 'Türkçe',
      'en': 'English',
      'de': 'Deutsch',
      'fr': 'Français',
      'es': 'Español',
      'ar': 'العربية',
      'ru': 'Русский',
      'zh': '中文',
      'ja': '日本語',
      'ko': '한국어'
    };
    return localeNames[localeCode] || localeCode;
  }

  onSubmit() {
    if (this.form.valid) {
      const formValue = this.form.value;
      
      // Add examples to the result
      formValue.examples = this.examples;
      
      // Ensure all parameters have captions
      formValue.parameters = formValue.parameters.map((param: any) => {
        if (!param.caption || param.caption.length === 0) {
          // Create default caption if missing
          param.caption = [{
            locale_code: this.data.project?.default_locale || this.data.defaultLocale || 'tr',
            caption: param.name
          }];
        }
        return param;
      });
      
      this.dialogRef.close(formValue);
    } else {
      this.snackBar.open('Please fill all required fields', 'Close', { duration: 3000 });
    }
  }

  save() {
    this.onSubmit();
  }

  cancel() {
    this.dialogRef.close();
  }
}