File size: 27,604 Bytes
6918275
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
import { createStore } from "/js/AlpineStore.js";
import {
  formatDateTime,
  getCurrentUserDateString,
  getCurrentUserISOString,
  getUserHour12,
  getUserTimezone,
} from "/js/time-utils.js";

// Global function references
const sendJsonData = globalThis.sendJsonData;
const toast = globalThis.toast;
const fetchApi = globalThis.fetchApi;

// ⚠️ CRITICAL: The .env file contains API keys and essential configuration.
// This file is REQUIRED for Agent Zero to function and must be backed up.

const model = {
  // State
  mode: 'backup', // 'backup' or 'restore'
  loading: false,
  loadingMessage: '',
  error: '',

  // File operations log (shared between backup and restore)
  fileOperationsLog: '',

  // Backup state
  backupMetadataConfig: null,
  includeHidden: false,
  previewStats: { total: 0, truncated: false },
  backupEditor: null,

  // Enhanced file preview state
  previewMode: 'grouped', // 'grouped' or 'flat'
  previewFiles: [],
  previewGroups: [],
  filteredPreviewFiles: [],
  fileSearchFilter: '',
  expandedGroups: new Set(),

  // Progress state
  progressData: null,
  progressEventSource: null,

  // Restore state
  backupFile: null,
  backupMetadata: null,
  restorePatterns: '',
  overwritePolicy: 'overwrite',
  cleanBeforeRestore: false,
  restoreEditor: null,
  restoreResult: null,

  // Initialization
  async initBackup() {
    this.mode = 'backup';
    this.resetState();
    await this.initBackupEditor();
    await this.updatePreview();
  },

  async initRestore() {
    this.mode = 'restore';
    this.resetState();
    await this.initRestoreEditor();
  },

  resetState() {
    this.loading = false;
    this.error = '';
    this.backupFile = null;
    this.backupMetadata = null;
    this.restoreResult = null;
    this.fileOperationsLog = '';
  },

  // File operations logging
  addFileOperation(message) {
    const timestamp = new Intl.DateTimeFormat(undefined, {
      timeStyle: "medium",
      hour12: getUserHour12(),
      timeZone: getUserTimezone(),
    }).format(new Date());
    this.fileOperationsLog += `[${timestamp}] ${message}\n`;

    // Auto-scroll to bottom - use setTimeout since $nextTick is not available in stores
    setTimeout(() => {
      const textarea = document.getElementById(this.mode === 'backup' ? 'backup-file-list' : 'restore-file-list');
      if (textarea) {
        textarea.scrollTop = textarea.scrollHeight;
      }
    }, 0);
  },

  clearFileOperations() {
    this.fileOperationsLog = '';
  },

  createDownloadToastGroup(prefix) {
    return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
  },

  showDownloadPreparingToast(group) {
    window.toastFrontendInfo?.("Preparing download...", "Download", 0, group, undefined, true);
  },

  showDownloadStartedToast(group) {
    window.toastFrontendInfo?.("Downloading...", "Download", 3, group, undefined, true);
  },

  showDownloadErrorToast(group, message) {
    window.toastFrontendError?.(message || "Download failed", "Download Error", 8, group, undefined, true);
  },

  // Cleanup method for modal close
  onClose() {
    this.resetState();
    if (this.backupEditor) {
      this.backupEditor.destroy();
      this.backupEditor = null;
    }
    if (this.restoreEditor) {
      this.restoreEditor.destroy();
      this.restoreEditor = null;
    }
  },

  // Get default backup metadata with resolved patterns from backend
  async getDefaultBackupMetadata() {
    const timestamp = getCurrentUserISOString();

    try {
      // Get resolved default patterns from backend
      const response = await sendJsonData("backup_get_defaults", {});

      if (response.success) {
        // Use patterns from backend with resolved absolute paths
        const include_patterns = response.default_patterns.include_patterns;
        const exclude_patterns = response.default_patterns.exclude_patterns;

        return {
          backup_name: `agent-zero-backup-${getCurrentUserDateString()}`,
          include_hidden: true,
          include_patterns: include_patterns,
          exclude_patterns: exclude_patterns,
          backup_config: {
            compression_level: 6,
            integrity_check: true
          }
        };
      }
    } catch (error) {
      console.warn("Failed to get default patterns from backend, using fallback");
    }

    // Fallback patterns (will be overridden by backend on first use)
    return {
      backup_name: `agent-zero-backup-${timestamp.slice(0, 10)}`,
      include_hidden: true,
      include_patterns: [
        // These will be replaced with resolved absolute paths by backend
        "# Loading default patterns from backend..."
      ],
      exclude_patterns: [],
      backup_config: {
        compression_level: 6,
        integrity_check: true
      }
    };
  },

  // Editor Management - Following Agent Zero ACE editor patterns
  async initBackupEditor() {
    const container = document.getElementById("backup-metadata-editor");
    if (container) {
      const editor = ace.edit("backup-metadata-editor");

      const dark = localStorage.getItem("darkMode");
      if (dark != "false") {
        editor.setTheme("ace/theme/github_dark");
      } else {
        editor.setTheme("ace/theme/tomorrow");
      }

      editor.session.setMode("ace/mode/json");

      // Initialize with default backup metadata
      const defaultMetadata = await this.getDefaultBackupMetadata();
      editor.setValue(JSON.stringify(defaultMetadata, null, 2));
      editor.clearSelection();

      // Auto-update preview on changes (debounced)
      let timeout;
      editor.on('change', () => {
        clearTimeout(timeout);
        timeout = setTimeout(() => {
          this.updatePreview();
        }, 1000);
      });

      this.backupEditor = editor;
    }
  },

  async initRestoreEditor() {
    const container = document.getElementById("restore-metadata-editor");
    if (container) {
      const editor = ace.edit("restore-metadata-editor");

      const dark = localStorage.getItem("darkMode");
      if (dark != "false") {
        editor.setTheme("ace/theme/github_dark");
      } else {
        editor.setTheme("ace/theme/tomorrow");
      }

      editor.session.setMode("ace/mode/json");
      editor.setValue('{}');
      editor.clearSelection();

      // Auto-validate JSON on changes
      editor.on('change', () => {
        this.validateRestoreMetadata();
      });

      this.restoreEditor = editor;
    }
  },

  // Unified editor value getter (following MCP servers pattern)
  getEditorValue() {
    const editor = this.mode === 'backup' ? this.backupEditor : this.restoreEditor;
    return editor ? editor.getValue() : '{}';
  },

  // Unified JSON formatting (following MCP servers pattern)
  formatJson() {
    const editor = this.mode === 'backup' ? this.backupEditor : this.restoreEditor;
    if (!editor) return;

    try {
      const currentContent = editor.getValue();
      const parsed = JSON.parse(currentContent);
      const formatted = JSON.stringify(parsed, null, 2);

      editor.setValue(formatted);
      editor.clearSelection();
      editor.navigateFileStart();
    } catch (error) {
      console.error("Failed to format JSON:", error);
      this.error = "Invalid JSON: " + error.message;
    }
  },

  // Enhanced File Preview Operations
  async updatePreview() {
    try {
      const metadataText = this.getEditorValue();
      const metadata = JSON.parse(metadataText);

      if (!metadata.include_patterns || metadata.include_patterns.length === 0) {
        this.previewStats = { total: 0, truncated: false };
        this.previewFiles = [];
        this.previewGroups = [];
        return;
      }

      // Convert patterns arrays back to string format for API
      const patternsString = this.convertPatternsToString(metadata.include_patterns, metadata.exclude_patterns);

      // Get grouped preview for better UX
      const response = await sendJsonData("backup_preview_grouped", {
        patterns: patternsString,
        include_hidden: metadata.include_hidden ?? true,
        max_depth: 3,
        search_filter: this.fileSearchFilter
      });

      if (response.success) {
        this.previewGroups = response.groups;
        this.previewStats = response.stats;

        // Flatten groups for flat view
        this.previewFiles = [];
        response.groups.forEach(group => {
          this.previewFiles.push(...group.files);
        });

        this.applyFileSearch();
      } else {
        this.error = response.error;
      }
    } catch (error) {
      this.error = `Preview error: ${error.message}`;
    }
  },

  // Convert pattern arrays to string format for backend API
  convertPatternsToString(includePatterns, excludePatterns) {
    const patterns = [];

    // Add include patterns
    if (includePatterns) {
      patterns.push(...includePatterns);
    }

    // Add exclude patterns with '!' prefix
    if (excludePatterns) {
      excludePatterns.forEach(pattern => {
        patterns.push(`!${pattern}`);
      });
    }

    return patterns.join('\n');
  },

  // Validation for backup metadata
  validateBackupMetadata() {
    try {
      const metadataText = this.getEditorValue();
      const metadata = JSON.parse(metadataText);

      // Validate required fields
      if (!Array.isArray(metadata.include_patterns)) {
        throw new Error('include_patterns must be an array');
      }
      if (!Array.isArray(metadata.exclude_patterns)) {
        throw new Error('exclude_patterns must be an array');
      }
      if (!metadata.backup_name || typeof metadata.backup_name !== 'string') {
        throw new Error('backup_name must be a non-empty string');
      }

      this.backupMetadataConfig = metadata;
      this.error = '';
      return true;
    } catch (error) {
      this.error = `Invalid backup metadata: ${error.message}`;
      return false;
    }
  },

  // File Preview UI Management
  initFilePreview() {
    this.fileSearchFilter = '';
    this.expandedGroups.clear();
    this.previewMode = localStorage.getItem('backupPreviewMode') || 'grouped';
  },

  togglePreviewMode() {
    this.previewMode = this.previewMode === 'grouped' ? 'flat' : 'grouped';
    localStorage.setItem('backupPreviewMode', this.previewMode);
  },

  toggleGroup(groupPath) {
    if (this.expandedGroups.has(groupPath)) {
      this.expandedGroups.delete(groupPath);
    } else {
      this.expandedGroups.add(groupPath);
    }
  },

  isGroupExpanded(groupPath) {
    return this.expandedGroups.has(groupPath);
  },

  debounceFileSearch() {
    clearTimeout(this.searchTimeout);
    this.searchTimeout = setTimeout(() => {
      this.applyFileSearch();
    }, 300);
  },

  clearFileSearch() {
    this.fileSearchFilter = '';
    this.applyFileSearch();
  },

  applyFileSearch() {
    if (!this.fileSearchFilter.trim()) {
      this.filteredPreviewFiles = this.previewFiles;
    } else {
      const search = this.fileSearchFilter.toLowerCase();
      this.filteredPreviewFiles = this.previewFiles.filter(file =>
        file.path.toLowerCase().includes(search)
      );
    }
  },

  async exportFileList() {
    const fileList = this.previewFiles.map(f => f.path).join('\n');
    const blob = new Blob([fileList], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'backup-file-list.txt';
    a.click();
    URL.revokeObjectURL(url);
  },

  async copyFileListToClipboard() {
    const fileList = this.previewFiles.map(f => f.path).join('\n');
    try {
      await navigator.clipboard.writeText(fileList);
      window.toastFrontendInfo('File list copied to clipboard', 'Clipboard');
    } catch (error) {
      window.toastFrontendError('Failed to copy to clipboard', 'Clipboard Error');
    }
  },

  // Backup Creation using direct API call
  async createBackup() {
    // Validate backup metadata first
    if (!this.validateBackupMetadata()) {
      return;
    }

    const downloadToastGroup = this.createDownloadToastGroup("backup-create");

    try {
      this.loading = true;
      this.loadingMessage = 'Creating backup...';
      this.error = '';
      this.clearFileOperations();
      this.addFileOperation('Starting backup creation...');
      this.showDownloadPreparingToast(downloadToastGroup);

      const metadata = this.backupMetadataConfig;

      // Use fetch directly since backup_create returns a file download, not JSON
      const response = await fetchApi('/backup_create', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          include_patterns: metadata.include_patterns,
          exclude_patterns: metadata.exclude_patterns,
          include_hidden: metadata.include_hidden ?? true,
          backup_name: metadata.backup_name
        })
      });

      if (response.ok) {
        // Handle file download
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `${metadata.backup_name}.zip`;
        a.click();
        window.URL.revokeObjectURL(url);

        this.addFileOperation('Backup created and downloaded successfully!');
        this.showDownloadStartedToast(downloadToastGroup);
      } else {
        // Try to parse error response
        const errorText = await response.text();
        try {
          const errorJson = JSON.parse(errorText);
          this.error = errorJson.error || 'Backup creation failed';
        } catch {
          this.error = `Backup creation failed: ${response.status} ${response.statusText}`;
        }
        this.addFileOperation(`Error: ${this.error}`);
        this.showDownloadErrorToast(downloadToastGroup, this.error);
      }

    } catch (error) {
      this.error = `Backup error: ${error.message}`;
      this.addFileOperation(`Error: ${error.message}`);
      this.showDownloadErrorToast(downloadToastGroup, this.error);
    } finally {
      this.loading = false;
    }
  },

  async downloadBackup(backupPath, backupName) {
    const downloadToastGroup = this.createDownloadToastGroup("backup-download");

    try {
      this.showDownloadPreparingToast(downloadToastGroup);
      const response = await fetchApi('/backup_download', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ backup_path: backupPath })
      });

      if (response.ok) {
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `${backupName}.zip`;
        a.click();
        window.URL.revokeObjectURL(url);
        this.showDownloadStartedToast(downloadToastGroup);
      } else {
        const errorText = await response.text();
        this.error = errorText || `Download failed: ${response.status}`;
        this.showDownloadErrorToast(downloadToastGroup, this.error);
      }
    } catch (error) {
      console.error('Download error:', error);
      this.error = error.message || 'Download failed';
      this.showDownloadErrorToast(downloadToastGroup, this.error);
    }
  },

  cancelBackup() {
    if (this.progressEventSource) {
      this.progressEventSource.close();
      this.progressEventSource = null;
    }
    this.loading = false;
    this.progressData = null;
  },

  resetToDefaults() {
    this.getDefaultBackupMetadata().then(defaultMetadata => {
      if (this.backupEditor) {
        this.backupEditor.setValue(JSON.stringify(defaultMetadata, null, 2));
        this.backupEditor.clearSelection();
      }
      this.updatePreview();
    });
  },

  // Dry run functionality
  async dryRun() {
    if (this.mode === 'backup') {
      await this.dryRunBackup();
    } else if (this.mode === 'restore') {
      await this.dryRunRestore();
    }
  },

  async dryRunBackup() {
    // Validate backup metadata first
    if (!this.validateBackupMetadata()) {
      return;
    }

    try {
      this.loading = true;
      this.loadingMessage = 'Performing dry run...';
      this.error = '';
      this.clearFileOperations();
      this.addFileOperation('Starting backup dry run...');

      const metadata = this.backupMetadataConfig;
      const patternsString = this.convertPatternsToString(metadata.include_patterns, metadata.exclude_patterns);

      const response = await sendJsonData("backup_test", {
        patterns: patternsString,
        include_hidden: metadata.include_hidden ?? true,
        max_files: 10000
      });

      if (response.success) {
        this.addFileOperation(`Found ${response.files.length} files that would be backed up:`);
        response.files.forEach((file, index) => {
          this.addFileOperation(`${index + 1}. ${file.path} (${this.formatFileSize(file.size)})`);
        });
        this.addFileOperation(`\nTotal: ${response.files.length} files, ${this.formatFileSize(response.files.reduce((sum, f) => sum + f.size, 0))}`);
        this.addFileOperation('Dry run completed successfully.');
      } else {
        this.error = response.error;
        this.addFileOperation(`Error: ${response.error}`);
      }
    } catch (error) {
      this.error = `Dry run error: ${error.message}`;
      this.addFileOperation(`Error: ${error.message}`);
    } finally {
      this.loading = false;
    }
  },

  async dryRunRestore() {
    if (!this.backupFile) {
      this.error = 'Please select a backup file first';
      return;
    }

    try {
      this.loading = true;
      this.loadingMessage = 'Performing restore dry run...';
      this.error = '';
      this.restoreResult = null;
      this.clearFileOperations();
      this.addFileOperation('Starting restore dry run...');

      const formData = new FormData();
      formData.append('backup_file', this.backupFile);
      formData.append('metadata', this.getEditorValue());
      formData.append('overwrite_policy', this.overwritePolicy);
      formData.append('clean_before_restore', this.cleanBeforeRestore);

      const response = await fetchApi('/backup_restore_preview', {
        method: 'POST',
        body: formData
      });

      const result = await response.json();

      if (result.success) {
        // Show delete operations if clean before restore is enabled
        if (result.files_to_delete && result.files_to_delete.length > 0) {
          this.addFileOperation(`Clean before restore - ${result.files_to_delete.length} files would be deleted:`);
          result.files_to_delete.forEach((file, index) => {
            this.addFileOperation(`${index + 1}. DELETE: ${file.path}`);
          });
          this.addFileOperation('');
        }

        // Show restore operations
        if (result.files_to_restore && result.files_to_restore.length > 0) {
          this.addFileOperation(`${result.files_to_restore.length} files would be restored:`);
          result.files_to_restore.forEach((file, index) => {
            this.addFileOperation(`${index + 1}. RESTORE: ${file.original_path} -> ${file.target_path}`);
          });
        }

        // Show skipped files
        if (result.skipped_files && result.skipped_files.length > 0) {
          this.addFileOperation(`\nSkipped ${result.skipped_files.length} files:`);
          result.skipped_files.forEach((file, index) => {
            this.addFileOperation(`${index + 1}. ${file.original_path} (${file.reason})`);
          });
        }

        const deleteCount = result.delete_count || 0;
        const restoreCount = result.restore_count || 0;
        const skippedCount = result.skipped_files?.length || 0;

        this.addFileOperation(`\nSummary: ${deleteCount} to delete, ${restoreCount} to restore, ${skippedCount} skipped`);
        this.addFileOperation('Dry run completed successfully.');
      } else {
        this.error = result.error;
        this.addFileOperation(`Error: ${result.error}`);
      }
    } catch (error) {
      this.error = `Dry run error: ${error.message}`;
      this.addFileOperation(`Error: ${error.message}`);
    } finally {
      this.loading = false;
    }
  },

  // Enhanced Restore Operations with Metadata Display
  async handleFileUpload(event) {
    const file = event.target.files[0];
    if (!file) return;

    this.backupFile = file;
    this.error = '';
    this.restoreResult = null;

    try {
      this.loading = true;
      this.loadingMessage = 'Inspecting backup archive...';

      const formData = new FormData();
      formData.append('backup_file', file);

      const response = await fetchApi('/backup_inspect', {
        method: 'POST',
        body: formData
      });

      const result = await response.json();

      if (result.success) {
        this.backupMetadata = result.metadata;

        // Load complete metadata for JSON editing
        this.restoreMetadata = JSON.parse(JSON.stringify(result.metadata)); // Deep copy

        // Initialize restore editor with complete metadata JSON
        if (this.restoreEditor) {
          this.restoreEditor.setValue(JSON.stringify(this.restoreMetadata, null, 2));
          this.restoreEditor.clearSelection();
        }

        // Validate backup compatibility
        this.validateBackupCompatibility();
      } else {
        this.error = result.error;
        this.backupMetadata = null;
      }
    } catch (error) {
      this.error = `Inspection error: ${error.message}`;
      this.backupMetadata = null;
    } finally {
      this.loading = false;
    }
  },

  validateBackupCompatibility() {
    if (!this.backupMetadata) return;

    const warnings = [];

    // Check Agent Zero version compatibility
    // Note: Both backup and current versions are obtained via git.get_git_info()
    const backupVersion = this.backupMetadata.agent_zero_version;
    const currentVersion = globalThis.gitinfo.version; // Retrieved from git.get_git_info() on backend

    if (backupVersion !== currentVersion && backupVersion !== "development") {
      warnings.push(`Backup created with Agent Zero ${backupVersion}, current version is ${currentVersion}`);
    }

    // Check backup age
    const backupDate = new Date(this.backupMetadata.timestamp);
    const daysSinceBackup = (Date.now() - backupDate) / (1000 * 60 * 60 * 24);

    if (daysSinceBackup > 30) {
      warnings.push(`Backup is ${Math.floor(daysSinceBackup)} days old`);
    }

    // Check system compatibility
    const systemInfo = this.backupMetadata.system_info;
    if (systemInfo && systemInfo.system) {
      // Could add platform-specific warnings here
    }

    if (warnings.length > 0) {
      window.toastFrontendWarning(`Compatibility warnings: ${warnings.join(', ')}`, 'Backup Compatibility');
    }
  },

  async performRestore() {
    if (!this.backupFile) {
      this.error = 'Please select a backup file';
      return;
    }

    try {
      this.loading = true;
      this.loadingMessage = 'Restoring files...';
      this.error = '';
      this.restoreResult = null;
      this.clearFileOperations();
      this.addFileOperation('Starting file restoration...');

      const formData = new FormData();
      formData.append('backup_file', this.backupFile);
      formData.append('metadata', this.getEditorValue());
      formData.append('overwrite_policy', this.overwritePolicy);
      formData.append('clean_before_restore', this.cleanBeforeRestore);

      const response = await fetchApi('/backup_restore', {
        method: 'POST',
        body: formData
      });

      const result = await response.json();

      if (result.success) {
        // Log deleted files if clean before restore was enabled
        if (result.deleted_files && result.deleted_files.length > 0) {
          this.addFileOperation(`Clean before restore - Successfully deleted ${result.deleted_files.length} files:`);
          result.deleted_files.forEach((file, index) => {
            this.addFileOperation(`${index + 1}. DELETED: ${file.path}`);
          });
          this.addFileOperation('');
        }

        // Log restored files
        this.addFileOperation(`Successfully restored ${result.restored_files.length} files:`);
        result.restored_files.forEach((file, index) => {
          this.addFileOperation(`${index + 1}. RESTORED: ${file.archive_path} -> ${file.target_path}`);
        });

        // Log skipped files
        if (result.skipped_files && result.skipped_files.length > 0) {
          this.addFileOperation(`\nSkipped ${result.skipped_files.length} files:`);
          result.skipped_files.forEach((file, index) => {
            this.addFileOperation(`${index + 1}. ${file.original_path} (${file.reason})`);
          });
        }

        // Log errors
        if (result.errors && result.errors.length > 0) {
          this.addFileOperation(`\nErrors during restoration:`);
          result.errors.forEach((error, index) => {
            this.addFileOperation(`${index + 1}. ${error.original_path}: ${error.error}`);
          });
        }

        const deletedCount = result.deleted_files?.length || 0;
        const restoredCount = result.restored_files.length;
        const skippedCount = result.skipped_files?.length || 0;
        const errorCount = result.errors?.length || 0;

        this.addFileOperation(`\nRestore completed: ${deletedCount} deleted, ${restoredCount} restored, ${skippedCount} skipped, ${errorCount} errors`);
        this.restoreResult = result;
        window.toastFrontendInfo('Restore completed successfully', 'Restore Status');
      } else {
        this.error = result.error;
        this.addFileOperation(`Error: ${result.error}`);
      }
    } catch (error) {
      this.error = `Restore error: ${error.message}`;
      this.addFileOperation(`Error: ${error.message}`);
    } finally {
      this.loading = false;
    }
  },

  // JSON Metadata Utilities
  validateRestoreMetadata() {
    try {
      const metadataText = this.getEditorValue();
      const metadata = JSON.parse(metadataText);

      // Validate required fields
      if (!Array.isArray(metadata.include_patterns)) {
        throw new Error('include_patterns must be an array');
      }
      if (!Array.isArray(metadata.exclude_patterns)) {
        throw new Error('exclude_patterns must be an array');
      }

      this.restoreMetadata = metadata;
      this.error = '';
      return true;
    } catch (error) {
      this.error = `Invalid JSON metadata: ${error.message}`;
      return false;
    }
  },

  getCurrentRestoreMetadata() {
    if (this.validateRestoreMetadata()) {
      return this.restoreMetadata;
    }
    return null;
  },

  // Restore Operations - Metadata Control
  resetToOriginalMetadata() {
    if (this.backupMetadata) {
      this.restoreMetadata = JSON.parse(JSON.stringify(this.backupMetadata)); // Deep copy

      if (this.restoreEditor) {
        this.restoreEditor.setValue(JSON.stringify(this.restoreMetadata, null, 2));
        this.restoreEditor.clearSelection();
      }
    }
  },

  // Utility
  formatTimestamp(timestamp) {
    if (!timestamp) return 'Unknown';
    return formatDateTime(timestamp, "full");
  },

  formatFileSize(bytes) {
    if (!bytes) return '0 B';
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(1024));
    return `${(bytes / Math.pow(1024, i)).toFixed(1)} ${sizes[i]}`;
  },

  formatDate(dateString) {
    if (!dateString) return 'Unknown';
    return formatDateTime(dateString, "date");
  }
};

const store = createStore("backupStore", model);
export { store };