File size: 23,156 Bytes
ef6e870
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * Migration Service - Unified data migration hook
 *
 * Centralizes all data migrations (localStorage, IndexedDB, legacy formats) into a single
 * initialization point. Each migration copies data to new format WITHOUT deleting the old.
 *
 * **Architecture:**
 * - Migrations are defined as objects with `id` and `run()` methods
 * - Migration state is tracked in localStorage to avoid re-running
 * - `runAllMigrations()` should be called once at app startup
 * - All migrations are NON-DESTRUCTIVE - legacy data is preserved for downgrade compatibility
 *
 * **Current Migrations:**
 * 1. localStorage prefix: Copy LlamaCppWebui.* → LlamaUi.* (both preserved)
 * 2. IndexedDB database: Copy LlamacppWebui → LlamaUi (both preserved)
 * 3. Legacy message format: Transform in-place (preserves structure, migrates markers)
 * 4. Theme key: Copy standalone `theme` → config object (both preserved)
 */

import Dexie from 'dexie';
import {
	STORAGE_APP_NAME,
	STORAGE_APP_NAME_DEPRECATED,
	DB_APP_NAME_DEPRECATED,
	CONFIG_LOCALSTORAGE_KEY,
	IDXDB_TABLES,
	IDXDB_STORES,
	NEW_TO_DEPRECATED_MAP
} from '$lib/constants';
import { LEGACY_AGENTIC_REGEX, LEGACY_REASONING_TAGS } from '$lib/constants/agentic';
import { SETTINGS_KEYS } from '$lib/constants/settings-registry';
import { MessageRole } from '$lib/enums';

// Types

interface Migration {
	/** Unique identifier for this migration */
	id: string;
	/** Human-readable description */
	description: string;
	/** Run the migration forward (non-destructive - copies, doesn't delete) */
	run(): Promise<void>;
}

interface MigrationState {
	completed: string[];
	failed: string[];
	lastRun: string;
}

// Constants

const MIGRATION_STATE_KEY = `${STORAGE_APP_NAME}.migration-state`;
const MIGRATION_STATE_VERSION = 1;

// State Management

function getMigrationState(): MigrationState {
	try {
		const raw = localStorage.getItem(MIGRATION_STATE_KEY);
		if (!raw) return { completed: [], failed: [], lastRun: '' };
		const parsed = JSON.parse(raw);
		if (parsed.version !== MIGRATION_STATE_VERSION) {
			return { completed: [], failed: [], lastRun: '' };
		}
		return {
			completed: parsed.completed ?? [],
			failed: parsed.failed ?? [],
			lastRun: parsed.lastRun ?? ''
		};
	} catch {
		return { completed: [], failed: [], lastRun: '' };
	}
}

function saveMigrationState(state: MigrationState): void {
	localStorage.setItem(
		MIGRATION_STATE_KEY,
		JSON.stringify({
			version: MIGRATION_STATE_VERSION,
			...state,
			lastRun: new Date().toISOString()
		})
	);
}

function isMigrationCompleted(id: string): boolean {
	const state = getMigrationState();
	return state.completed.includes(id);
}

function markMigrationCompleted(id: string): void {
	const state = getMigrationState();
	if (!state.completed.includes(id)) {
		state.completed.push(id);
	}
	state.failed = state.failed.filter((f) => f !== id);
	saveMigrationState(state);
}

function markMigrationFailed(id: string): void {
	const state = getMigrationState();
	if (!state.failed.includes(id)) {
		state.failed.push(id);
	}
	saveMigrationState(state);
}

// Migration 1: LocalStorage Key Prefix (Non-Destructive)

const LOCALSTORAGE_MIGRATION_ID = 'localstorage-prefix-v1';

const localStorageMigration: Migration = {
	id: LOCALSTORAGE_MIGRATION_ID,
	description: 'Copy localStorage keys from LlamaCppWebui to LlamaUi prefix (non-destructive)',

	async run(): Promise<void> {
		// Non-destructive: copy to new key, but KEEP the old key
		for (const [newKey, deprecatedKey] of Object.entries(NEW_TO_DEPRECATED_MAP)) {
			// Only migrate if new key doesn't already exist
			const newValue = localStorage.getItem(newKey);
			if (newValue !== null) {
				if (import.meta.env.DEV && import.meta.env.VITE_DEBUG)
					console.log(`[Migration] localStorage: ${newKey} already exists, skipping`);
				continue;
			}

			const oldValue = localStorage.getItem(deprecatedKey);
			if (oldValue !== null) {
				localStorage.setItem(newKey, oldValue);
				// Keep old key for downgrade compatibility - DO NOT DELETE
				if (import.meta.env.DEV && import.meta.env.VITE_DEBUG) {
					console.log(
						`[Migration] localStorage: copied ${deprecatedKey}${newKey} (preserved old)`
					);
				}
			}
		}
	}
};

// Migration 2: IndexedDB Database Name (Non-Destructive)

const IDXDB_MIGRATION_ID = 'idxdb-database-v1';

const idxdbMigration: Migration = {
	id: IDXDB_MIGRATION_ID,
	description: 'Copy IndexedDB from LlamacppWebui to LlamaUi database (non-destructive)',

	async run(): Promise<void> {
		const oldDbNames = await Dexie.getDatabaseNames();
		if (!oldDbNames.includes(DB_APP_NAME_DEPRECATED)) {
			if (import.meta.env.DEV && import.meta.env.VITE_DEBUG)
				console.log('[Migration] IndexedDB: no old database found, skipping');
			return;
		}

		// Check if new database already has data
		const newDb = new Dexie(STORAGE_APP_NAME);
		newDb.version(1).stores(IDXDB_STORES);
		const existingConvs = await newDb.table(IDXDB_TABLES.conversations).count();
		if (existingConvs > 0) {
			if (import.meta.env.DEV && import.meta.env.VITE_DEBUG)
				console.log('[Migration] IndexedDB: new database already has data, skipping');
			return;
		}

		if (import.meta.env.DEV && import.meta.env.VITE_DEBUG)
			console.log('[Migration] IndexedDB: copying from', DB_APP_NAME_DEPRECATED);

		const oldDb = new Dexie(DB_APP_NAME_DEPRECATED);
		oldDb.version(1).stores(IDXDB_STORES);

		const conversations = await oldDb.table(IDXDB_TABLES.conversations).toArray();
		const messages = await oldDb.table(IDXDB_TABLES.messages).toArray();

		if (conversations.length > 0) {
			await newDb.table(IDXDB_TABLES.conversations).bulkAdd(conversations);
			if (import.meta.env.DEV && import.meta.env.VITE_DEBUG)
				console.log(`[Migration] IndexedDB: copied ${conversations.length} conversations`);
		}
		if (messages.length > 0) {
			await newDb.table(IDXDB_TABLES.messages).bulkAdd(messages);
			if (import.meta.env.DEV && import.meta.env.VITE_DEBUG)
				console.log(`[Migration] IndexedDB: copied ${messages.length} messages`);
		}

		// Non-destructive: DO NOT delete old database - keep for downgrade compatibility
		if (import.meta.env.DEV && import.meta.env.VITE_DEBUG)
			console.log('[Migration] IndexedDB: preserved old database for downgrade compatibility');
	}
};

// Migration 3: Legacy Message Format

const LEGACY_MESSAGE_MIGRATION_ID = 'legacy-message-format-v2';

interface ParsedTurn {
	textBefore: string;
	toolCalls: Array<{ name: string; args: string; result: string }>;
}

function parseLegacyToolCalls(content: string): ParsedTurn[] {
	const turns: ParsedTurn[] = [];
	const regex = new RegExp(LEGACY_AGENTIC_REGEX.COMPLETED_TOOL_CALL.source, 'g');

	let lastIndex = 0;
	let currentTurn: ParsedTurn = { textBefore: '', toolCalls: [] };
	let match;

	while ((match = regex.exec(content)) !== null) {
		const textBefore = content.slice(lastIndex, match.index).trim();

		if (textBefore && currentTurn.toolCalls.length > 0) {
			turns.push(currentTurn);
			currentTurn = { textBefore, toolCalls: [] };
		} else if (textBefore && currentTurn.toolCalls.length === 0) {
			currentTurn.textBefore = textBefore;
		}

		currentTurn.toolCalls.push({
			name: match[1],
			args: match[2],
			result: match[3].replace(/^\n+|\n+$/g, '')
		});

		lastIndex = match.index + match[0].length;
	}

	const remainingText = content.slice(lastIndex).trim();

	if (currentTurn.toolCalls.length > 0) {
		turns.push(currentTurn);
	}

	if (remainingText) {
		const cleanRemaining = remainingText
			.replace(LEGACY_AGENTIC_REGEX.AGENTIC_TOOL_CALL_OPEN, '')
			.trim();
		if (cleanRemaining) {
			turns.push({ textBefore: cleanRemaining, toolCalls: [] });
		}
	}

	if (turns.length === 0) {
		turns.push({ textBefore: content.trim(), toolCalls: [] });
	}

	return turns;
}

function extractLegacyReasoning(content: string): { reasoning: string; cleanContent: string } {
	let reasoning = '';
	let cleanContent = content;

	const re = new RegExp(LEGACY_AGENTIC_REGEX.REASONING_EXTRACT.source, 'g');
	let match;
	while ((match = re.exec(content)) !== null) {
		reasoning += match[1];
	}

	cleanContent = cleanContent
		.replace(new RegExp(LEGACY_AGENTIC_REGEX.REASONING_BLOCK.source, 'g'), '')
		.replace(LEGACY_AGENTIC_REGEX.REASONING_OPEN, '');

	return { reasoning, cleanContent };
}

function hasLegacyMarkers(content: string): boolean {
	return LEGACY_AGENTIC_REGEX.HAS_LEGACY_MARKERS.test(content);
}

let DatabaseService: typeof import('./database.service').DatabaseService | null = null;

async function getDatabaseService() {
	if (!DatabaseService) {
		const module = await import('./database.service');
		DatabaseService = module.DatabaseService;
	}
	return DatabaseService;
}

const legacyMessageMigration: Migration = {
	id: LEGACY_MESSAGE_MIGRATION_ID,
	description: 'Migrate legacy marker-based messages to structured format',

	async run(): Promise<void> {
		const db = await getDatabaseService();
		const conversations = await db.getAllConversations();
		let migratedCount = 0;

		for (const conv of conversations) {
			const allMessages = await db.getConversationMessages(conv.id);

			for (const message of allMessages) {
				if (message.role !== MessageRole.ASSISTANT) {
					if (message.content?.includes(LEGACY_REASONING_TAGS.START)) {
						const { reasoning, cleanContent } = extractLegacyReasoning(message.content);
						await db.updateMessage(message.id, {
							content: cleanContent.trim(),
							reasoningContent: reasoning || undefined
						});
						migratedCount++;
					}
					continue;
				}

				if (!hasLegacyMarkers(message.content ?? '')) continue;

				const { reasoning, cleanContent } = extractLegacyReasoning(message.content);
				const turns = parseLegacyToolCalls(cleanContent);

				let existingToolCalls: Array<{
					id: string;
					function?: { name: string; arguments: string };
				}> = [];
				if (message.toolCalls) {
					try {
						existingToolCalls = JSON.parse(message.toolCalls);
					} catch {
						// Ignore
					}
				}

				const firstTurn = turns[0];
				if (!firstTurn) continue;

				const firstTurnToolCalls = firstTurn.toolCalls.map((tc, i) => {
					const existing =
						existingToolCalls.find((e) => e.function?.name === tc.name) || existingToolCalls[i];
					return {
						id: existing?.id || `legacy_tool_${i}`,
						type: 'function' as const,
						function: { name: tc.name, arguments: tc.args }
					};
				});

				await db.updateMessage(message.id, {
					content: firstTurn.textBefore,
					reasoningContent: reasoning || undefined,
					toolCalls: firstTurnToolCalls.length > 0 ? JSON.stringify(firstTurnToolCalls) : ''
				});

				let currentParentId = message.id;
				let toolCallIdCounter = existingToolCalls.length;

				for (let i = 0; i < firstTurn.toolCalls.length; i++) {
					const tc = firstTurn.toolCalls[i];
					const toolCallId = firstTurnToolCalls[i]?.id || `legacy_tool_${i}`;

					const toolMsg = await db.createMessageBranch(
						{
							convId: conv.id,
							type: 'text',
							role: MessageRole.TOOL,
							content: tc.result,
							toolCallId,
							timestamp: message.timestamp + i + 1,
							toolCalls: '',
							children: []
						},
						currentParentId
					);
					currentParentId = toolMsg.id;
				}

				for (let turnIdx = 1; turnIdx < turns.length; turnIdx++) {
					const turn = turns[turnIdx];

					const turnToolCalls = turn.toolCalls.map((tc, i) => {
						const idx = toolCallIdCounter + i;
						const existing = existingToolCalls[idx];
						return {
							id: existing?.id || `legacy_tool_${idx}`,
							type: 'function' as const,
							function: { name: tc.name, arguments: tc.args }
						};
					});
					toolCallIdCounter += turn.toolCalls.length;

					const assistantMsg = await db.createMessageBranch(
						{
							convId: conv.id,
							type: 'text',
							role: MessageRole.ASSISTANT,
							content: turn.textBefore,
							timestamp: message.timestamp + turnIdx * 100,
							toolCalls: turnToolCalls.length > 0 ? JSON.stringify(turnToolCalls) : '',
							children: [],
							model: message.model
						},
						currentParentId
					);
					currentParentId = assistantMsg.id;

					for (let i = 0; i < turn.toolCalls.length; i++) {
						const tc = turn.toolCalls[i];
						const toolCallId = turnToolCalls[i]?.id || `legacy_tool_${toolCallIdCounter + i}`;

						const toolMsg = await db.createMessageBranch(
							{
								convId: conv.id,
								type: 'text',
								role: MessageRole.TOOL,
								content: tc.result,
								toolCallId,
								timestamp: message.timestamp + turnIdx * 100 + i + 1,
								toolCalls: '',
								children: []
							},
							currentParentId
						);
						currentParentId = toolMsg.id;
					}
				}

				if (message.children.length > 0 && currentParentId !== message.id) {
					for (const childId of message.children) {
						const child = allMessages.find((m) => m.id === childId);
						if (!child) continue;
						if (child.role !== MessageRole.TOOL) {
							await db.updateMessage(childId, { parent: currentParentId });
						}
					}
					await db.updateMessage(message.id, { children: [] });
				}

				migratedCount++;
			}
		}

		if (import.meta.env.DEV && import.meta.env.VITE_DEBUG)
			console.log(`[Migration] Legacy messages: migrated ${migratedCount} messages`);
	}
};

// Migration 4: Theme Key (Non-Destructive)

const THEME_MIGRATION_ID = 'theme-key-v1';

const themeMigration: Migration = {
	id: THEME_MIGRATION_ID,
	description: 'Copy standalone theme key to config object (non-destructive)',

	async run(): Promise<void> {
		const legacyTheme = localStorage.getItem('theme');
		if (legacyTheme === null) {
			if (import.meta.env.DEV && import.meta.env.VITE_DEBUG)
				console.log('[Migration] Theme: no legacy theme key found, skipping');
			return;
		}

		// Check if config already has theme
		const configRaw = localStorage.getItem(CONFIG_LOCALSTORAGE_KEY);
		const config = configRaw ? JSON.parse(configRaw) : {};

		if (SETTINGS_KEYS.THEME in config) {
			if (import.meta.env.DEV && import.meta.env.VITE_DEBUG)
				console.log('[Migration] Theme: config already has theme, skipping');
			return;
		}

		config[SETTINGS_KEYS.THEME] = legacyTheme;
		localStorage.setItem(CONFIG_LOCALSTORAGE_KEY, JSON.stringify(config));

		// Non-destructive: DO NOT delete legacy theme key - keep for downgrade compatibility
		if (import.meta.env.DEV && import.meta.env.VITE_DEBUG)
			console.log(`[Migration] Theme: copied standalone theme to config (preserved old key)`);
	}
};

// Migration Registry & Runner

const CUSTOM_JSON_MIGRATION_ID = 'custom-json-key-v1';

const customJsonKeyMigration: Migration = {
	id: CUSTOM_JSON_MIGRATION_ID,
	description: 'Copy legacy custom config key to customJson (non-destructive)',

	async run(): Promise<void> {
		const configRaw = localStorage.getItem(CONFIG_LOCALSTORAGE_KEY);
		if (configRaw === null) return;

		const config = JSON.parse(configRaw);

		if (!('custom' in config)) return;
		if (SETTINGS_KEYS.CUSTOM_JSON in config) return;

		config[SETTINGS_KEYS.CUSTOM_JSON] = config.custom;
		localStorage.setItem(CONFIG_LOCALSTORAGE_KEY, JSON.stringify(config));

		// Non-destructive: keep the legacy custom key for downgrade compatibility
		if (import.meta.env.DEV && import.meta.env.VITE_DEBUG)
			console.log(`[Migration] Custom JSON: copied custom to customJson (preserved old key)`);
	}
};

const MCP_DEFAULT_ENABLED_MIGRATION_ID = 'mcp-default-enabled-to-config-v1';

const LEGACY_MCP_DEFAULT_ENABLED_KEY = `${STORAGE_APP_NAME}.mcpDefaultEnabled`;
const DEPRECATED_LEGACY_MCP_DEFAULT_ENABLED_KEY = `${STORAGE_APP_NAME_DEPRECATED}.mcpDefaultEnabled`;

const mcpDefaultEnabledMigration: Migration = {
	id: MCP_DEFAULT_ENABLED_MIGRATION_ID,
	description:
		'Copy mcpDefaultEnabled localStorage key into settings config (preserves legacy keys)',

	async run(): Promise<void> {
		const raw =
			localStorage.getItem(LEGACY_MCP_DEFAULT_ENABLED_KEY) ??
			localStorage.getItem(DEPRECATED_LEGACY_MCP_DEFAULT_ENABLED_KEY);

		// Legacy keys intentionally left in place so a downgrade keeps reading them.

		if (raw === null) {
			if (import.meta.env.DEV && import.meta.env.VITE_DEBUG)
				console.log('[Migration] MCP default enabled: no legacy key found, skipping');
			return;
		}

		const configRaw = localStorage.getItem(CONFIG_LOCALSTORAGE_KEY);
		const config = configRaw ? JSON.parse(configRaw) : {};

		// Don't overwrite an existing config entry — current data wins.
		if (MCP_DEFAULT_OVERRIDES_LEGACY_KEY in config) {
			if (import.meta.env.DEV && import.meta.env.VITE_DEBUG)
				console.log('[Migration] MCP default enabled: config already has overrides, skipping');
			return;
		}

		try {
			const parsed = JSON.parse(raw);
			if (!Array.isArray(parsed)) return;
			const valid = parsed.every(
				(o) =>
					typeof o === 'object' &&
					o !== null &&
					typeof (o as Record<string, unknown>).serverId === 'string' &&
					typeof (o as Record<string, unknown>).enabled === 'boolean'
			);
			if (!valid) return;
		} catch {
			return;
		}

		config[MCP_DEFAULT_OVERRIDES_LEGACY_KEY] = raw;
		localStorage.setItem(CONFIG_LOCALSTORAGE_KEY, JSON.stringify(config));

		if (import.meta.env.DEV && import.meta.env.VITE_DEBUG)
			console.log('[Migration] MCP default enabled: moved legacy key into config');
	}
};

const CONFIG_TYPES_MIGRATION_ID = 'config-type-normalization-v1';

const configTypesMigration: Migration = {
	id: CONFIG_TYPES_MIGRATION_ID,
	description: 'Coerce legacy string-encoded booleans in persisted config to real booleans',

	async run(): Promise<void> {
		const configRaw = localStorage.getItem(CONFIG_LOCALSTORAGE_KEY);
		if (configRaw === null) return;

		const config = JSON.parse(configRaw);
		let changed = false;

		// Pre-schema configs persisted booleans as "true"/"false" strings; the strict server
		// schema rejects them. No config string field holds exactly "true"/"false", so the
		// match is unambiguous.
		for (const key of Object.keys(config)) {
			if (config[key] === 'true') {
				config[key] = true;
				changed = true;
			} else if (config[key] === 'false') {
				config[key] = false;
				changed = true;
			}
		}

		if (changed) {
			localStorage.setItem(CONFIG_LOCALSTORAGE_KEY, JSON.stringify(config));
		}

		if (import.meta.env.DEV && import.meta.env.VITE_DEBUG)
			console.log(`[Migration] Config types: coerced string booleans (changed=${changed})`);
	}
};

const MCP_DEFAULT_OVERRIDES_LEGACY_KEY = `${STORAGE_APP_NAME}.mcpDefaultServerOverrides`;
const MCP_DEFAULT_OVERRIDES_MERGE_MIGRATION_ID = 'mcp-default-overrides-merge-v1';

/**
 * Folds `mcpDefaultServerOverrides` (the legacy "default for new chats" list,
 * JSON-encoded as `[{ serverId, enabled }, ...]`) into `mcpServers[i].enabled`.
 * The legacy override key is intentionally left in the config so a downgrade
 * keeps reading it. Runs after `mcpDefaultEnabledMigration` so any legacy
 * standalone overrides are already inside the config.
 */
const mcpDefaultOverridesMergeMigration: Migration = {
	id: MCP_DEFAULT_OVERRIDES_MERGE_MIGRATION_ID,
	description:
		'Merge mcpDefaultServerOverrides entries onto mcpServers[i].enabled (preserves legacy key)',

	async run(): Promise<void> {
		const configRaw = localStorage.getItem(CONFIG_LOCALSTORAGE_KEY);
		if (configRaw === null) return;

		const config = JSON.parse(configRaw);
		const raw = config[MCP_DEFAULT_OVERRIDES_LEGACY_KEY];

		if (typeof raw !== 'string' || raw.length === 0) {
			if (import.meta.env.DEV && import.meta.env.VITE_DEBUG)
				console.log('[Migration] MCP default overrides merge: nothing to merge');
			return;
		}

		let overrides: { serverId: string; enabled: boolean }[];
		try {
			const parsed = JSON.parse(raw);
			if (!Array.isArray(parsed)) return;
			overrides = parsed.filter(
				(o) =>
					typeof o === 'object' &&
					o !== null &&
					typeof (o as Record<string, unknown>).serverId === 'string' &&
					typeof (o as Record<string, unknown>).enabled === 'boolean'
			) as { serverId: string; enabled: boolean }[];
		} catch {
			return;
		}

		const serversRaw = config[SETTINGS_KEYS.MCP_SERVERS];
		let servers: { id: string; enabled?: boolean }[];
		try {
			servers = typeof serversRaw === 'string' ? JSON.parse(serversRaw) : [];
		} catch {
			return;
		}

		if (!Array.isArray(servers)) servers = [];

		let serversChanged = false;
		const knownIds = new Set(servers.map((s) => s.id));
		for (const override of overrides) {
			if (!knownIds.has(override.serverId)) continue;
			const index = servers.findIndex((s) => s.id === override.serverId);

			if (index >= 0 && servers[index].enabled !== override.enabled) {
				servers[index] = { ...servers[index], enabled: override.enabled };
				serversChanged = true;
			}
		}

		if (serversChanged) {
			config[SETTINGS_KEYS.MCP_SERVERS] = JSON.stringify(servers);
			localStorage.setItem(CONFIG_LOCALSTORAGE_KEY, JSON.stringify(config));
		}

		if (import.meta.env.DEV && import.meta.env.VITE_DEBUG)
			console.log(
				`[Migration] MCP default overrides merge: applied=${overrides.length} serversChanged=${serversChanged} (legacy key preserved)`
			);
	}
};

const migrations: Migration[] = [
	localStorageMigration,
	idxdbMigration,
	legacyMessageMigration,
	themeMigration,
	customJsonKeyMigration,
	mcpDefaultEnabledMigration,
	mcpDefaultOverridesMergeMigration,
	configTypesMigration
];

export const MigrationService = {
	/**
	 * Get all registered migrations
	 */
	getMigrations(): Migration[] {
		return [...migrations];
	},

	/**
	 * Check if a specific migration has been completed
	 */
	isCompleted(id: string): boolean {
		return isMigrationCompleted(id);
	},

	/**
	 * Get current migration state
	 */
	getState(): MigrationState {
		return getMigrationState();
	},

	/**
	 * Reset migration state (use with caution - migrations will run again)
	 */
	resetState(): void {
		localStorage.removeItem(MIGRATION_STATE_KEY);
		if (import.meta.env.DEV && import.meta.env.VITE_DEBUG)
			console.log('[Migration] State reset - all migrations will run again');
	},

	/**
	 * Run all pending migrations (non-destructive - preserves legacy data)
	 * Should be called once at app initialization
	 */
	async runAllMigrations(): Promise<void> {
		const state = getMigrationState();
		if (import.meta.env.DEV && import.meta.env.VITE_DEBUG)
			console.log('[Migration] Starting migration run, state:', state);

		for (const migration of migrations) {
			if (isMigrationCompleted(migration.id)) {
				if (import.meta.env.DEV && import.meta.env.VITE_DEBUG)
					console.log(`[Migration] ${migration.id}: already completed, skipping`);
				continue;
			}

			try {
				if (import.meta.env.DEV && import.meta.env.VITE_DEBUG)
					console.log(`[Migration] ${migration.id}: running...`);
				await migration.run();
				markMigrationCompleted(migration.id);
				if (import.meta.env.DEV && import.meta.env.VITE_DEBUG)
					console.log(`[Migration] ${migration.id}: completed successfully`);
			} catch (error) {
				console.error(`[Migration] ${migration.id}: failed`, error);
				markMigrationFailed(migration.id);
			}
		}

		if (import.meta.env.DEV && import.meta.env.VITE_DEBUG)
			console.log('[Migration] All migrations complete');
	}
};