File size: 47,151 Bytes
e07a303
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e41605
e07a303
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e41605
 
 
e07a303
 
 
 
 
6e41605
 
 
 
e07a303
 
 
 
 
 
 
 
 
 
 
6e41605
 
e07a303
 
 
 
 
 
 
 
6e41605
 
 
e07a303
 
 
 
 
 
 
 
 
6e41605
e07a303
 
 
 
 
 
6e41605
 
 
 
 
 
 
 
e07a303
 
6e41605
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e07a303
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e41605
 
e07a303
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e41605
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e07a303
 
 
 
 
 
 
 
 
 
 
 
6e41605
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e07a303
 
 
 
 
 
 
 
 
 
 
 
6e41605
 
e07a303
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e41605
e07a303
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e41605
e07a303
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e41605
e07a303
6e41605
e07a303
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e41605
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e07a303
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e41605
 
 
 
 
 
 
 
 
e07a303
 
 
 
 
 
 
 
 
6e41605
 
 
 
 
e07a303
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e41605
 
 
 
 
 
 
 
 
 
 
 
 
e07a303
 
6e41605
 
 
 
 
 
 
 
e07a303
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e41605
 
e07a303
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e41605
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e07a303
 
6e41605
 
 
 
 
e07a303
6e41605
 
e07a303
 
 
6e41605
 
 
 
 
e07a303
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
/**

 * ╔══════════════════════════════════════════════════════════════════════╗

 * ║               CHAHUADEV HUB — Electron Main Process                 ║

 * ║              Official App Distribution Center (Desktop)             ║

 * ╚══════════════════════════════════════════════════════════════════════╝

 *

 * @author    Chahuadev

 * @license   NON-COMMERCIAL & ACCEPTABLE USE ONLY.

 *            Strictly prohibited for sale or malicious activities.

 *            See LICENSE.md for full terms.

 */



'use strict';

const { app, BrowserWindow, ipcMain, shell, session, Menu } = require('electron');
const { autoUpdater } = require('electron-updater');
const path         = require('path');
const fs           = require('fs');
const os           = require('os');
const https        = require('https');
const http         = require('http');
const { spawn, exec } = require('child_process');
const { URL } = require('url');
const SecurityCore = require('./security/security-core.js');

// Ignore dev flags in packaged builds so end users cannot force dev mode.
if (app.isPackaged) {
  process.argv = process.argv.filter(arg => arg !== '--dev' && arg !== '--dev-mode');
}

// ── Constants ────────────────────────────────────────────────────────────────
const HF_AUTHOR      = 'chahuadev';
const HF_REPO        = 'chahuadev/chahuadev-framework-binaries';
const HF_API_URL     = `https://huggingface.co/api/datasets/${HF_REPO}/tree/main`;
const HF_COMMITS_URL  = `https://huggingface.co/api/datasets/${HF_REPO}/commits/main`;
const R2_CDN_BASE     = 'https://r2.chahuadev.com';
const R2_CATALOG_URL  = 'https://r2.chahuadev.com/catalog.json';
const APP_CATALOG_ID  = 'chahuadev-hub';
const GITHUB_CATALOG_URL = 'https://raw.githubusercontent.com/toyspata00/chahuadev-hub/main/catalog.json';
const HF_DATASETS_API = `https://huggingface.co/api/datasets?author=${HF_AUTHOR}&full=true`;
const HF_MODELS_API   = `https://huggingface.co/api/models?author=${HF_AUTHOR}&full=true`;
const HF_SPACES_API   = `https://huggingface.co/api/spaces?author=${HF_AUTHOR}&full=true`;
const DOWNLOAD_DIR   = path.join(os.homedir(), 'Downloads', 'ChahuadevHub');
const APP_BASE_DIR   = app.isPackaged
  ? (process.env.PORTABLE_EXECUTABLE_DIR || path.dirname(process.execPath))
  : __dirname;
const HF_SANDBOX_DIR = path.join(APP_BASE_DIR, '.hf-sandbox-cache');

// ── npm Registry Constants ────────────────────────────────────────────────────
const NPM_ORG          = 'chahuadev';
const NPM_ORG_PKG_URL  = `https://registry.npmjs.org/-/org/${NPM_ORG}/package`;
const NPM_REG_BASE     = 'https://registry.npmjs.org';
const NPM_DL_BASE      = 'https://api.npmjs.org/downloads/point/last-month';

// ── Cache System (ป้องกันคนรัวปุ่ม) ─────────────────────────────────────────
let cachedChangelog    = null;
let lastChangelogFetch = 0;
const CACHE_COOLDOWN   = 5 * 60 * 1000; // 5 นาที
const HF_TREE_STALE_MS = 5 * 60 * 1000;
const HF_PREVIEW_MAX_BYTES = 256 * 1024;

// npm cache
let cachedNpmPackages    = null;
let lastNpmFetch         = 0;

// Hugging Face API cache (keyed by endpoint) with in-flight de-duplication
const hfApiCache = new Map();
const hfPendingRequests = new Map();
const hfRepoTreeCache = new Map();
const hfRepoCommitHeadCache = new Map();
const hfRepoFileCacheMeta = new Map();

const SKIP_FILES = new Set([
  '.gitattributes', 'README.md',
  'chahuadev-framework-binaries.png', 'emoji-cleaner-app.png'
]);

// Allowed npm packages for self-update / install (whitelist — renderer cannot override)
const NPM_PKG_WHITELIST = new Set([
  '@chahuadev/chahuadev-hub-app',
  '@chahuadev/dev-launcher',
  '@chahuadev/junk-sweeper-app',
  '@chahuadev/emoji-cleaner-app',
  '@chahuadev/framework'
]);

const isDev = !app.isPackaged && process.argv.includes('--dev');
const UPDATE_CHANNEL = ((process.env.APP_UPDATE_CHANNEL || process.env.UPDATE_CHANNEL || 'stable').toLowerCase() === 'beta') ? 'beta' : 'stable';
const UPDATE_BASE_URL = 'https://r2.chahuadev.com';
let updaterInitialized = false;
let updaterState = {
  lastCheckedAt: null,
  lastResult: 'idle',
  lastError: null
};
const security = new SecurityCore();

function configureUpdaterFeed() {
  const feedUrl = `${UPDATE_BASE_URL}/`;
  autoUpdater.setFeedURL({
    provider: 'generic',
    url: feedUrl
  });
  autoUpdater.allowPrerelease = UPDATE_CHANNEL === 'beta';
  autoUpdater.allowDowngrade = true;
  autoUpdater.channel = UPDATE_CHANNEL;
  console.log(`[Updater] Channel: ${UPDATE_CHANNEL} | Feed: ${feedUrl}`);
}

async function checkForUpdatesNow() {
  updaterState.lastCheckedAt = new Date().toISOString();
  try {
    const result = await autoUpdater.checkForUpdates();
    const version = result && result.updateInfo && result.updateInfo.version ? result.updateInfo.version : null;
    updaterState.lastResult = version ? 'update-available' : 'no-update';
    updaterState.lastError = null;
    return {
      ok: true,
      channel: UPDATE_CHANNEL,
      updateAvailable: Boolean(version),
      version
    };
  } catch (error) {
    updaterState.lastResult = 'error';
    updaterState.lastError = error && error.message ? error.message : String(error);
    return {
      ok: false,
      channel: UPDATE_CHANNEL,
      error: updaterState.lastError
    };
  }
}

function initAutoUpdater() {
  if (!app.isPackaged || isDev) return;
  configureUpdaterFeed();
  autoUpdater.autoDownload = true;
  autoUpdater.autoInstallOnAppQuit = true;
  autoUpdater.logger = console;
  autoUpdater.on('error', (e) => {
    updaterState.lastResult = 'error';
    updaterState.lastError = e && e.message ? e.message : String(e);
    console.warn('[Updater] Error:', updaterState.lastError);
  });
  autoUpdater.on('update-available', () => {
    updaterState.lastResult = 'update-available';
    updaterState.lastError = null;
  });
  autoUpdater.on('update-not-available', () => {
    updaterState.lastResult = 'no-update';
    updaterState.lastError = null;
  });
  autoUpdater.on('update-downloaded', (info) => {
    updaterState.lastResult = 'downloaded';
    const r = require('electron').dialog.showMessageBoxSync({
      type: 'info',
      buttons: ['Restart now', 'Later'],
      defaultId: 0,
      cancelId: 1,
      title: 'Update ready',
      message: `Version ${info && info.version ? info.version : 'new'} is ready to install.`
    });
    if (r === 0) autoUpdater.quitAndInstall();
  });
  setTimeout(() => autoUpdater.checkForUpdates().catch(() => {}), 12000);
  setInterval(() => autoUpdater.checkForUpdates().catch(() => {}), 6 * 60 * 60 * 1000);
  updaterInitialized = true;
}

function createDevMenuTemplate() {
  return [
    {
      label: 'File',
      submenu: [
        { role: 'close' },
        { type: 'separator' },
        { role: process.platform === 'darwin' ? 'hide' : 'quit' }
      ]
    },
    {
      label: 'Edit',
      submenu: [
        { role: 'undo' }, { role: 'redo' },
        { type: 'separator' },
        { role: 'cut' }, { role: 'copy' }, { role: 'paste' },
        { role: 'selectAll' }
      ]
    },
    {
      label: 'View',
      submenu: [
        { role: 'reload' },
        { role: 'forceReload' },
        { type: 'separator' },
        { role: 'resetZoom' },
        { role: 'zoomIn' },
        { role: 'zoomOut' },
        { type: 'separator' },
        { role: 'togglefullscreen' }
      ]
    },
    {
      label: 'Window',
      submenu: [
        { role: 'minimize' },
        { role: 'zoom' },
        { role: 'close' }
      ]
    },
    {
      label: 'Help',
      submenu: [
        {
          label: 'Chahuadev Website',
          click: () => shell.openExternal('https://chahuadev.com/')
        }
      ]
    },
    {
      label: 'Dev',
      submenu: [
        { role: 'toggleDevTools' },
        { role: 'reload' },
        { role: 'forceReload' }
      ]
    }
  ];
}

function applyProductionWindowHardening(win) {
  if (isDev || !win || win.isDestroyed()) return;

  win.webContents.on('before-input-event', (event, input) => {
    const key = (input.key || '').toLowerCase();
    const blockedShortcut =
      key === 'f12' ||
      ((input.control || input.meta) && input.shift && (key === 'i' || key === 'j' || key === 'c'));

    if (blockedShortcut) {
      event.preventDefault();
    }
  });

  win.webContents.on('devtools-opened', () => {
    if (!win.webContents.isDestroyed()) {
      win.webContents.closeDevTools();
    }
  });
}

// ── Security Init ────────────────────────────────────────────────────────────────────
function initSecurity() {
  security.applySecurityConfig();  // Layer 5b: enforce strict CSP from main process (survives HTML tampering)
  security.applyStrictCSP(session.defaultSession, isDev);  if (!isDev) {
    const ok = security.validateChecksums();
    if (!ok) {
      console.error('[Security] CRITICAL: Integrity check failed.');
      // Don’t hard-exit on first run (checksums may not exist yet)
    }
    console.log('[Security] Production mode active.');
  } else {
    console.log('[Security] Dev mode — security checks relaxed.');
  }
}

// ── Windows ───────────────────────────────────────────────────────────────────
let mainWindow   = null;
let splashWindow = null;

// ── HTTP Helper (follows redirects) ──────────────────────────────────────────
function fetchJSON(urlStr, redirectCount = 0) {
  return new Promise((resolve, reject) => {
    if (redirectCount > 10) return reject(new Error('Too many redirects'));
    let parsed;
    try { parsed = new URL(urlStr); } catch (e) { return reject(e); }
    const mod = parsed.protocol === 'https:' ? https : http;
    const req = mod.get(urlStr, {
      headers: { 'User-Agent': 'ChahuadevHub/1.0.0 (Electron)' }
    }, (res) => {
      if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
        res.resume();
        const nextUrl = new URL(res.headers.location, urlStr).toString();
        fetchJSON(nextUrl, redirectCount + 1).then(resolve).catch(reject);
        return;
      }
      if (res.statusCode !== 200) {
        res.resume();
        return reject(new Error(`HTTP ${res.statusCode} — ${urlStr}`));
      }
      let data = '';
      res.on('data', chunk => { data += chunk; });
      res.on('end', () => {
        try { resolve(JSON.parse(data)); } catch (e) { reject(e); }
      });
      res.on('error', reject);
    });
    req.on('error', reject);
    req.setTimeout(20000, () => { req.destroy(new Error('Request timeout')); });
  });
}

async function fetchWithCooldownCache(cacheKey, fetcher) {
  const now = Date.now();
  const cached = hfApiCache.get(cacheKey);
  if (cached && (now - cached.ts < CACHE_COOLDOWN)) {
    return cached.data;
  }

  if (hfPendingRequests.has(cacheKey)) {
    return hfPendingRequests.get(cacheKey);
  }

  const pending = (async () => {
    const data = await fetcher();
    hfApiCache.set(cacheKey, { ts: Date.now(), data });
    return data;
  })();

  hfPendingRequests.set(cacheKey, pending);
  try {
    return await pending;
  } finally {
    hfPendingRequests.delete(cacheKey);
  }
}

function normalizeRepoPath(input) {
  const raw = String(input || '').replace(/\\/g, '/').trim();
  if (!raw) return '';
  const cleaned = raw
    .split('/')
    .filter(Boolean)
    .filter(seg => seg !== '.' && seg !== '..')
    .join('/');
  return cleaned;
}

function getRepoTypeSegment(repoType) {
  const t = String(repoType || '').toLowerCase();
  if (t === 'dataset') return 'datasets';
  if (t === 'space') return 'spaces';
  return 'models';
}

function buildRepoTreeApiUrl(repoId, repoType, repoPath = '', expand = false) {
  const typeSegment = getRepoTypeSegment(repoType);
  const normalizedPath = normalizeRepoPath(repoPath);
  const encodedPath = normalizedPath
    ? '/' + normalizedPath.split('/').map(encodeURIComponent).join('/')
    : '';
  const suffix = expand ? '?expand=true' : '';
  return `https://huggingface.co/api/${typeSegment}/${repoId}/tree/main${encodedPath}${suffix}`;
}

function buildRepoRawFileUrl(repoId, repoType, repoPath) {
  const normalizedPath = normalizeRepoPath(repoPath);
  const encodedPath = normalizedPath.split('/').map(encodeURIComponent).join('/');
  const prefix = repoType === 'dataset' ? 'datasets/' : repoType === 'space' ? 'spaces/' : '';
  return `https://huggingface.co/${prefix}${repoId}/resolve/main/${encodedPath}?download=true`;
}

function getRepoCacheRoot(repoId, repoType) {
  const safeRepo = String(repoId || '').replace(/[^a-zA-Z0-9._\/-]/g, '_');
  const root = path.join(HF_SANDBOX_DIR, getRepoTypeSegment(repoType), safeRepo);
  fs.mkdirSync(root, { recursive: true });
  return root;
}

function resolveSafeRepoLocalPath(repoId, repoType, repoPath) {
  const repoRoot = getRepoCacheRoot(repoId, repoType);
  const parts = normalizeRepoPath(repoPath).split('/').filter(Boolean);
  const target = path.resolve(repoRoot, ...parts);
  const safeRoot = path.resolve(repoRoot);
  if (!target.startsWith(safeRoot)) {
    throw new Error('Invalid file path');
  }
  fs.mkdirSync(path.dirname(target), { recursive: true });
  return target;
}

async function getLatestRepoCommitHead(repoId, repoType) {
  const key = `${repoType}:${repoId}`;
  const now = Date.now();
  const cached = hfRepoCommitHeadCache.get(key);
  if (cached && (now - cached.checkedAt < HF_TREE_STALE_MS)) {
    return cached;
  }

  const url = `https://huggingface.co/api/${getRepoTypeSegment(repoType)}/${repoId}/commits/main`;
  const commits = await fetchJSON(url);
  const head = Array.isArray(commits) && commits[0] ? commits[0] : {};
  const value = {
    id: String(head.id || head.sha || ''),
    date: String(head.date || head.createdAt || ''),
    checkedAt: now
  };
  hfRepoCommitHeadCache.set(key, value);
  return value;
}

async function fetchRepoTreeSmart(repoId, repoType, options = {}) {
  const normalizedPath = normalizeRepoPath(options.path || '');
  const expand = !!options.expand;
  const force = !!options.force;
  const cacheKey = `${repoType}:${repoId}:${normalizedPath}:${expand ? 'expand' : 'flat'}`;
  const now = Date.now();
  const cached = hfRepoTreeCache.get(cacheKey);

  if (cached && !force && (now - cached.checkedAt < HF_TREE_STALE_MS)) {
    return cached.entries;
  }

  let head = null;
  try {
    head = await getLatestRepoCommitHead(repoId, repoType);
  } catch {
    // If commit endpoint fails but we have cached tree, serve cache.
    if (cached && !force) {
      cached.checkedAt = now;
      return cached.entries;
    }
  }

  if (cached && !force && head && head.id && cached.commitId && head.id === cached.commitId) {
    cached.checkedAt = now;
    return cached.entries;
  }

  const url = buildRepoTreeApiUrl(repoId, repoType, normalizedPath, expand);
  const entries = await fetchJSON(url);
  const normalizedEntries = Array.isArray(entries) ? entries : [];
  hfRepoTreeCache.set(cacheKey, {
    entries: normalizedEntries,
    checkedAt: now,
    commitId: head && head.id ? head.id : (cached && cached.commitId ? cached.commitId : ''),
    path: normalizedPath,
    expand
  });
  return normalizedEntries;
}

function detectLanguageFromPath(filePath) {
  const ext = path.extname(String(filePath || '')).toLowerCase();
  const map = {
    '.js': 'javascript', '.cjs': 'javascript', '.mjs': 'javascript',
    '.ts': 'typescript', '.tsx': 'typescript', '.jsx': 'javascript',
    '.json': 'json', '.md': 'markdown', '.txt': 'plaintext',
    '.html': 'html', '.css': 'css', '.scss': 'scss',
    '.py': 'python', '.java': 'java', '.go': 'go',
    '.yml': 'yaml', '.yaml': 'yaml', '.xml': 'xml',
    '.sh': 'shell', '.bat': 'bat', '.ps1': 'powershell',
    '.rs': 'rust', '.cpp': 'cpp', '.c': 'c'
  };
  return map[ext] || 'plaintext';
}

function isLikelyTextBuffer(buffer) {
  if (!buffer || buffer.length === 0) return true;
  const sample = buffer.subarray(0, Math.min(buffer.length, 4096));
  for (let i = 0; i < sample.length; i++) {
    if (sample[i] === 0) return false;
  }
  return true;
}

async function cacheRepoFileLocally(repoId, repoType, repoPath) {
  const normalizedPath = normalizeRepoPath(repoPath);
  if (!normalizedPath) throw new Error('Missing repo file path');

  const metaKey = `${repoType}:${repoId}:${normalizedPath}`;
  const head = await getLatestRepoCommitHead(repoId, repoType).catch(() => null);
  const localPath = resolveSafeRepoLocalPath(repoId, repoType, normalizedPath);
  const prevMeta = hfRepoFileCacheMeta.get(metaKey);

  if (
    prevMeta &&
    fs.existsSync(prevMeta.localPath) &&
    head &&
    head.id &&
    prevMeta.commitId === head.id
  ) {
    return { localPath: prevMeta.localPath, commitId: prevMeta.commitId };
  }

  const rawUrl = buildRepoRawFileUrl(repoId, repoType, normalizedPath);
  await downloadRaw(rawUrl, localPath);
  try {
    fs.chmodSync(localPath, 0o444);
  } catch {
    // Best effort only; some environments may not support chmod semantics.
  }

  const commitId = head && head.id ? head.id : (prevMeta && prevMeta.commitId ? prevMeta.commitId : '');
  hfRepoFileCacheMeta.set(metaKey, { localPath, commitId, updatedAt: Date.now() });
  return { localPath, commitId };
}

function openFileInBestEditor(targetPath) {
  return new Promise((resolve) => {
    const safePath = String(targetPath || '');
    if (!safePath) return resolve('not-found');

    const quoted = safePath.replace(/"/g, '\\"');
    exec(`code -g "${quoted}"`, { windowsHide: true }, (codeErr) => {
      if (!codeErr) return resolve('ok-vscode');

      const npCandidates = [
        process.env.NotepadPlusPlusPath || '',
        'C:\\Program Files\\Notepad++\\notepad++.exe',
        'C:\\Program Files (x86)\\Notepad++\\notepad++.exe'
      ].filter(Boolean);

      const npPath = npCandidates.find(p => fs.existsSync(p));
      if (npPath) {
        const child = spawn(npPath, [safePath], { detached: true, stdio: 'ignore', windowsHide: true });
        child.unref();
        return resolve('ok-notepadpp');
      }

      shell.openPath(safePath).then(() => resolve('ok-default')).catch(() => resolve('error'));
    });
  });
}

// ── Semver comparison helper ──────────────────────────────────────────────────
function semverGt(a, b) {
  const pa = String(a || '0').split('.').map(Number);
  const pb = String(b || '0').split('.').map(Number);
  for (let i = 0; i < 3; i++) {
    const na = pa[i] || 0, nb = pb[i] || 0;
    if (na > nb) return true;
    if (na < nb) return false;
  }
  return false;
}

function mapPlatformToCatalogOs(platform) {
  if (platform === 'win32') return 'Windows';
  if (platform === 'linux') return 'Linux';
  if (platform === 'darwin') return 'macOS';
  return 'Unknown';
}

function findCatalogEntry(catalog) {
  const files = catalog && Array.isArray(catalog.files) ? catalog.files : [];
  const platformOs = mapPlatformToCatalogOs(process.platform);
  const exact = files.find((f) => f && f.id === APP_CATALOG_ID && f.os === platformOs);
  if (exact) return exact;
  return files.find((f) => f && f.id === APP_CATALOG_ID) || null;
}

// ── Raw file downloader used by hot-patch ─────────────────────────────────────
function downloadRaw(urlStr, destPath, redirectCount = 0) {
  return new Promise((resolve, reject) => {
    if (redirectCount > 10) return reject(new Error('Too many redirects'));
    let parsed;
    try { parsed = new URL(urlStr); } catch (e) { return reject(e); }
    const mod = parsed.protocol === 'https:' ? https : http;
    const req = mod.get(urlStr, {
      headers: { 'User-Agent': 'ChahuadevHub/1.0.0 (Electron)' }
    }, (res) => {
      if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
        res.resume();
        const nextUrl = new URL(res.headers.location, urlStr).toString();
        downloadRaw(nextUrl, destPath, redirectCount + 1).then(resolve).catch(reject);
        return;
      }
      if (res.statusCode !== 200) { res.resume(); return reject(new Error(`HTTP ${res.statusCode}`)); }
      fs.mkdirSync(path.dirname(destPath), { recursive: true });
      const ws = fs.createWriteStream(destPath);
      res.pipe(ws);
      ws.on('finish', () => ws.close(() => resolve(destPath)));
      ws.on('error', reject);
    });
    req.on('error', reject);
    req.setTimeout(30000, () => req.destroy(new Error('Timeout')));
  });
}

// ── Splash Window ─────────────────────────────────────────────────────────────
function createSplashWindow() {
  splashWindow = new BrowserWindow({
    width: 520,
    height: 340,
    frame: false,
    resizable: false,
    alwaysOnTop: true,
    skipTaskbar: true,
    center: true,
    backgroundColor: '#09090f',
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: false,
      contextIsolation: true,
      sandbox: true
    }
  });
  splashWindow.loadFile(path.join(__dirname, 'splash.html'));
  splashWindow.webContents.on('will-navigate', (e) => e.preventDefault());
}

// ── Main Window ───────────────────────────────────────────────────────────────
function createMainWindow() {
  mainWindow = new BrowserWindow({
    width: 1100,
    height: 740,
    minWidth: 900,
    minHeight: 580,
    show: false,
    backgroundColor: '#09090f',
    icon: path.join(__dirname, 'icons', 'icon.png'),
    autoHideMenuBar: !isDev,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: false,
      contextIsolation: true,
      sandbox: true
    }
  });

  mainWindow.loadFile(path.join(__dirname, 'index.html'));
  mainWindow.setMenuBarVisibility(isDev);

  // Block external navigation
  mainWindow.webContents.on('will-navigate', (e) => e.preventDefault());
  mainWindow.webContents.setWindowOpenHandler(() => ({ action: 'deny' }));

  // Security: DevTools lockdown + navigation guard
  security.applyDevToolsLockdown(mainWindow, isDev);
  applyProductionWindowHardening(mainWindow);

  mainWindow.once('ready-to-show', () => {
    const delay = isDev ? 120 : 350;
    setTimeout(() => {
      if (splashWindow && !splashWindow.isDestroyed()) {
        splashWindow.close();
        splashWindow = null;
      }
      if (mainWindow && !mainWindow.isDestroyed()) {
        mainWindow.show();
        mainWindow.focus();
        if (isDev) mainWindow.webContents.openDevTools();
      }
    }, delay);
  });

  mainWindow.on('closed', () => { mainWindow = null; });
}

// ── App lifecycle ─────────────────────────────────────────────────────────────
app.whenReady().then(() => {
  createSplashWindow();
  initSecurity();
  initAutoUpdater();
  if (isDev) {
    Menu.setApplicationMenu(Menu.buildFromTemplate(createDevMenuTemplate()));
  } else {
    Menu.setApplicationMenu(null);
  }
  fs.mkdirSync(DOWNLOAD_DIR, { recursive: true });
  createMainWindow();

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createMainWindow();
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

// ════════════════════════════════════════════════════════════════════════════
// IPC Handlers
// ════════════════════════════════════════════════════════════════════════════

// Return download directory path
ipcMain.handle('get-download-dir', () => DOWNLOAD_DIR);

// Expose isDev flag to renderer (for hiding dev-only features)
ipcMain.handle('get-is-dev', () => isDev);

// Fetch file list from catalog.json (GitHub primary, R2 + local fallback)
ipcMain.handle('fetch-files', async () => {
  const parseFiles = (data) => {
    if (Array.isArray(data)) return data;
    if (data && Array.isArray(data.files)) return data.files;
    return [];
  };

  const sources = [
    GITHUB_CATALOG_URL,
    R2_CATALOG_URL,
  ];

  for (const src of sources) {
    try {
      const data = await fetchWithCooldownCache(src, () => fetchJSON(src));
      return { files: parseFiles(data) };
    } catch (error) {
      console.warn('[catalog] Remote fetch failed:', src, error.message);
    }
  }

  try {
    const localPath = path.join(__dirname, 'catalog.json');
    if (fs.existsSync(localPath)) {
      const raw = fs.readFileSync(localPath, 'utf8');
      const data = JSON.parse(raw);
      return { files: parseFiles(data) };
    }
  } catch (localErr) {
    console.error('[catalog] Local fallback failed:', localErr.message);
  }

  return { files: [] };
});

// Fetch commit changelog — with cache + cooldown to block API spam
ipcMain.handle('fetch-changelog', async () => {
  const now = Date.now();

  if (cachedChangelog && (now - lastChangelogFetch < CACHE_COOLDOWN)) {
    console.log('[Cache] Returning cached changelog');
    return cachedChangelog;
  }

  try {
    const endpoints = [
      [HF_DATASETS_API, 'dataset'],
      [HF_MODELS_API,   'model'],
      [HF_SPACES_API,   'space']
    ];

    let allRepos = [];
    for (const [url, rtype] of endpoints) {
      try {
        const data = await fetchJSON(url);
        for (const r of data) allRepos.push({ repoId: r.id || r.modelId, type: rtype });
      } catch (_) { }
    }

    const commitPromises = allRepos.map(async ({ repoId, type }) => {
      const commitUrl = `https://huggingface.co/api/${type}s/${repoId}/commits/main`;
      try {
        const commits = await fetchJSON(commitUrl);
        return commits.map(c => {
          const shortRepo = repoId.split('/').pop();
          c.title = `[${shortRepo}] ${c.title || c.message || '—'}`;
          return c;
        });
      } catch (_) { return []; }
    });

    const results = await Promise.all(commitPromises);
    let allCommits = [];
    results.forEach(repoCommits => { allCommits = allCommits.concat(repoCommits); });
    allCommits.sort((a, b) => new Date(b.date) - new Date(a.date));
    const finalData = allCommits.slice(0, 50);

    cachedChangelog    = finalData;
    lastChangelogFetch = now;
    return finalData;

  } catch (err) {
    console.error('Changelog fetch error:', err);
    throw err;
  }
});

// Fetch all repos (datasets + models + spaces) for Explorer panel
ipcMain.handle('fetch-all-repos', async () => {
  const [datasetsRaw, modelsRaw, spacesRaw] = await Promise.all([
    fetchWithCooldownCache(HF_DATASETS_API, () => fetchJSON(HF_DATASETS_API)).catch(() => []),
    fetchWithCooldownCache(HF_MODELS_API, () => fetchJSON(HF_MODELS_API)).catch(()   => []),
    fetchWithCooldownCache(HF_SPACES_API, () => fetchJSON(HF_SPACES_API)).catch(()   => []),
  ]);

  const sortByDate = arr => [...arr].sort((a, b) => {
    const da = a.lastModified || a.updatedAt || '';
    const db = b.lastModified || b.updatedAt || '';
    return db.localeCompare(da);
  });

  return {
    datasets: sortByDate(Array.isArray(datasetsRaw) ? datasetsRaw : []),
    models:   sortByDate(Array.isArray(modelsRaw)   ? modelsRaw   : []),
    spaces:   sortByDate(Array.isArray(spacesRaw)   ? spacesRaw   : []),
  };
});

// Fetch commits for a specific repo
ipcMain.handle('fetch-repo-commits', async (_, repoId, repoType) => {
  const url = `https://huggingface.co/api/${repoType}s/${repoId}/commits/main`;
  return await fetchWithCooldownCache(url, () => fetchJSON(url));
});

// Fetch file tree for a specific repo
ipcMain.handle('fetch-repo-tree', async (_, repoId, repoType, options = {}) => {
  return fetchRepoTreeSmart(repoId, repoType, options);
});

ipcMain.handle('fetch-repo-file', async (_, repoId, repoType, repoPath) => {
  try {
    const normalizedPath = normalizeRepoPath(repoPath);
    if (!normalizedPath) {
      return { ok: false, error: 'Missing file path' };
    }

    const { localPath } = await cacheRepoFileLocally(repoId, repoType, normalizedPath);
    const stat = fs.statSync(localPath);
    const isTooLarge = stat.size > HF_PREVIEW_MAX_BYTES;
    const previewSize = Math.min(stat.size, HF_PREVIEW_MAX_BYTES);
    const buffer = Buffer.alloc(previewSize);
    const fd = fs.openSync(localPath, 'r');
    try {
      fs.readSync(fd, buffer, 0, previewSize, 0);
    } finally {
      fs.closeSync(fd);
    }
    const isText = isLikelyTextBuffer(buffer);
    let content = '';

    if (isText) {
      content = buffer.toString('utf8');
    }

    return {
      ok: true,
      path: normalizedPath,
      localPath,
      isText,
      size: stat.size,
      truncated: isTooLarge,
      language: detectLanguageFromPath(normalizedPath),
      content
    };
  } catch (error) {
    return { ok: false, error: error && error.message ? error.message : String(error) };
  }
});

ipcMain.handle('open-repo-file-editor', async (_, repoId, repoType, repoPath) => {
  try {
    const normalizedPath = normalizeRepoPath(repoPath);
    if (!normalizedPath) return { ok: false, error: 'Missing file path' };
    const { localPath } = await cacheRepoFileLocally(repoId, repoType, normalizedPath);
    const result = await openFileInBestEditor(localPath);
    return { ok: result !== 'error', mode: result, localPath };
  } catch (error) {
    return { ok: false, error: error && error.message ? error.message : String(error) };
  }
});

// Fetch dashboard stats: datasets + models + spaces counts, total downloads, recent activity
ipcMain.handle('fetch-dashboard', async () => {
  const endpoints = [
    [HF_DATASETS_API, 'dataset'],
    [HF_MODELS_API,   'model'],
    [HF_SPACES_API,   'space']
  ];
  const stats   = { datasets: 0, models: 0, spaces: 0, totalDownloads: 0 };
  const activity = [];

  for (const [url, rtype] of endpoints) {
    try {
      const data = await fetchWithCooldownCache(url, () => fetchJSON(url));
      if (!Array.isArray(data)) continue;
      if (rtype === 'dataset') stats.datasets = data.length;
      if (rtype === 'model')   stats.models   = data.length;
      if (rtype === 'space')   stats.spaces   = data.length;
      for (const r of data) {
        const dl = r.downloads || r.downloadsAllTime || 0;
        stats.totalDownloads += Number(dl) || 0;
        const id      = r.id || r.modelId || '';
        const updated = r.lastModified || r.updatedAt || '';
        if (id && updated) activity.push({ id, type: rtype, updated, private: !!r.private });
      }
    } catch (_) { /* skip */ }
  }

  activity.sort((a, b) => b.updated.localeCompare(a.updated));
  return { stats, activity: activity.slice(0, 20) };
});

// ── npm Packages ─────────────────────────────────────────────────────────────
// Fetch all packages in the @chahuadev npm org with metadata + monthly downloads
ipcMain.handle('fetch-npm-packages', async () => {
  const now = Date.now();
  if (cachedNpmPackages && (now - lastNpmFetch < CACHE_COOLDOWN)) {
    return cachedNpmPackages;
  }

  try {
    // 1. Get list of packages in the org
    const pkgMap = await fetchJSON(NPM_ORG_PKG_URL);
    const names  = Object.keys(pkgMap || {});

    // 2. Fetch metadata + downloads for each package in parallel
    const results = await Promise.all(
      names.map(async (name) => {
        const [meta, dlData] = await Promise.all([
          fetchJSON(`${NPM_REG_BASE}/${encodeURIComponent(name)}`).catch(() => null),
          fetchJSON(`${NPM_DL_BASE}/${encodeURIComponent(name)}`).catch(() => null),
        ]);

        const latest  = meta?.['dist-tags']?.latest || '';
        const verData = meta?.versions?.[latest] || {};
        const timeMap = meta?.time || {};
        const versionTimeRows = Object.entries(timeMap)
          .filter(([v]) => v !== 'created' && v !== 'modified')
          .sort((a, b) => String(b[1] || '').localeCompare(String(a[1] || '')));
        const repositoryUrl = typeof verData.repository === 'string'
          ? verData.repository
          : (verData.repository && verData.repository.url ? verData.repository.url : '');
        const readmeRaw = typeof meta?.readme === 'string' ? meta.readme : '';
        const readmeExcerpt = readmeRaw.slice(0, 12000);
        return {
          name,
          version:     latest,
          description: verData.description || meta?.description || '',
          keywords:    verData.keywords    || [],
          homepage:    verData.homepage    || `https://www.npmjs.com/package/${encodeURIComponent(name)}`,
          license:     verData.license     || '',
          updatedAt:   meta?.time?.[latest] || '',
          downloads:   dlData?.downloads   || 0,
          versionsCount: Object.keys(meta?.versions || {}).length,
          recentVersions: versionTimeRows.slice(0, 12).map(([version, date]) => ({ version, date })),
          repositoryUrl,
          npmUrl: `https://www.npmjs.com/package/${encodeURIComponent(name)}`,
          readmeExcerpt,
        };
      })
    );

    // Sort by downloads descending
    results.sort((a, b) => b.downloads - a.downloads);

    cachedNpmPackages = results;
    lastNpmFetch      = now;
    return results;
  } catch (err) {
    console.error('[npm] fetch-npm-packages error:', err);
    throw err;
  }
});

// Check if a downloaded file already exists on disk
ipcMain.handle('check-file-exists', (_, filePath) => {
  const destPath = path.join(DOWNLOAD_DIR, filePath);
  return fs.existsSync(destPath);
});

// ── Update detection: single downloads-meta.json inside app userData ─────────
// Stored in %APPDATA%/Chahuadev-Hub/downloads-meta.json  (never in user Downloads)
// Schema: { "Junk-Sweeper.exe": { version, releaseDate }, ... }
const DOWNLOADS_META_PATH = path.join(app.getPath('userData'), 'downloads-meta.json');

function readDownloadsMeta() {
  try {
    if (!fs.existsSync(DOWNLOADS_META_PATH)) return {};
    return JSON.parse(fs.readFileSync(DOWNLOADS_META_PATH, 'utf8'));
  } catch { return {}; }
}

function writeDownloadsMeta(data) {
  fs.mkdirSync(path.dirname(DOWNLOADS_META_PATH), { recursive: true });
  fs.writeFileSync(DOWNLOADS_META_PATH, JSON.stringify(data, null, 2), 'utf8');
}

ipcMain.handle('save-file-meta', (_, filePath, meta) => {
  const all = readDownloadsMeta();
  all[filePath] = meta;
  writeDownloadsMeta(all);
  return { success: true };
});

ipcMain.handle('get-file-meta', (_, filePath) => {
  const all = readDownloadsMeta();
  return all[filePath] || null;
});

// Open a locally downloaded file / launch it
// Layer 6: verify hash from catalog before opening
ipcMain.handle('open-file', async (_, filePath, expectedHash) => {
  const destPath = path.join(DOWNLOAD_DIR, filePath);
  if (!fs.existsSync(destPath)) return 'not-found';
  if (expectedHash) {
    const { ok } = security.verifyDownloadedFile(destPath, expectedHash);
    if (!ok) return 'integrity-failed';
  }
  return shell.openPath(destPath);
});

// Open the folder containing a downloaded file in the system file explorer
ipcMain.handle('open-file-folder', async (_, filePath) => {
  const destPath = path.join(DOWNLOAD_DIR, filePath);
  if (!fs.existsSync(destPath)) {
    // If file doesn't exist, open the parent download directory instead
    return shell.openPath(DOWNLOAD_DIR);
  }
  shell.showItemInFolder(destPath);
  return 'ok';
});

// Open downloads folder in system file explorer
ipcMain.handle('open-downloads', async () => {
  fs.mkdirSync(DOWNLOAD_DIR, { recursive: true });
  return shell.openPath(DOWNLOAD_DIR);
});

// Open external URL — allow whitelisted hosts only
const ALLOWED_EXTERNAL_HOSTS = new Set([
  'huggingface.co',
  'github.com',
  'raw.githubusercontent.com',
  'www.tiktok.com',
  'chahuadev.com',
  'www.chahuadev.com',
  'www.npmjs.com',
  'r2.chahuadev.com',
  'www.buymeacoffee.com',
  'buymeacoffee.com',
]);
ipcMain.handle('open-external-url', (_, url) => {
  if (typeof url !== 'string') return;
  try {
    const parsed = new URL(url);
    if (parsed.protocol !== 'https:') return;
    if (!ALLOWED_EXTERNAL_HOSTS.has(parsed.hostname)) return;
    shell.openExternal(parsed.toString());
  } catch (_) {
    return;
  }
});

// Download a file with streaming progress events
ipcMain.handle('download-file', (event, filePath, fileSize) => {
  return new Promise((resolve, reject) => {
    // Build download URL — encode each path segment individually
    const encodedPath = filePath.split('/').map(encodeURIComponent).join('/');
    const downloadUrl = `${R2_CDN_BASE}/${encodedPath}`;
    const destPath    = path.join(DOWNLOAD_DIR, filePath);

    // Ensure destination directory exists
    fs.mkdirSync(path.dirname(destPath), { recursive: true });

    function download(urlStr, redirectCount) {
      if (redirectCount > 15) return reject(new Error('Too many redirects'));
      let parsed;
      try { parsed = new URL(urlStr); } catch (e) { return reject(e); }
      const mod = parsed.protocol === 'https:' ? https : http;

      const req = mod.get(urlStr, {
        headers: { 'User-Agent': 'ChahuadevHub/1.0.0 (Electron)' }
      }, (res) => {
        // Follow redirect
        if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
          res.resume();
          const nextUrl = new URL(res.headers.location, urlStr).toString();
          download(nextUrl, redirectCount + 1);
          return;
        }
        if (res.statusCode !== 200) {
          res.resume();
          return reject(new Error(`HTTP ${res.statusCode}`));
        }

        const total = parseInt(res.headers['content-length'] || fileSize || '0', 10);
        let downloaded = 0;
        const fileStream = fs.createWriteStream(destPath);

        res.on('data', (chunk) => {
          downloaded += chunk.length;
          fileStream.write(chunk);
          const pct = total > 0 ? downloaded / total : 0;
          if (!event.sender.isDestroyed()) {
            event.sender.send('download-progress', filePath, downloaded, total, pct);
          }
        });

        res.on('end', () => {
          fileStream.end(() => {
            resolve({ success: true, dest: destPath, downloaded });
          });
        });

        res.on('error', (err) => {
          fileStream.destroy();
          fs.unlink(destPath, () => {});
          reject(err);
        });
      });

      req.on('error', (err) => {
        fs.unlink(destPath, () => {});
        reject(err);
      });
      req.setTimeout(60000, () => {
        req.destroy(new Error('Download timeout'));
      });
    }

    download(downloadUrl, 0);
  });
});

// ════════════════════════════════════════════════════════════════════════════
// App Self-Update (Approach 1 + 2)
// ════════════════════════════════════════════════════════════════════════════

// Return current app version
ipcMain.handle('get-app-version', () => app.getVersion());

ipcMain.handle('updater:get-channel', () => UPDATE_CHANNEL);

ipcMain.handle('updater:get-status', () => ({
  initialized: updaterInitialized,
  channel: UPDATE_CHANNEL,
  ...updaterState
}));

ipcMain.handle('updater:check-now', async () => {
  if (!app.isPackaged || isDev) {
    return { ok: false, channel: UPDATE_CHANNEL, error: 'Updater is disabled in development mode.' };
  }
  if (!updaterInitialized) {
    return { ok: false, channel: UPDATE_CHANNEL, error: 'Updater is not initialized yet.' };
  }
  return checkForUpdatesNow();
});

// Fetch catalog.json from R2, compare with running version
ipcMain.handle('check-app-update', async () => {
  try {
    const catalog = await fetchJSON(R2_CATALOG_URL);
    const latestEntry = findCatalogEntry(catalog);
    if (!latestEntry || !latestEntry.version) {
      return { hasUpdate: false, error: `No catalog entry for ${APP_CATALOG_ID}` };
    }
    const current = app.getVersion();
    const latestVersion = String(latestEntry.version || '');
    const hasUpdate = semverGt(latestVersion, current);
    return {
      hasUpdate,
      current,
      latest:      latestVersion,
      releaseDate: String(latestEntry.releaseDate || ''),
      notes:       String(latestEntry.notes || ''),
      path:        String(latestEntry.path || ''),
      os:          String(latestEntry.os || '')
    };
  } catch (e) {
    return { hasUpdate: false, error: e.message };
  }
});

// ── npm self-update ───────────────────────────────────────────────────────────
// Runs: npm install -g @chahuadev/chahuadev-hub-app --foreground-scripts --force
// Uses exec() so Node's built-in shell handles npm resolution on all platforms.
// Security: command string is hardcoded — renderer passes no arguments.
ipcMain.handle('npm-self-update', (event) => {
  return new Promise((resolve) => {
    const CMD = 'npm install -g @chahuadev/chahuadev-hub-app --foreground-scripts --force';

    const send = (line) => {
      const trimmed = (line || '').toString().trim();
      if (trimmed && !event.sender.isDestroyed())
        event.sender.send('npm-update-log', trimmed);
    };

    const child = exec(CMD, { windowsHide: true });

    child.stdout.on('data', d => send(d));
    child.stderr.on('data', d => send(d));

    child.on('close', (code) => {
      resolve({ success: code === 0, code });
    });

    child.on('error', (err) => {
      send('ERROR: ' + err.message);
      resolve({ success: false, error: err.message });
    });
  });
});

// Relaunch app (kept for future use)
ipcMain.handle('relaunch-app', () => {
  app.relaunch();
  app.quit();
});

// Get npm global install path for a given package
ipcMain.handle('npm-get-install-path', (_, pkgName) => {
  return new Promise((resolve) => {
    exec('npm root -g', { windowsHide: true }, (err, stdout) => {
      if (err) return resolve(null);
      const root = stdout.trim();
      // Resolve scoped (@org/pkg) or unscoped (pkg) package path
      let pkgPath;
      if (pkgName && pkgName.startsWith('@')) {
        const parts = pkgName.slice(1).split('/');
        pkgPath = path.join(root, '@' + parts[0], parts[1] || '');
      } else if (pkgName) {
        pkgPath = path.join(root, pkgName);
      } else {
        pkgPath = path.join(root, '@chahuadev', 'chahuadev-hub-app');
      }
      resolve(fs.existsSync(pkgPath) ? pkgPath : root);
    });
  });
});

// Open the install folder for a given npm package (opens bin subdir if exists)
ipcMain.handle('open-npm-folder', (_, pkgName) => {
  return new Promise((resolve) => {
    exec('npm root -g', { windowsHide: true }, (err, stdout) => {
      if (err) return resolve('error');
      const root = stdout.trim();
      let pkgPath;
      if (pkgName && pkgName.startsWith('@')) {
        const parts = pkgName.slice(1).split('/');
        pkgPath = path.join(root, '@' + parts[0], parts[1] || '');
      } else if (pkgName) {
        pkgPath = path.join(root, pkgName);
      } else {
        return resolve('not-found');
      }
      if (!fs.existsSync(pkgPath)) return resolve('not-found');
      const binPath = path.join(pkgPath, 'bin');
      const openTarget = fs.existsSync(binPath) ? binPath : pkgPath;
      shell.openPath(openTarget);
      resolve('ok');
    });
  });
});

// Install any whitelisted npm package globally
ipcMain.handle('npm-install-package', (event, pkgName) => {
  if (!NPM_PKG_WHITELIST.has(pkgName)) {
    return Promise.resolve({ success: false, error: 'Package not in whitelist' });
  }
  return new Promise((resolve) => {
    const CMD = `npm install -g ${pkgName} --foreground-scripts --force`;
    const send = (line) => {
      const trimmed = (line || '').toString().trim();
      if (trimmed && !event.sender.isDestroyed())
        event.sender.send('npm-install-log', trimmed);
    };
    const child = exec(CMD, { windowsHide: true });
    child.stdout.on('data', d => send(d));
    child.stderr.on('data', d => send(d));
    child.on('close', (code) => resolve({ success: code === 0, code }));
    child.on('error', (err) => {
      send('ERROR: ' + err.message);
      resolve({ success: false, error: err.message });
    });
  });
});