// 数据迁移工具 - 从Chrome Storage迁移到IndexedDB
// 提供数据迁移、备份和恢复功能

class DataMigrationManager {
  constructor() {
    this.indexedDBManager = new IndexedDBManager();
  }

  // 检查迁移状态
  async checkMigrationStatus() {
    try {
      // 检查IndexedDB中是否有数据
      await this.indexedDBManager.init();
      const idbData = await this.indexedDBManager.getAllData();
      const hasIDBData = idbData.categories.length > 0 || idbData.links.length > 0;

      // 检查Chrome Storage中是否有数据
      let chromeData = null;
      let hasChromeData = false;
      
      if (typeof chrome !== 'undefined' && chrome.storage) {
        try {
          // 先检查sync storage
          const syncResult = await chrome.storage.sync.get(['categories', 'links', 'settings']);
          if (syncResult.categories?.length > 0 || syncResult.links?.length > 0) {
            chromeData = {
              type: 'sync',
              data: {
                categories: syncResult.categories || [],
                links: syncResult.links || [],
                settings: syncResult.settings || {}
              }
            };
            hasChromeData = true;
          } else {
            // 检查local storage
            const localResult = await chrome.storage.local.get(['categories', 'links', 'settings']);
            if (localResult.categories?.length > 0 || localResult.links?.length > 0) {
              chromeData = {
                type: 'local',
                data: {
                  categories: localResult.categories || [],
                  links: localResult.links || [],
                  settings: localResult.settings || {}
                }
              };
              hasChromeData = true;
            }
          }
        } catch (error) {
          console.warn('无法访问Chrome Storage:', error);
        }
      }

      return {
        hasIndexedDBData: hasIDBData,
        hasChromeStorageData: hasChromeData,
        chromeStorageType: chromeData?.type || null,
        needsMigration: hasChromeData && !hasIDBData,
        dataConflict: hasChromeData && hasIDBData,
        indexedDBDataCount: {
          categories: idbData.categories.length,
          links: idbData.links.length
        },
        chromeDataCount: chromeData ? {
          categories: chromeData.data.categories.length,
          links: chromeData.data.links.length
        } : null
      };
    } catch (error) {
      console.error('检查迁移状态失败:', error);
      return {
        hasIndexedDBData: false,
        hasChromeStorageData: false,
        error: error.message
      };
    }
  }

  // 从Chrome Storage迁移数据到IndexedDB
  async migrateFromChromeStorage(options = {}) {
    const {
      sourceType = 'auto', // 'auto', 'sync', 'local'
      clearSource = false,  // 是否清空源数据
      backupFirst = true   // 是否先备份
    } = options;

    try {
      console.log('🚀 开始数据迁移...');
      
      // 1. 检查迁移状态
      const status = await this.checkMigrationStatus();
      if (!status.hasChromeStorageData) {
        throw new Error('Chrome Storage中没有找到数据');
      }

      // 2. 确定数据源
      let sourceData;
      let actualSourceType;
      
      if (sourceType === 'auto') {
        // 自动选择：优先sync，然后local
        const syncData = await chrome.storage.sync.get(['categories', 'links', 'settings']);
        if (syncData.categories?.length > 0 || syncData.links?.length > 0) {
          sourceData = syncData;
          actualSourceType = 'sync';
        } else {
          const localData = await chrome.storage.local.get(['categories', 'links', 'settings']);
          sourceData = localData;
          actualSourceType = 'local';
        }
      } else {
        const storageAPI = sourceType === 'sync' ? chrome.storage.sync : chrome.storage.local;
        sourceData = await storageAPI.get(['categories', 'links', 'settings']);
        actualSourceType = sourceType;
      }

      console.log(`📊 从Chrome Storage ${actualSourceType}获取数据:`, {
        categories: sourceData.categories?.length || 0,
        links: sourceData.links?.length || 0,
        hasSettings: !!sourceData.settings
      });

      // 3. 数据备份（可选）
      let backupData = null;
      if (backupFirst) {
        backupData = await this.createBackup(sourceData, actualSourceType);
        console.log('💾 已创建数据备份');
      }

      // 4. 数据验证和清理
      const cleanedData = this.validateAndCleanData(sourceData);
      
      // 5. 导入到IndexedDB
      await this.indexedDBManager.init();
      await this.indexedDBManager.importData(cleanedData);
      
      console.log('✅ 数据导入IndexedDB成功');

      // 6. 验证迁移结果
      const migratedData = await this.indexedDBManager.getAllData();
      const verificationResult = this.verifyMigration(cleanedData, migratedData);
      
      if (!verificationResult.success) {
        throw new Error(`数据验证失败: ${verificationResult.errors.join(', ')}`);
      }

      // 7. 清空源数据（可选）
      if (clearSource) {
        const storageAPI = actualSourceType === 'sync' ? chrome.storage.sync : chrome.storage.local;
        await storageAPI.clear();
        console.log('🗑️ 已清空Chrome Storage源数据');
      }

      // 8. 记录迁移信息
      await this.recordMigration({
        sourceType: actualSourceType,
        timestamp: new Date().toISOString(),
        dataCount: {
          categories: cleanedData.categories.length,
          links: cleanedData.links.length
        },
        backupId: backupData?.id || null
      });

      return {
        success: true,
        sourceType: actualSourceType,
        migratedData: {
          categories: cleanedData.categories.length,
          links: cleanedData.links.length
        },
        backupId: backupData?.id || null
      };

    } catch (error) {
      console.error('❌ 数据迁移失败:', error);
      throw error;
    }
  }

  // 数据验证和清理
  validateAndCleanData(rawData) {
    const cleanedData = {
      categories: [],
      links: [],
      settings: rawData.settings || {
        theme: 'light',
        defaultView: 'grid',
        autoCapture: true
      }
    };

    // 清理分类数据
    if (rawData.categories && Array.isArray(rawData.categories)) {
      cleanedData.categories = rawData.categories.filter(cat => {
        return cat && cat.id && cat.name;
      }).map(cat => ({
        id: cat.id.toString(),
        name: cat.name,
        icon: cat.icon || '📁',
        color: cat.color || '#4285f4',
        description: cat.description || '',
        createdAt: cat.createdAt || new Date().toISOString(),
        linkCount: cat.linkCount || 0
      }));
    }

    // 清理链接数据
    if (rawData.links && Array.isArray(rawData.links)) {
      cleanedData.links = rawData.links.filter(link => {
        return link && link.id && link.url && link.title;
      }).map(link => ({
        id: link.id.toString(),
        url: link.url,
        title: link.title,
        logo: link.logo || this.generateLogo(link.title),
        category: link.category || '',
        categoryId: link.categoryId || '',
        note: link.note || '',
        isQuickAccess: Boolean(link.isQuickAccess),
        visitCount: parseInt(link.visitCount) || 0,
        createdAt: link.createdAt || new Date().toISOString(),
        lastVisited: link.lastVisited || null
      }));
    }

    return cleanedData;
  }

  // 验证迁移结果
  verifyMigration(sourceData, migratedData) {
    const errors = [];
    
    // 验证分类数量
    if (sourceData.categories.length !== migratedData.categories.length) {
      errors.push(`分类数量不匹配: 源${sourceData.categories.length}, 目标${migratedData.categories.length}`);
    }
    
    // 验证链接数量
    if (sourceData.links.length !== migratedData.links.length) {
      errors.push(`链接数量不匹配: 源${sourceData.links.length}, 目标${migratedData.links.length}`);
    }
    
    // 验证分类ID
    const sourceCategoryIds = new Set(sourceData.categories.map(c => c.id));
    const migratedCategoryIds = new Set(migratedData.categories.map(c => c.id));
    
    for (const id of sourceCategoryIds) {
      if (!migratedCategoryIds.has(id)) {
        errors.push(`缺少分类ID: ${id}`);
      }
    }
    
    // 验证链接ID
    const sourceLinkIds = new Set(sourceData.links.map(l => l.id));
    const migratedLinkIds = new Set(migratedData.links.map(l => l.id));
    
    for (const id of sourceLinkIds) {
      if (!migratedLinkIds.has(id)) {
        errors.push(`缺少链接ID: ${id}`);
      }
    }
    
    return {
      success: errors.length === 0,
      errors
    };
  }

  // 创建数据备份
  async createBackup(data, sourceType) {
    const backupId = `backup_${Date.now()}`;
    const backupData = {
      id: backupId,
      timestamp: new Date().toISOString(),
      sourceType,
      data: JSON.parse(JSON.stringify(data)) // 深拷贝
    };

    // 保存备份到IndexedDB的metadata存储
    await this.indexedDBManager.init();
    const store = await this.indexedDBManager.getStore('metadata', 'readwrite');
    
    return new Promise((resolve, reject) => {
      const request = store.put({
        key: `backup_${backupId}`,
        value: backupData,
        type: 'backup',
        createdAt: new Date().toISOString()
      });
      
      request.onsuccess = () => {
        resolve(backupData);
      };
      
      request.onerror = () => {
        reject(request.error);
      };
    });
  }

  // 记录迁移信息
  async recordMigration(migrationInfo) {
    await this.indexedDBManager.init();
    const store = await this.indexedDBManager.getStore('metadata', 'readwrite');
    
    return new Promise((resolve, reject) => {
      const request = store.put({
        key: 'migration_info',
        value: migrationInfo,
        type: 'migration',
        createdAt: new Date().toISOString()
      });
      
      request.onsuccess = () => {
        resolve();
      };
      
      request.onerror = () => {
        reject(request.error);
      };
    });
  }

  // 获取迁移历史
  async getMigrationHistory() {
    await this.indexedDBManager.init();
    const store = await this.indexedDBManager.getStore('metadata');
    
    return new Promise((resolve, reject) => {
      const request = store.get('migration_info');
      
      request.onsuccess = () => {
        resolve(request.result?.value || null);
      };
      
      request.onerror = () => {
        reject(request.error);
      };
    });
  }

  // 列出所有备份
  async listBackups() {
    await this.indexedDBManager.init();
    const store = await this.indexedDBManager.getStore('metadata');
    
    return new Promise((resolve, reject) => {
      const index = store.index ? store.index('type') : null;
      const request = index ? index.getAll('backup') : store.getAll();
      
      request.onsuccess = () => {
        const backups = request.result
          .filter(item => item.type === 'backup')
          .map(item => ({
            id: item.value.id,
            timestamp: item.value.timestamp,
            sourceType: item.value.sourceType,
            dataCount: {
              categories: item.value.data.categories?.length || 0,
              links: item.value.data.links?.length || 0
            }
          }))
          .sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
        
        resolve(backups);
      };
      
      request.onerror = () => {
        reject(request.error);
      };
    });
  }

  // 从备份恢复数据
  async restoreFromBackup(backupId) {
    await this.indexedDBManager.init();
    const store = await this.indexedDBManager.getStore('metadata');
    
    return new Promise((resolve, reject) => {
      const request = store.get(`backup_${backupId}`);
      
      request.onsuccess = async () => {
        const backup = request.result;
        if (!backup) {
          reject(new Error('备份不存在'));
          return;
        }
        
        try {
          // 清空当前数据
          await this.indexedDBManager.clearAllData();
          
          // 恢复备份数据
          const cleanedData = this.validateAndCleanData(backup.value.data);
          await this.indexedDBManager.importData(cleanedData);
          
          resolve({
            success: true,
            backupInfo: {
              id: backup.value.id,
              timestamp: backup.value.timestamp,
              sourceType: backup.value.sourceType
            },
            restoredData: {
              categories: cleanedData.categories.length,
              links: cleanedData.links.length
            }
          });
        } catch (error) {
          reject(error);
        }
      };
      
      request.onerror = () => {
        reject(request.error);
      };
    });
  }

  // 生成Logo（工具方法）
  generateLogo(title) {
    if (!title) return '?';
    // 如果是中文，取第一个字
    if (/[一-龥]/.test(title)) {
      return title.charAt(0);
    }
    // 如果是英文，取前两个字母
    const words = title.split(' ');
    if (words.length >= 2) {
      return (words[0].charAt(0) + words[1].charAt(0)).toUpperCase();
    } else {
      return title.substring(0, 2).toUpperCase();
    }
  }

  // 一键迁移（推荐使用）
  async quickMigration() {
    const status = await this.checkMigrationStatus();
    
    if (status.error) {
      throw new Error(`迁移检查失败: ${status.error}`);
    }
    
    if (!status.needsMigration) {
      if (status.hasIndexedDBData) {
        return {
          success: true,
          message: 'IndexedDB中已有数据，无需迁移',
          alreadyMigrated: true
        };
      } else {
        return {
          success: false,
          message: 'Chrome Storage中没有数据可迁移'
        };
      }
    }
    
    if (status.dataConflict) {
      console.warn('检测到数据冲突，将覆盖IndexedDB中的现有数据');
    }
    
    return await this.migrateFromChromeStorage({
      sourceType: 'auto',
      clearSource: false, // 保留原数据作为备份
      backupFirst: true
    });
  }
}

// 导出迁移管理器
if (typeof module !== 'undefined' && module.exports) {
  module.exports = DataMigrationManager;
} else {
  window.DataMigrationManager = DataMigrationManager;
}