• Creates a complete backup of application data and triggers file download. Automatically adds entry to backup history and manages history limit. Large backups are exported asynchronously to avoid blocking the UI.

    Note: This function is intended for manual user-initiated backups that trigger browser downloads. For automatic backups before matching/sync operations that don't require user interaction, use globalThis.electronBackup.createNow() instead, which writes directly to the configured backup location.

    Returns Promise<string>

    Unique identifier for the created backup.

    If backup creation or export fails.

    export async function createBackup(): Promise<string> {
    try {
    console.log("[Backup] Creating backup...");

    // Collect all backupable data
    const { data: backupData, size: backupSize } = await collectBackupData();
    console.log(
    `[Backup] Backup size: ${(backupSize / 1024 / 1024).toFixed(2)} MB`,
    );

    // Generate backup ID
    const backupId = `backup_${Date.now()}`;

    // Export to JSON file asynchronously to avoid blocking UI for large payloads
    // Yield to the event loop before starting export
    await new Promise<void>((resolve, reject) => {
    setTimeout(async () => {
    try {
    await exportToJson(
    backupData as unknown as Record<string, unknown>,
    "backup",
    );
    resolve();
    } catch (error) {
    console.error("[Backup] Failed to export JSON:", error);
    reject(error);
    }
    }, 0);
    });

    // Add to backup history
    const historyEntry: BackupHistoryEntry = {
    id: backupId,
    timestamp: Date.now(),
    appVersion: backupData.metadata.appVersion,
    dataKeys: backupData.metadata.dataKeys,
    size: backupSize,
    };

    addBackupToHistory(historyEntry);

    console.log("[Backup] Backup created successfully:", backupId);
    return backupId;
    } catch (error) {
    console.error("[Backup] Failed to create backup:", error);
    throw new Error(
    `Failed to create backup: ${error instanceof Error ? error.message : "Unknown error"}`,
    );
    }
    }