coding-agent-search 0.6.0

Unified TUI search over local coding agent histories
Documentation
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
/**
 * cass Archive Viewer - Storage Abstraction Module
 *
 * Provides a unified interface for different storage backends:
 *   - memory: In-memory only (most secure, lost on page close)
 *   - session: sessionStorage (cleared when tab closes)
 *   - local: localStorage (persists across sessions)
 *   - opfs: Origin Private File System (persistent, largest capacity)
 *
 * Security model:
 *   - Default is memory-only for maximum security
 *   - User must explicitly opt-in to persistent storage
 *   - Clear functions available for all storage types
 */

// Storage modes
export const StorageMode = {
    MEMORY: 'memory',
    SESSION: 'session',
    LOCAL: 'local',
    OPFS: 'opfs',
};

// Storage keys (prefixed to avoid collisions)
const STORAGE_PREFIX = 'cass-archive-';
const ALL_ARCHIVE_DATA_PREFIX_RE = /^cass-archive-[0-9a-f]{8}-data-/;
const ALL_ARCHIVE_PREF_PREFIX_RE = /^cass-archive-[0-9a-f]{8}-pref-/;
const LEGACY_PREF_KEYS = {
    MODE: `${STORAGE_PREFIX}storage-mode`,
    OPFS_ENABLED: `${STORAGE_PREFIX}opfs-enabled`,
    LAST_UNLOCK: `${STORAGE_PREFIX}last-unlock`,
    DB_CACHED: `${STORAGE_PREFIX}db-cached`,
};
const KEYS = {
    get MODE() {
        return `${getArchivePreferencePrefix()}storage-mode`;
    },
    get OPFS_ENABLED() {
        return `${getArchivePreferencePrefix()}opfs-enabled`;
    },
    THEME: `${STORAGE_PREFIX}theme`,
    get LAST_UNLOCK() {
        return `${getArchivePreferencePrefix()}last-unlock`;
    },
    get DB_CACHED() {
        return `${getArchivePreferencePrefix()}db-cached`;
    },
};
const LEGACY_OPFS_DB_FILES = [
    'cass-archive.sqlite3',
    'cass-archive.sqlite3-wal',
    'cass-archive.sqlite3-shm',
    'cass-archive.db',
    'cass-archive.db-wal',
    'cass-archive.db-shm',
];
const LEGACY_SESSION_KEYS = [
    'cass_session_dek',
    'cass_session_expiry',
    'cass_unlocked',
];
const LEGACY_SESSION_MANAGER_KEYS = [
    'cass_session',
    'cass_expiry',
    'cass_storage_pref',
];
const ALL_ARCHIVE_SESSION_KEY_RE = /^cass_(?:session_(?:dek|expiry)|unlocked)_[0-9a-f]{8}$/;
const ALL_SESSION_MANAGER_KEY_RE = /^cass_(?:session|expiry|storage_pref)_[0-9a-f]{8}$/;
const ALL_ARCHIVE_TOFU_KEY_RE = /^cass_fingerprint_v2_[0-9a-f]{8}$/;

// In-memory storage (fallback and default)
const memoryStore = new Map();

// Current storage mode
let currentMode = StorageMode.MEMORY;
let opfsEnabled = false;

// OPFS directory handle (cached)
let opfsRoot = null;

function tryGetSessionStorage() {
    try {
        if (typeof sessionStorage !== 'undefined') {
            return sessionStorage;
        }
    } catch (error) {
        // Ignore unavailable storage backends.
    }
    return null;
}

function tryGetLocalStorage() {
    try {
        if (typeof localStorage !== 'undefined') {
            return localStorage;
        }
    } catch (error) {
        // Ignore unavailable storage backends.
    }
    return null;
}

function hashScopeId(input) {
    let hash = 0x811c9dc5;
    for (let i = 0; i < input.length; i++) {
        hash ^= input.charCodeAt(i);
        hash = Math.imul(hash, 0x01000193) >>> 0;
    }
    return hash.toString(16).padStart(8, '0');
}

export function getArchiveScopeUrl() {
    try {
        return new URL('./', window.location.href).href;
    } catch (error) {
        const href = typeof window?.location?.href === 'string'
            ? window.location.href
            : 'unknown';
        return href.split('#')[0].split('?')[0];
    }
}

export function getArchiveScopeId() {
    return hashScopeId(getArchiveScopeUrl());
}

function getArchivePreferencePrefix() {
    return `${STORAGE_PREFIX}${getArchiveScopeId()}-pref-`;
}

function getArchiveDataPrefix() {
    return `${STORAGE_PREFIX}${getArchiveScopeId()}-data-`;
}

function getArchiveDataKey(key) {
    return `${getArchiveDataPrefix()}${key}`;
}

function isArchiveDataEntryName(name) {
    return ALL_ARCHIVE_DATA_PREFIX_RE.test(name);
}

function isArchivePreferenceKey(name) {
    return ALL_ARCHIVE_PREF_PREFIX_RE.test(name);
}

function getCurrentArchiveSessionKeys() {
    const scopeId = getArchiveScopeId();
    return new Set([
        ...LEGACY_SESSION_KEYS,
        ...LEGACY_SESSION_MANAGER_KEYS,
        `cass_session_dek_${scopeId}`,
        `cass_session_expiry_${scopeId}`,
        `cass_unlocked_${scopeId}`,
        `cass_session_${scopeId}`,
        `cass_expiry_${scopeId}`,
        `cass_storage_pref_${scopeId}`,
    ]);
}

function isArchiveSessionKey(name) {
    return (
        LEGACY_SESSION_KEYS.includes(name)
        || LEGACY_SESSION_MANAGER_KEYS.includes(name)
        || ALL_ARCHIVE_SESSION_KEY_RE.test(name)
        || ALL_SESSION_MANAGER_KEY_RE.test(name)
    );
}

function getCurrentArchiveTofuKey() {
    return `cass_fingerprint_v2_${getArchiveScopeId()}`;
}

function isArchiveTofuKey(name) {
    return ALL_ARCHIVE_TOFU_KEY_RE.test(name);
}

function getServiceWorkerCachePrefix() {
    return `cass-archive-${getArchiveScopeId()}-`;
}

export function getArchiveOpfsDbFiles() {
    const scopeId = getArchiveScopeId();
    return [
        `cass-archive-${scopeId}.sqlite3`,
        `cass-archive-${scopeId}.sqlite3-wal`,
        `cass-archive-${scopeId}.sqlite3-shm`,
        `cass-archive-${scopeId}.db`,
        `cass-archive-${scopeId}.db-wal`,
        `cass-archive-${scopeId}.db-shm`,
    ];
}

export function getArchiveOpfsPrimaryDbName() {
    return getArchiveOpfsDbFiles()[0];
}

function isCassOpfsDbFile(name) {
    return (
        LEGACY_OPFS_DB_FILES.includes(name)
        || /^cass-archive-[0-9a-f]{8}\.(?:sqlite3|db)(?:-(?:wal|shm))?$/.test(name)
    );
}

/**
 * Initialize storage module
 * Loads saved storage mode preference
 */
export async function initStorage() {
    console.log('[Storage] Initializing...');

    const savedMode = getStoredMode();
    opfsEnabled = getPersistedOpfsEnabled();
    currentMode = savedMode;
    if (currentMode === StorageMode.OPFS) {
        if (!isOpfsEnabled()) {
            setOpfsEnabled(true);
        }
        currentMode = StorageMode.MEMORY;
        try {
            localStorage.setItem(KEYS.MODE, StorageMode.MEMORY);
        } catch (e) {
            // Ignore
        }
    }
    console.log('[Storage] Restored mode:', currentMode);

    return currentMode;
}

/**
 * Get current storage mode
 */
export function getStorageMode() {
    return currentMode;
}

/**
 * Get the stored storage mode preference
 */
export function getStoredMode() {
    try {
        const savedMode = localStorage.getItem(KEYS.MODE);
        if (savedMode && Object.values(StorageMode).includes(savedMode)) {
            return savedMode;
        }
    } catch (e) {
        // Ignore
    }
    return StorageMode.MEMORY;
}

function getPersistedOpfsEnabled() {
    try {
        return localStorage.getItem(KEYS.OPFS_ENABLED) === 'true';
    } catch (e) {
        return false;
    }
}

/**
 * Check if OPFS persistence is enabled by user
 */
export function isOpfsEnabled() {
    return opfsEnabled;
}

/**
 * Persist OPFS opt-in preference
 */
export function setOpfsEnabled(enabled) {
    opfsEnabled = Boolean(enabled);
    try {
        if (opfsEnabled) {
            localStorage.setItem(KEYS.OPFS_ENABLED, 'true');
        } else {
            localStorage.removeItem(KEYS.OPFS_ENABLED);
        }
    } catch (e) {
        console.warn('[Storage] Could not persist OPFS preference');
    }
    return opfsEnabled;
}

/**
 * Set storage mode
 * @param {string} mode - One of StorageMode values
 * @param {boolean} migrate - Whether to migrate existing data
 */
export async function setStorageMode(mode, migrate = false) {
    if (!Object.values(StorageMode).includes(mode)) {
        throw new Error(`Invalid storage mode: ${mode}`);
    }

    if (mode === StorageMode.OPFS) {
        if (!isOpfsEnabled()) {
            setOpfsEnabled(true);
        }
        mode = StorageMode.MEMORY;
    }

    const oldMode = currentMode;

    // Migrate data if requested
    if (migrate && oldMode !== mode) {
        await migrateStorage(oldMode, mode);
    }

    currentMode = mode;

    // Save mode preference (in localStorage so it persists)
    try {
        localStorage.setItem(KEYS.MODE, mode);
    } catch (e) {
        console.warn('[Storage] Could not save mode preference');
    }

    console.log('[Storage] Mode changed:', oldMode, '->', mode);
    return mode;
}

/**
 * Check if OPFS is available
 */
export function isOPFSAvailable() {
    return 'storage' in navigator && 'getDirectory' in navigator.storage;
}

/**
 * Initialize OPFS
 */
async function initOPFS() {
    if (!isOPFSAvailable()) {
        throw new Error('OPFS not available in this browser');
    }

    opfsRoot = await navigator.storage.getDirectory();
    console.log('[Storage] OPFS initialized');
    return opfsRoot;
}

/**
 * Get OPFS directory handle
 */
export async function getOPFSRoot() {
    if (!opfsRoot) {
        await initOPFS();
    }
    return opfsRoot;
}

/**
 * Store a value
 * @param {string} key - Storage key
 * @param {*} value - Value to store (will be JSON serialized)
 */
export async function setItem(key, value) {
    const fullKey = getArchiveDataKey(key);
    const serialized = JSON.stringify(value);

    switch (currentMode) {
        case StorageMode.MEMORY:
            memoryStore.set(fullKey, serialized);
            break;

        case StorageMode.SESSION:
            try {
                sessionStorage.setItem(fullKey, serialized);
            } catch (e) {
                console.warn('[Storage] sessionStorage write failed:', e);
                memoryStore.set(fullKey, serialized);
            }
            break;

        case StorageMode.LOCAL:
            try {
                localStorage.setItem(fullKey, serialized);
            } catch (e) {
                console.warn('[Storage] localStorage write failed:', e);
                memoryStore.set(fullKey, serialized);
            }
            break;

        case StorageMode.OPFS:
            await writeOPFSFile(fullKey, serialized);
            break;
    }
}

/**
 * Get a value
 * @param {string} key - Storage key
 * @param {*} defaultValue - Default value if not found
 */
export async function getItem(key, defaultValue = null) {
    const fullKey = getArchiveDataKey(key);
    let serialized = null;

    switch (currentMode) {
        case StorageMode.MEMORY:
            serialized = memoryStore.get(fullKey);
            break;

        case StorageMode.SESSION:
            try {
                serialized = sessionStorage.getItem(fullKey);
            } catch (e) {
                serialized = memoryStore.get(fullKey);
            }
            break;

        case StorageMode.LOCAL:
            try {
                serialized = localStorage.getItem(fullKey);
            } catch (e) {
                serialized = memoryStore.get(fullKey);
            }
            break;

        case StorageMode.OPFS:
            serialized = await readOPFSFile(fullKey);
            break;
    }

    if (serialized === null || serialized === undefined) {
        return defaultValue;
    }

    try {
        return JSON.parse(serialized);
    } catch (e) {
        return serialized;
    }
}

/**
 * Remove a value
 * @param {string} key - Storage key
 */
export async function removeItem(key) {
    const fullKey = getArchiveDataKey(key);

    switch (currentMode) {
        case StorageMode.MEMORY:
            memoryStore.delete(fullKey);
            break;

        case StorageMode.SESSION:
            try {
                sessionStorage.removeItem(fullKey);
            } catch (e) {
                // Ignore
            }
            memoryStore.delete(fullKey);
            break;

        case StorageMode.LOCAL:
            try {
                localStorage.removeItem(fullKey);
            } catch (e) {
                // Ignore
            }
            memoryStore.delete(fullKey);
            break;

        case StorageMode.OPFS:
            await deleteOPFSFile(fullKey);
            break;
    }
}

/**
 * Write file to OPFS
 */
async function writeOPFSFile(filename, content) {
    try {
        const root = await getOPFSRoot();
        const fileHandle = await root.getFileHandle(filename, { create: true });
        const writable = await fileHandle.createWritable();
        await writable.write(content);
        await writable.close();
    } catch (e) {
        console.error('[Storage] OPFS write failed:', e);
        // Fallback to memory
        memoryStore.set(filename, content);
    }
}

/**
 * Read file from OPFS
 */
async function readOPFSFile(filename) {
    try {
        const root = await getOPFSRoot();
        const fileHandle = await root.getFileHandle(filename);
        const file = await fileHandle.getFile();
        return await file.text();
    } catch (e) {
        if (e.name !== 'NotFoundError') {
            console.warn('[Storage] OPFS read failed:', e);
        }
        return null;
    }
}

/**
 * Delete file from OPFS
 */
async function deleteOPFSFile(filename) {
    try {
        const root = await getOPFSRoot();
        await root.removeEntry(filename);
    } catch (e) {
        if (e.name !== 'NotFoundError') {
            console.warn('[Storage] OPFS delete failed:', e);
        }
    }
}

/**
 * Store binary data (for database file)
 * @param {string} key - Storage key
 * @param {ArrayBuffer|Uint8Array} data - Binary data
 */
export async function setBinaryItem(key, data) {
    const fullKey = getArchiveDataKey(key);

    if (currentMode === StorageMode.OPFS) {
        try {
            const root = await getOPFSRoot();
            const fileHandle = await root.getFileHandle(fullKey, { create: true });
            const writable = await fileHandle.createWritable();
            await writable.write(data);
            await writable.close();
            console.log('[Storage] Binary data written to OPFS:', fullKey);
            return true;
        } catch (e) {
            console.error('[Storage] OPFS binary write failed:', e);
            return false;
        }
    }

    // For non-OPFS modes, we can't efficiently store binary data
    // Log warning and return false
    console.warn('[Storage] Binary storage only supported in OPFS mode');
    return false;
}

/**
 * Get binary data
 * @param {string} key - Storage key
 */
export async function getBinaryItem(key) {
    const fullKey = getArchiveDataKey(key);

    if (currentMode === StorageMode.OPFS) {
        try {
            const root = await getOPFSRoot();
            const fileHandle = await root.getFileHandle(fullKey);
            const file = await fileHandle.getFile();
            return await file.arrayBuffer();
        } catch (e) {
            if (e.name !== 'NotFoundError') {
                console.warn('[Storage] OPFS binary read failed:', e);
            }
            return null;
        }
    }

    return null;
}

/**
 * Migrate data between storage modes
 */
async function migrateStorage(fromMode, toMode) {
    console.log('[Storage] Migrating from', fromMode, 'to', toMode);

    // Get all keys from source
    const archiveDataPrefix = getArchiveDataPrefix();
    const keys = [];
    const values = new Map();

    switch (fromMode) {
        case StorageMode.MEMORY:
            for (const [key, value] of memoryStore) {
                if (key.startsWith(archiveDataPrefix)) {
                    keys.push(key);
                    values.set(key, value);
                }
            }
            break;

        case StorageMode.SESSION:
            {
                const storage = tryGetSessionStorage();
                if (!storage) {
                    break;
                }
                for (let i = 0; i < storage.length; i++) {
                    const key = storage.key(i);
                    if (key && key.startsWith(archiveDataPrefix)) {
                        keys.push(key);
                        values.set(key, storage.getItem(key));
                    }
                }
            }
            break;

        case StorageMode.LOCAL:
            {
                const storage = tryGetLocalStorage();
                if (!storage) {
                    break;
                }
                for (let i = 0; i < storage.length; i++) {
                    const key = storage.key(i);
                    if (key && key.startsWith(archiveDataPrefix)) {
                        keys.push(key);
                        values.set(key, storage.getItem(key));
                    }
                }
            }
            break;

        case StorageMode.OPFS:
            // OPFS data lives behind async file handles; migrating it into the
            // synchronous/local branches would require an async UX path with
            // explicit progress/error handling. Until that exists, leave the
            // data in OPFS and warn instead of silently pretending migration ran.
            console.warn('[Storage] OPFS→other migration not yet supported; data remains in OPFS');
            return;
    }

    // Write to destination
    const oldMode = currentMode;
    currentMode = toMode;

    for (const key of keys) {
        const shortKey = key.slice(archiveDataPrefix.length);
        const value = values.get(key);
        if (value) {
            try {
                await setItem(shortKey, JSON.parse(value));
            } catch (e) {
                await setItem(shortKey, value);
            }
        }
    }

    currentMode = oldMode;
    console.log('[Storage] Migrated', keys.length, 'items');
}

function removeMapEntriesWithPrefix(map, prefix) {
    for (const key of [...map.keys()]) {
        if (key.startsWith(prefix)) {
            map.delete(key);
        }
    }
}

function removeStorageEntriesWithPrefix(storage, prefix) {
    const keys = [];
    for (let i = 0; i < storage.length; i++) {
        const key = storage.key(i);
        if (key && key.startsWith(prefix)) {
            keys.push(key);
        }
    }
    keys.forEach((key) => storage.removeItem(key));
}

function removeStorageEntries(storage, predicate) {
    const keys = [];
    for (let i = 0; i < storage.length; i++) {
        const key = storage.key(i);
        if (key && predicate(key)) {
            keys.push(key);
        }
    }
    keys.forEach((key) => storage.removeItem(key));
}

function clearCurrentArchivePreferenceKeys(options = {}) {
    const { includeLegacy = false } = options;

    try {
        localStorage.removeItem(KEYS.MODE);
        localStorage.removeItem(KEYS.OPFS_ENABLED);
        localStorage.removeItem(KEYS.LAST_UNLOCK);
        localStorage.removeItem(KEYS.DB_CACHED);
        if (includeLegacy) {
            Object.values(LEGACY_PREF_KEYS).forEach((key) => localStorage.removeItem(key));
        }
    } catch (e) {
        // Ignore
    }
}

function clearCurrentArchiveSessionState(currentSessionKeys, currentTofuKey) {
    const sessionStorageBackend = tryGetSessionStorage();
    if (sessionStorageBackend) {
        removeStorageEntries(sessionStorageBackend, (key) => currentSessionKeys.has(key));
    }

    const localStorageBackend = tryGetLocalStorage();
    if (localStorageBackend) {
        removeStorageEntries(localStorageBackend, (key) => (
            currentSessionKeys.has(key)
            || key === currentTofuKey
        ));
    }
}

/**
 * Clear all cass storage in current mode
 */
export async function clearCurrentStorage() {
    console.log('[Storage] Clearing current storage:', currentMode);
    const archiveDataPrefix = getArchiveDataPrefix();
    const currentSessionKeys = getCurrentArchiveSessionKeys();
    const currentTofuKey = getCurrentArchiveTofuKey();
    let cleared = true;

    // Writes in session/local modes can fall back to memoryStore if the browser
    // rejects storage access. Clear that archive-scoped fallback copy too.
    removeMapEntriesWithPrefix(memoryStore, archiveDataPrefix);
    clearCurrentArchiveSessionState(currentSessionKeys, currentTofuKey);

    switch (currentMode) {
        case StorageMode.MEMORY:
            break;

        case StorageMode.SESSION:
            {
                const storage = tryGetSessionStorage();
                if (storage) {
                    removeStorageEntries(storage, (key) => key.startsWith(archiveDataPrefix));
                }
            }
            break;

        case StorageMode.LOCAL:
            {
                const storage = tryGetLocalStorage();
                if (storage) {
                    removeStorageEntries(storage, (key) => key.startsWith(archiveDataPrefix));
                }
            }
            break;

        case StorageMode.OPFS:
            cleared = await clearOPFS();
            break;
    }

    return cleared;
}

/**
 * Clear OPFS storage
 */
export async function clearOPFS(options = {}) {
    const { allArchives = false } = options;

    if (!isOPFSAvailable()) {
        return true;
    }

    try {
        let cleared = true;
        const root = await navigator.storage.getDirectory();
        const currentArchiveDbFiles = new Set(getArchiveOpfsDbFiles());
        const archiveDataPrefix = getArchiveDataPrefix();

        // Iterate and delete all entries
        const entries = [];
        for await (const entry of root.keys()) {
            const shouldDeleteData = allArchives
                ? isArchiveDataEntryName(entry)
                : entry.startsWith(archiveDataPrefix);
            const shouldDeleteDb = allArchives
                ? isCassOpfsDbFile(entry)
                : currentArchiveDbFiles.has(entry) || LEGACY_OPFS_DB_FILES.includes(entry);
            if (shouldDeleteData || shouldDeleteDb) {
                entries.push(entry);
            }
        }

        for (const entry of entries) {
            try {
                await root.removeEntry(entry);
            } catch (e) {
                console.warn('[Storage] Failed to delete OPFS entry:', entry, e);
                cleared = false;
            }
        }

        console.log('[Storage] OPFS cleared:', entries.length, 'entries');
        return cleared;
    } catch (e) {
        console.error('[Storage] OPFS clear failed:', e);
        return false;
    }
}

/**
 * Clear all cass storage across all modes
 */
export async function clearAllStorage(options = {}) {
    const { allArchives = false } = options;

    console.log('[Storage] Clearing all storage');
    const archiveDataPrefix = getArchiveDataPrefix();
    const currentSessionKeys = getCurrentArchiveSessionKeys();
    const currentTofuKey = getCurrentArchiveTofuKey();

    // Clear memory
    if (allArchives) {
        removeMapEntriesWithPrefix(memoryStore, STORAGE_PREFIX);
    } else {
        removeMapEntriesWithPrefix(memoryStore, archiveDataPrefix);
    }

    // Clear sessionStorage
    try {
        if (allArchives) {
            removeStorageEntries(sessionStorage, (key) =>
                key.startsWith(STORAGE_PREFIX) || isArchiveSessionKey(key)
            );
        } else {
            removeStorageEntries(sessionStorage, (key) =>
                key.startsWith(archiveDataPrefix) || currentSessionKeys.has(key)
            );
        }
    } catch (e) {
        // Ignore
    }

    // Clear localStorage
    try {
        if (allArchives) {
            removeStorageEntries(localStorage, (key) =>
                key.startsWith(STORAGE_PREFIX)
                && (isArchiveDataEntryName(key) || isArchivePreferenceKey(key) || Object.values(LEGACY_PREF_KEYS).includes(key))
                || isArchiveSessionKey(key)
                || isArchiveTofuKey(key)
            );
        } else {
            removeStorageEntries(localStorage, (key) =>
                key.startsWith(archiveDataPrefix)
                || currentSessionKeys.has(key)
                || key === currentTofuKey
            );
            clearCurrentArchivePreferenceKeys({ includeLegacy: true });
        }
    } catch (e) {
        // Ignore
    }

    // Clear OPFS
    const opfsCleared = await clearOPFS({ allArchives });

    console.log('[Storage] All storage cleared');
    return opfsCleared;
}

/**
 * Clear Service Worker cache
 */
export async function clearServiceWorkerCache(options = {}) {
    const { allArchives = false } = options;

    if (!('caches' in window)) {
        console.log('[Storage] Cache API not available');
        return true;
    }

    try {
        const cacheNames = await caches.keys();
        const cachePrefix = getServiceWorkerCachePrefix();
        const cassNames = cacheNames.filter(
            (name) => allArchives
                ? name.startsWith('cass-archive-')
                : name.startsWith(cachePrefix)
        );

        const deleteResults = await Promise.all(cassNames.map((name) => caches.delete(name)));
        const cleared = deleteResults.every(Boolean);
        if (cleared) {
            console.log('[Storage] Service Worker caches cleared:', cassNames);
        } else {
            console.warn('[Storage] Some Service Worker caches could not be cleared:', cassNames);
        }
        return cleared;
    } catch (e) {
        console.error('[Storage] Failed to clear SW cache:', e);
        return false;
    }
}

/**
 * Unregister Service Worker
 */
export async function unregisterServiceWorker(options = {}) {
    const { allArchives = false } = options;

    if (!('serviceWorker' in navigator)) {
        return true;
    }

    try {
        const registrations = await navigator.serviceWorker.getRegistrations();
        const currentScope = getArchiveScopeUrl();
        const targets = registrations.filter((reg) => allArchives || reg.scope === currentScope);
        const unregisterResults = await Promise.all(targets.map((reg) => reg.unregister()));
        const unregistered = unregisterResults.every(Boolean);
        if (unregistered) {
            console.log('[Storage] Service Workers unregistered');
        } else {
            console.warn('[Storage] Some Service Workers could not be unregistered');
        }
        return unregistered;
    } catch (e) {
        console.error('[Storage] Failed to unregister SW:', e);
        return false;
    }
}

/**
 * Get storage usage statistics
 */
export async function getStorageStats() {
    const stats = {
        mode: currentMode,
        memory: {
            items: 0,
            bytes: 0,
        },
        session: {
            items: 0,
            bytes: 0,
        },
        local: {
            items: 0,
            bytes: 0,
        },
        opfs: {
            items: 0,
            bytes: 0,
            dbBytes: 0,
            dbFiles: [],
            available: isOPFSAvailable(),
        },
        quota: null,
    };

    const archiveDataPrefix = getArchiveDataPrefix();
    const currentArchiveDbFiles = new Set(getArchiveOpfsDbFiles());

    // Count memory items
    for (const [key, value] of memoryStore) {
        if (key.startsWith(archiveDataPrefix)) {
            stats.memory.items++;
            stats.memory.bytes += key.length + (value?.length || 0);
        }
    }

    // Count sessionStorage
    try {
        for (let i = 0; i < sessionStorage.length; i++) {
            const key = sessionStorage.key(i);
            if (key && key.startsWith(archiveDataPrefix)) {
                stats.session.items++;
                const value = sessionStorage.getItem(key);
                stats.session.bytes += key.length + (value?.length || 0);
            }
        }
    } catch (e) {
        // Ignore
    }

    // Count localStorage
    try {
        for (let i = 0; i < localStorage.length; i++) {
            const key = localStorage.key(i);
            if (key && key.startsWith(archiveDataPrefix)) {
                stats.local.items++;
                const value = localStorage.getItem(key);
                stats.local.bytes += key.length + (value?.length || 0);
            }
        }
    } catch (e) {
        // Ignore
    }

    // Count OPFS
    if (isOPFSAvailable()) {
        try {
            const root = await navigator.storage.getDirectory();
            for await (const name of root.keys()) {
                if (name.startsWith(archiveDataPrefix) || currentArchiveDbFiles.has(name)) {
                    stats.opfs.items++;
                    try {
                        const handle = await root.getFileHandle(name);
                        const file = await handle.getFile();
                        stats.opfs.bytes += file.size;
                        if (currentArchiveDbFiles.has(name)) {
                            stats.opfs.dbBytes += file.size;
                            stats.opfs.dbFiles.push(name);
                        }
                    } catch (e) {
                        // Ignore individual file errors
                    }
                }
            }
        } catch (e) {
            console.warn('[Storage] OPFS stats failed:', e);
        }
    }

    // Get quota estimate
    if ('storage' in navigator && 'estimate' in navigator.storage) {
        try {
            stats.quota = await navigator.storage.estimate();
        } catch (e) {
            // Ignore
        }
    }

    return stats;
}

/**
 * Check if database is cached in OPFS
 */
export async function isDatabaseCached() {
    try {
        const root = await getOPFSRoot();
        for (const name of getArchiveOpfsDbFiles()) {
            try {
                await root.getFileHandle(name);
                return true;
            } catch (e) {
                // Try next name
            }
        }
        return false;
    } catch (e) {
        return false;
    }
}

/**
 * Format bytes for display
 */
export function formatBytes(bytes) {
    const value = Number(bytes);
    if (!Number.isFinite(value) || value <= 0) return '0 B';

    const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
    const i = Math.min(
        Math.floor(Math.log(value) / Math.log(1024)),
        units.length - 1
    );
    const size = value / Math.pow(1024, i);

    return size.toFixed(i > 0 ? 1 : 0) + ' ' + units[i];
}

// Export storage keys for external use
export { KEYS as StorageKeys };

export default {
    StorageMode,
    StorageKeys: KEYS,
    initStorage,
    getStoredMode,
    getStorageMode,
    setStorageMode,
    isOPFSAvailable,
    isOpfsEnabled,
    setOpfsEnabled,
    getOPFSRoot,
    setItem,
    getItem,
    removeItem,
    setBinaryItem,
    getBinaryItem,
    clearCurrentStorage,
    clearOPFS,
    clearAllStorage,
    clearServiceWorkerCache,
    unregisterServiceWorker,
    getStorageStats,
    isDatabaseCached,
    formatBytes,
    getArchiveScopeUrl,
    getArchiveScopeId,
    getArchiveOpfsDbFiles,
    getArchiveOpfsPrimaryDbName,
};