import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import { ConfigManager } from '../../config/config-manager.js';
import { promises as fs } from 'fs';
import path from 'path';

let configManager: ConfigManager;

export async function setupDataManagementTools(server: Server, config?: ConfigManager) {
  configManager = config || new ConfigManager();

  // Add data management tool handlers
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
    const { name, arguments: args } = request.params;

    if (!args) {
      throw new Error('No arguments provided');
    }

    switch (name) {
      case 'export_all_data': {
        const { includeConfig = true } = args as { includeConfig?: boolean };
        
        const storageManager = configManager.getStorageManager();
        
        try {
          const exportPath = await storageManager.exportAllData();
          
          // Get export metadata
          const metadataPath = path.join(exportPath, 'metadata.json');
          const metadata = JSON.parse(await fs.readFile(metadataPath, 'utf-8'));
          
          // List exported items
          const dataDir = path.join(exportPath, 'data');
          const modules = await fs.readdir(dataDir);
          
          return {
            content: [
              {
                type: 'text',
                text: `✅ All Atlas data exported successfully!\n\n` +
                      `📦 Export location: ${exportPath}\n` +
                      `📅 Exported at: ${metadata.exportedAt}\n` +
                      `📁 Project: ${metadata.projectRoot}\n` +
                      `📦 Modules exported: ${modules.join(', ')}\n\n` +
                      `You can now:\n` +
                      `• Archive this export for backup\n` +
                      `• Import it into another project\n` +
                      `• Share it with team members`,
              },
            ],
            structured: {
              exportPath,
              exportId: path.basename(exportPath),
              metadata,
              modules,
            },
          };
        } catch (error) {
          return {
            content: [
              {
                type: 'text',
                text: `❌ Error exporting data: ${(error as Error).message}`,
              },
            ],
          };
        }
      }
      
      case 'import_data': {
        const { exportPath, createBackup = true } = args as {
          exportPath: string;
          createBackup?: boolean;
        };
        
        const storageManager = configManager.getStorageManager();
        
        try {
          await storageManager.importData(exportPath);
          
          return {
            content: [
              {
                type: 'text',
                text: `✅ Data imported successfully!\n\n` +
                      `📦 Imported from: ${exportPath}\n` +
                      `💾 Backup created: ${createBackup ? 'Yes' : 'No'}\n\n` +
                      `⚠️  Note: Restart any active tools to load the new data.`,
              },
            ],
            structured: {
              importPath: exportPath,
              backupCreated: createBackup,
            },
          };
        } catch (error) {
          return {
            content: [
              {
                type: 'text',
                text: `❌ Error importing data: ${(error as Error).message}`,
              },
            ],
          };
        }
      }
      
      case 'sync_to_project': {
        const { 
          modules = ['kanban', 'development'], 
          format = 'json' 
        } = args as {
          modules?: string[];
          format?: 'json' | 'markdown';
        };
        
        const storageManager = configManager.getStorageManager();
        const syncItems: Array<{ module: string; file: string; destination: string }> = [];
        
        // Define what to sync for each module
        for (const module of modules) {
          switch (module) {
            case 'kanban':
              syncItems.push({
                module: 'kanban',
                file: 'kanban.json',
                destination: '.atlas-sync/kanban.json',
              });
              break;
            case 'development':
              syncItems.push({
                module: 'development',
                file: 'development.json',
                destination: '.atlas-sync/development.json',
              });
              break;
          }
        }
        
        await storageManager.syncToProject(syncItems);
        
        // If markdown format requested, also generate readable versions
        if (format === 'markdown') {
          for (const item of syncItems) {
            try {
              const data = await storageManager.loadData(item.module, item.file);
              const mdContent = await generateMarkdownFromData(item.module, data);
              const mdPath = item.destination.replace('.json', '.md');
              await fs.writeFile(
                storageManager.getProjectFilePath(mdPath),
                mdContent,
                'utf-8'
              );
            } catch (error) {
              // Continue with other files
            }
          }
        }
        
        return {
          content: [
            {
              type: 'text',
              text: `✅ Data synced to your project!\n\n` +
                    `📁 Synced modules: ${modules.join(', ')}\n` +
                    `📄 Format: ${format}\n` +
                    `📍 Location: .atlas-sync/\n\n` +
                    `This data is now part of your project and will be:\n` +
                    `• Included in git commits\n` +
                    `• Shared with your team\n` +
                    `• Backed up with your code`,
            },
          ],
          structured: {
            syncedModules: modules,
            format,
            items: syncItems,
          },
        };
      }
      
      case 'configure_storage': {
        const { mode, customPath } = args as {
          mode: 'project-local' | 'user-home' | 'custom';
          customPath?: string;
        };
        
        if (mode === 'custom' && !customPath) {
          return {
            content: [
              {
                type: 'text',
                text: `❌ Error: Custom storage mode requires a customPath parameter`,
              },
            ],
          };
        }
        
        // Update storage configuration
        const currentConfig = configManager.get();
        currentConfig.storage = {
          mode: mode as any,
          path: customPath,
          isolation: 'project',
        };
        
        configManager.set(currentConfig);
        await configManager.save();
        
        const storageManager = configManager.getStorageManager();
        const newLocation = await storageManager.getStorageLocation();
        
        return {
          content: [
            {
              type: 'text',
              text: `✅ Storage configuration updated!\n\n` +
                    `📁 Storage mode: ${mode}\n` +
                    `📍 Location: ${newLocation.base}\n` +
                    (customPath ? `📍 Custom path: ${customPath}\n` : '') +
                    `\n⚠️  Note: Existing data remains in the old location.\n` +
                    `Use 'export_all_data' and 'import_data' to migrate.`,
            },
          ],
          structured: {
            mode,
            customPath,
            location: newLocation,
          },
        };
      }
      
      case 'import_documentation': {
        const { 
          sourcePath,
          includeTemplates = true,
          includeGeneratedDocs = true,
          includeUserDocs = false,
          overwrite = false 
        } = args as {
          sourcePath: string;
          includeTemplates?: boolean;
          includeGeneratedDocs?: boolean;
          includeUserDocs?: boolean;
          overwrite?: boolean;
        };
        
        const storageManager = configManager.getStorageManager();
        
        try {
          // Validate source path exists
          await fs.access(sourcePath);
          
          const importStats = {
            templatesImported: 0,
            docsImported: 0,
            userDocsImported: 0,
            skipped: 0,
            errors: [] as string[]
          };
          
          // Import documentation templates
          if (includeTemplates) {
            const templatesPath = path.join(sourcePath, 'templates');
            try {
              await fs.access(templatesPath);
              const templateFiles = await fs.readdir(templatesPath);
              
              for (const file of templateFiles) {
                if (file.endsWith('.md') || file.endsWith('.txt')) {
                  try {
                    const content = await fs.readFile(path.join(templatesPath, file), 'utf-8');
                    const destPath = await storageManager.getModuleDataPath('documentation', `templates/${file}`);
                    await fs.mkdir(path.dirname(destPath), { recursive: true });
                    
                    if (!overwrite && await fileExists(destPath)) {
                      importStats.skipped++;
                      continue;
                    }
                    
                    await fs.writeFile(destPath, content, 'utf-8');
                    importStats.templatesImported++;
                  } catch (error) {
                    importStats.errors.push(`Template ${file}: ${(error as Error).message}`);
                  }
                }
              }
            } catch {
              // Templates directory doesn't exist, skip
            }
          }
          
          // Import generated documentation
          if (includeGeneratedDocs) {
            const docsPath = path.join(sourcePath, 'docs');
            try {
              await fs.access(docsPath);
              const docFiles = await fs.readdir(docsPath, { recursive: true });
              
              for (const file of docFiles) {
                if (typeof file === 'string' && (file.endsWith('.md') || file.endsWith('.txt'))) {
                  try {
                    const sourcefile = path.join(docsPath, file);
                    const content = await fs.readFile(sourcefile, 'utf-8');
                    const destPath = await storageManager.getModuleDataPath('documentation', `generated/${file}`);
                    await fs.mkdir(path.dirname(destPath), { recursive: true });
                    
                    if (!overwrite && await fileExists(destPath)) {
                      importStats.skipped++;
                      continue;
                    }
                    
                    await fs.writeFile(destPath, content, 'utf-8');
                    importStats.docsImported++;
                  } catch (error) {
                    importStats.errors.push(`Doc ${file}: ${(error as Error).message}`);
                  }
                }
              }
            } catch {
              // Docs directory doesn't exist, skip
            }
          }
          
          // Import user documentation
          if (includeUserDocs) {
            const userDocsPath = path.join(sourcePath, 'user-docs');
            try {
              await fs.access(userDocsPath);
              const userFiles = await fs.readdir(userDocsPath, { recursive: true });
              
              for (const file of userFiles) {
                if (typeof file === 'string' && (file.endsWith('.md') || file.endsWith('.txt'))) {
                  try {
                    const sourcefile = path.join(userDocsPath, file);
                    const content = await fs.readFile(sourcefile, 'utf-8');
                    const destPath = await storageManager.getModuleDataPath('documentation', `user/${file}`);
                    await fs.mkdir(path.dirname(destPath), { recursive: true });
                    
                    if (!overwrite && await fileExists(destPath)) {
                      importStats.skipped++;
                      continue;
                    }
                    
                    await fs.writeFile(destPath, content, 'utf-8');
                    importStats.userDocsImported++;
                  } catch (error) {
                    importStats.errors.push(`User doc ${file}: ${(error as Error).message}`);
                  }
                }
              }
            } catch {
              // User docs directory doesn't exist, skip
            }
          }
          
          const totalImported = importStats.templatesImported + importStats.docsImported + importStats.userDocsImported;
          
          return {
            content: [
              {
                type: 'text',
                text: `✅ Documentation import completed!\n\n` +
                      `📁 Source: ${sourcePath}\n` +
                      `📊 **Import Summary**:\n` +
                      `  • Templates: ${importStats.templatesImported} imported\n` +
                      `  • Generated docs: ${importStats.docsImported} imported\n` +
                      `  • User docs: ${importStats.userDocsImported} imported\n` +
                      `  • Skipped (existing): ${importStats.skipped}\n` +
                      `  • Total imported: ${totalImported}\n\n` +
                      (importStats.errors.length > 0 ? 
                        `⚠️ **Errors** (${importStats.errors.length}):\n${importStats.errors.map(e => `  • ${e}`).join('\n')}\n\n` : '') +
                      `💡 Use the documentation tools to access imported content.`,
              },
            ],
            structured: {
              sourcePath,
              ...importStats,
              totalImported,
            },
          };
        } catch (error) {
          return {
            content: [
              {
                type: 'text',
                text: `❌ Documentation import failed: ${(error as Error).message}`,
              },
            ],
          };
        }
      }
      
      case 'import_project_data': {
        const { 
          sourcePath,
          selectiveImport = [],
          createBackup = true,
          mergeStrategy = 'skip_existing'
        } = args as {
          sourcePath: string;
          selectiveImport?: string[];
          createBackup?: boolean;
          mergeStrategy?: 'overwrite' | 'skip_existing' | 'merge';
        };
        
        const storageManager = configManager.getStorageManager();
        
        try {
          // Validate source path
          await fs.access(sourcePath);
          
          // Check if it's a Atlas export or project directory
          const isAtlasExport = await fileExists(path.join(sourcePath, 'metadata.json'));
          const isProjectDirectory = await fileExists(path.join(sourcePath, '.atlas'));
          
          if (!isAtlasExport && !isProjectDirectory) {
            return {
              content: [
                {
                  type: 'text',
                  text: `❌ Invalid source: Not a Atlas export or project directory\n\n` +
                        `Expected either:\n` +
                        `• Atlas export with metadata.json\n` +
                        `• Project directory with .atlas marker`,
                },
              ],
            };
          }
          
          const importStats = {
            modulesImported: 0,
            filesImported: 0,
            dataSize: 0,
            skipped: 0,
            errors: [] as string[]
          };
          
          // Create backup if requested
          if (createBackup) {
            try {
              const backupPath = await storageManager.exportAllData();
              console.log(`Backup created at: ${backupPath}`);
            } catch (error) {
              importStats.errors.push(`Backup failed: ${(error as Error).message}`);
            }
          }
          
          let sourceDataPath: string;
          let availableModules: string[];
          
          if (isAtlasExport) {
            // Import from Atlas export
            sourceDataPath = path.join(sourcePath, 'data');
            availableModules = await fs.readdir(sourceDataPath);
          } else {
            // Import from project .atlas directory
            sourceDataPath = path.join(sourcePath, '.atlas');
            availableModules = await fs.readdir(sourceDataPath);
          }
          
          // Filter modules if selective import specified
          const modulesToImport = selectiveImport.length > 0 
            ? availableModules.filter(module => selectiveImport.includes(module))
            : availableModules;
          
          for (const moduleName of modulesToImport) {
            try {
              const moduleSourcePath = path.join(sourceDataPath, moduleName);
              const moduleFiles = await fs.readdir(moduleSourcePath, { recursive: true });
              
              for (const file of moduleFiles) {
                if (typeof file === 'string' && file.endsWith('.json')) {
                  try {
                    const sourceFile = path.join(moduleSourcePath, file);
                    const content = await fs.readFile(sourceFile, 'utf-8');
                    const destPath = await storageManager.getModuleDataPath(moduleName, file);
                    
                    // Handle merge strategy
                    if (await fileExists(destPath) && mergeStrategy === 'skip_existing') {
                      importStats.skipped++;
                      continue;
                    }
                    
                    if (await fileExists(destPath) && mergeStrategy === 'merge') {
                      // Attempt to merge JSON data
                      try {
                        const existingData = JSON.parse(await fs.readFile(destPath, 'utf-8'));
                        const newData = JSON.parse(content);
                        const mergedData = { ...existingData, ...newData };
                        await fs.writeFile(destPath, JSON.stringify(mergedData, null, 2), 'utf-8');
                      } catch {
                        // If merge fails, overwrite
                        await fs.writeFile(destPath, content, 'utf-8');
                      }
                    } else {
                      // Overwrite or new file
                      await fs.mkdir(path.dirname(destPath), { recursive: true });
                      await fs.writeFile(destPath, content, 'utf-8');
                    }
                    
                    importStats.filesImported++;
                    importStats.dataSize += content.length;
                  } catch (error) {
                    importStats.errors.push(`${moduleName}/${file}: ${(error as Error).message}`);
                  }
                }
              }
              
              importStats.modulesImported++;
            } catch (error) {
              importStats.errors.push(`Module ${moduleName}: ${(error as Error).message}`);
            }
          }
          
          return {
            content: [
              {
                type: 'text',
                text: `✅ Project data import completed!\n\n` +
                      `📁 Source: ${sourcePath}\n` +
                      `📊 **Import Summary**:\n` +
                      `  • Modules: ${importStats.modulesImported} imported\n` +
                      `  • Files: ${importStats.filesImported} imported\n` +
                      `  • Data size: ${Math.round(importStats.dataSize / 1024)} KB\n` +
                      `  • Skipped: ${importStats.skipped}\n` +
                      `  • Strategy: ${mergeStrategy}\n\n` +
                      (importStats.errors.length > 0 ? 
                        `⚠️ **Errors** (${importStats.errors.length}):\n${importStats.errors.slice(0, 5).map(e => `  • ${e}`).join('\n')}${importStats.errors.length > 5 ? '\n  • ...' : ''}\n\n` : '') +
                      `💡 Restart tools or refresh to use imported data.`,
              },
            ],
            structured: {
              sourcePath,
              ...importStats,
              modulesToImport,
            },
          };
        } catch (error) {
          return {
            content: [
              {
                type: 'text',
                text: `❌ Project data import failed: ${(error as Error).message}`,
              },
            ],
          };
        }
      }

      case 'import_external_docs': {
        const { 
          sourcePath,
          autoCategories = true,
          preserveStructure = true,
          includeMetadata = true,
          supportedFormats = ['md', 'txt', 'rst', 'adoc']
        } = args as {
          sourcePath: string;
          autoCategories?: boolean;
          preserveStructure?: boolean;
          includeMetadata?: boolean;
          supportedFormats?: string[];
        };
        
        const storageManager = configManager.getStorageManager();
        
        try {
          await fs.access(sourcePath);
          
          const importStats = {
            documentsImported: 0,
            categoriesCreated: 0,
            metadataExtracted: 0,
            skipped: 0,
            errors: [] as string[],
            categories: {} as Record<string, number>
          };
          
          // Function to categorize document based on filename and content
          const categorizeDocument = (filename: string, content: string): {
            category: string;
            subcategory?: string;
            tags: string[];
          } => {
            const lower = filename.toLowerCase();
            const contentLower = content.toLowerCase();
            
            // API Documentation
            if (lower.includes('api') || contentLower.includes('endpoint') || contentLower.includes('swagger')) {
              return { category: 'api', subcategory: 'reference', tags: ['api', 'reference'] };
            }
            
            // User/End-user Documentation
            if (lower.includes('user') || lower.includes('guide') || contentLower.includes('how to')) {
              return { category: 'user', subcategory: 'guides', tags: ['user', 'guide', 'tutorial'] };
            }
            
            // Developer Documentation
            if (lower.includes('dev') || lower.includes('contrib') || contentLower.includes('development')) {
              return { category: 'developer', subcategory: 'setup', tags: ['developer', 'setup'] };
            }
            
            // Architecture/Design
            if (lower.includes('arch') || lower.includes('design') || contentLower.includes('architecture')) {
              return { category: 'architecture', subcategory: 'design', tags: ['architecture', 'design'] };
            }
            
            // README files
            if (lower.includes('readme')) {
              return { category: 'overview', subcategory: 'introduction', tags: ['readme', 'overview'] };
            }
            
            // Changelog/Release notes
            if (lower.includes('change') || lower.includes('release') || lower.includes('history')) {
              return { category: 'releases', subcategory: 'changelog', tags: ['changelog', 'releases'] };
            }
            
            // Troubleshooting/FAQ
            if (lower.includes('troubleshoot') || lower.includes('faq') || lower.includes('problem')) {
              return { category: 'support', subcategory: 'troubleshooting', tags: ['troubleshooting', 'faq'] };
            }
            
            // Configuration
            if (lower.includes('config') || lower.includes('setting') || contentLower.includes('configuration')) {
              return { category: 'configuration', subcategory: 'setup', tags: ['configuration', 'setup'] };
            }
            
            // Default category
            return { category: 'general', subcategory: 'misc', tags: ['general'] };
          };
          
          // Function to extract metadata from document
          const extractMetadata = (filename: string, content: string) => {
            const metadata: any = {
              filename,
              originalPath: '',
              importedAt: new Date().toISOString(),
              wordCount: content.split(/\s+/).length,
              lineCount: content.split('\n').length,
              size: content.length
            };
            
            // Extract title from first line or H1
            const firstLine = content.split('\n')[0];
            if (firstLine.startsWith('#')) {
              metadata.title = firstLine.replace(/^#+\s*/, '');
            } else if (firstLine.trim()) {
              metadata.title = firstLine.trim();
            } else {
              metadata.title = filename.replace(/\.[^.]+$/, ''); // Remove extension
            }
            
            // Extract headers for table of contents
            const headers = content.match(/^#{1,6}\s+.+$/gm) || [];
            metadata.tableOfContents = headers.map(header => {
              const level = (header.match(/^#+/) || [''])[0].length;
              const text = header.replace(/^#+\s*/, '');
              return { level, text };
            });
            
            // Look for common patterns
            if (content.includes('```')) {
              metadata.hasCodeBlocks = true;
            }
            if (content.match(/!\[.*?\]\(.*?\)/)) {
              metadata.hasImages = true;
            }
            if (content.match(/\[.*?\]\(.*?\)/)) {
              metadata.hasLinks = true;
            }
            
            return metadata;
          };
          
          // Recursively process directory
          const processDirectory = async (dirPath: string, relativePath = '') => {
            const entries = await fs.readdir(dirPath, { withFileTypes: true });
            
            for (const entry of entries) {
              const fullPath = path.join(dirPath, entry.name);
              const entryRelativePath = path.join(relativePath, entry.name);
              
              if (entry.isDirectory()) {
                await processDirectory(fullPath, entryRelativePath);
              } else if (entry.isFile()) {
                const ext = path.extname(entry.name).slice(1);
                
                if (supportedFormats.includes(ext)) {
                  try {
                    const content = await fs.readFile(fullPath, 'utf-8');
                    
                    // Categorize document
                    let category = { category: 'general', subcategory: 'misc', tags: ['general'] };
                    if (autoCategories) {
                      const cat = categorizeDocument(entry.name, content);
                      category = { ...cat, subcategory: cat.subcategory || 'misc' };
                    }
                    
                    // Extract metadata
                    let metadata = {};
                    if (includeMetadata) {
                      metadata = extractMetadata(entry.name, content);
                      (metadata as any).originalPath = entryRelativePath;
                      importStats.metadataExtracted++;
                    }
                    
                    // Determine destination path
                    let destPath: string;
                    if (preserveStructure) {
                      destPath = await storageManager.getModuleDataPath('documentation', `external/${entryRelativePath}`);
                    } else {
                      const categoryPath = autoCategories ? `${category.category}/${category.subcategory || ''}` : 'imported';
                      destPath = await storageManager.getModuleDataPath('documentation', `${categoryPath}/${entry.name}`);
                    }
                    
                    await fs.mkdir(path.dirname(destPath), { recursive: true });
                    
                    // Save document with metadata
                    const documentData = {
                      content,
                      metadata,
                      category: autoCategories ? category : undefined,
                      importedFrom: entryRelativePath,
                      importedAt: new Date().toISOString()
                    };
                    
                    await fs.writeFile(destPath, JSON.stringify(documentData, null, 2), 'utf-8');
                    
                    // Update stats
                    importStats.documentsImported++;
                    if (autoCategories) {
                      const catKey = category.category;
                      importStats.categories[catKey] = (importStats.categories[catKey] || 0) + 1;
                    }
                    
                  } catch (error) {
                    importStats.errors.push(`${entryRelativePath}: ${(error as Error).message}`);
                  }
                }
              }
            }
          };
          
          await processDirectory(sourcePath);
          
          const categoriesCreated = Object.keys(importStats.categories).length;
          
          return {
            content: [
              {
                type: 'text',
                text: `✅ External documentation import completed!\n\n` +
                      `📁 **Source**: ${sourcePath}\n` +
                      `📊 **Import Summary**:\n` +
                      `  • Documents imported: ${importStats.documentsImported}\n` +
                      `  • Categories created: ${categoriesCreated}\n` +
                      `  • Metadata extracted: ${importStats.metadataExtracted}\n` +
                      `  • Formats processed: ${supportedFormats.join(', ')}\n\n` +
                      (categoriesCreated > 0 ? 
                        `📂 **Categories**:\n${Object.entries(importStats.categories).map(([cat, count]) => `  • ${cat}: ${count} documents`).join('\n')}\n\n` : '') +
                      (importStats.errors.length > 0 ? 
                        `⚠️ **Errors** (${importStats.errors.length}):\n${importStats.errors.slice(0, 3).map(e => `  • ${e}`).join('\n')}${importStats.errors.length > 3 ? '\n  • ...' : ''}\n\n` : '') +
                      `💡 Documents are now searchable and accessible through the documentation module.`,
              },
            ],
            structured: {
              sourcePath,
              ...importStats,
              categoriesCreated,
            },
          };
        } catch (error) {
          return {
            content: [
              {
                type: 'text',
                text: `❌ External documentation import failed: ${(error as Error).message}`,
              },
            ],
          };
        }
      }

      case 'bulk_import_templates': {
        const { 
          templateType = 'all',
          source = 'builtin',
          customPath,
          overwrite = false 
        } = args as {
          templateType?: 'documentation' | 'project' | 'business' | 'all';
          source?: 'builtin' | 'github' | 'local';
          customPath?: string;
          overwrite?: boolean;
        };
        
        const storageManager = configManager.getStorageManager();
        
        try {
          const importStats = {
            templatesImported: 0,
            skipped: 0,
            errors: [] as string[]
          };
          
          // Define built-in template sets
          const builtinTemplates = {
            documentation: [
              { name: 'README.md', content: '# {{projectName}}\n\n## Description\n{{description}}\n\n## Installation\n```bash\nnpm install\n```' },
              { name: 'API.md', content: '# API Documentation\n\n## Endpoints\n\n### GET /api/health\nReturns server status' },
              { name: 'CONTRIBUTING.md', content: '# Contributing Guide\n\n## Development Setup\n1. Clone the repository\n2. Install dependencies\n3. Run tests' }
            ],
            project: [
              { name: 'gitignore.template', content: 'node_modules/\n.env\ndist/\n*.log' },
              { name: 'package.json.template', content: '{\n  "name": "{{projectName}}",\n  "version": "1.0.0",\n  "description": "{{description}}"\n}' },
              { name: 'tsconfig.json.template', content: '{\n  "compilerOptions": {\n    "target": "ES2020",\n    "module": "commonjs"\n  }\n}' }
            ],
            business: [
              { name: 'business-plan.md', content: '# Business Plan\n\n## Executive Summary\n{{summary}}\n\n## Market Analysis\n{{market}}' },
              { name: 'pitch-deck.md', content: '# Pitch Deck\n\n## Problem\n{{problem}}\n\n## Solution\n{{solution}}' }
            ]
          };
          
          let templates: Array<{name: string, content: string}> = [];
          
          if (source === 'builtin') {
            if (templateType === 'all') {
              templates = [
                ...builtinTemplates.documentation,
                ...builtinTemplates.project,
                ...builtinTemplates.business
              ];
            } else {
              templates = builtinTemplates[templateType] || [];
            }
          } else if (source === 'local' && customPath) {
            // Import from local directory
            try {
              await fs.access(customPath);
              const files = await fs.readdir(customPath, { recursive: true });
              
              for (const file of files) {
                if (typeof file === 'string' && (file.endsWith('.md') || file.endsWith('.template') || file.endsWith('.txt'))) {
                  const content = await fs.readFile(path.join(customPath, file), 'utf-8');
                  templates.push({ name: file, content });
                }
              }
            } catch (error) {
              importStats.errors.push(`Failed to read from ${customPath}: ${(error as Error).message}`);
            }
          }
          
          // Import templates
          for (const template of templates) {
            try {
              const destPath = await storageManager.getModuleDataPath('templates', template.name);
              await fs.mkdir(path.dirname(destPath), { recursive: true });
              
              if (!overwrite && await fileExists(destPath)) {
                importStats.skipped++;
                continue;
              }
              
              await fs.writeFile(destPath, template.content, 'utf-8');
              importStats.templatesImported++;
            } catch (error) {
              importStats.errors.push(`Template ${template.name}: ${(error as Error).message}`);
            }
          }
          
          return {
            content: [
              {
                type: 'text',
                text: `✅ Bulk template import completed!\n\n` +
                      `📦 **Import Summary**:\n` +
                      `  • Source: ${source}\n` +
                      `  • Type: ${templateType}\n` +
                      `  • Templates imported: ${importStats.templatesImported}\n` +
                      `  • Skipped (existing): ${importStats.skipped}\n` +
                      (importStats.errors.length > 0 ? 
                        `  • Errors: ${importStats.errors.length}\n\n` +
                        `⚠️ **Errors**:\n${importStats.errors.map(e => `  • ${e}`).join('\n')}\n\n` : '') +
                      `💡 Templates are now available for project generation.`,
              },
            ],
            structured: {
              source,
              templateType,
              ...importStats,
            },
          };
        } catch (error) {
          return {
            content: [
              {
                type: 'text',
                text: `❌ Bulk template import failed: ${(error as Error).message}`,
              },
            ],
          };
        }
      }

      case 'export_module_data': {
        const { moduleName, format = 'json' } = args as {
          moduleName: string;
          format?: 'json' | 'markdown' | 'csv';
        };
        
        const storageManager = configManager.getStorageManager();
        
        try {
          // Load module data
          const dataFile = `${moduleName}.json`;
          const data = await storageManager.loadData(moduleName, dataFile);
          
          if (!data) {
            return {
              content: [
                {
                  type: 'text',
                  text: `❌ No data found for module: ${moduleName}`,
                },
              ],
            };
          }
          
          // Determine export path and content
          let exportContent: string;
          let exportFile: string;
          
          switch (format) {
            case 'markdown':
              exportContent = await generateMarkdownFromData(moduleName, data);
              exportFile = `${moduleName}-export.md`;
              break;
            case 'csv':
              exportContent = await generateCSVFromData(moduleName, data);
              exportFile = `${moduleName}-export.csv`;
              break;
            default:
              exportContent = JSON.stringify(data, null, 2);
              exportFile = `${moduleName}-export.json`;
          }
          
          // Save to project directory
          const exportPath = storageManager.getProjectFilePath(exportFile);
          await fs.writeFile(exportPath, exportContent, 'utf-8');
          
          return {
            content: [
              {
                type: 'text',
                text: `✅ Module data exported!\n\n` +
                      `📦 Module: ${moduleName}\n` +
                      `📄 Format: ${format}\n` +
                      `📍 File: ${exportFile}\n` +
                      `📏 Size: ${exportContent.length} bytes`,
              },
            ],
            structured: {
              module: moduleName,
              format,
              file: exportFile,
              path: exportPath,
              size: exportContent.length,
            },
          };
        } catch (error) {
          return {
            content: [
              {
                type: 'text',
                text: `❌ Error exporting module data: ${(error as Error).message}`,
              },
            ],
          };
        }
      }
      
      default:
        // Not a data management tool
        return null as any;
    }
  });

  return {
    tools: [
      {
        name: 'export_all_data',
        description: 'Export all Atlas data for backup or migration',
        inputSchema: {
          type: 'object',
          properties: {
            includeConfig: { 
              type: 'boolean', 
              default: true,
              description: 'Include configuration in export'
            },
          },
          required: [],
        },
      },
      {
        name: 'import_data',
        description: 'Import previously exported Atlas data',
        inputSchema: {
          type: 'object',
          properties: {
            exportPath: { type: 'string', description: 'Path to export directory' },
            createBackup: { 
              type: 'boolean', 
              default: true,
              description: 'Create backup before importing'
            },
          },
          required: ['exportPath'],
        },
      },
      {
        name: 'sync_to_project',
        description: 'Sync Atlas data to your project directory',
        inputSchema: {
          type: 'object',
          properties: {
            modules: { 
              type: 'array',
              items: { type: 'string' },
              default: ['kanban', 'development'],
              description: 'Modules to sync'
            },
            format: { 
              type: 'string',
              enum: ['json', 'markdown'],
              default: 'json',
              description: 'Export format'
            },
          },
          required: [],
        },
      },
      {
        name: 'configure_storage',
        description: 'Configure where Atlas stores data',
        inputSchema: {
          type: 'object',
          properties: {
            mode: { 
              type: 'string',
              enum: ['project-local', 'user-home', 'custom'],
              description: 'Storage mode'
            },
            customPath: { 
              type: 'string',
              description: 'Custom storage path (required for custom mode)'
            },
          },
          required: ['mode'],
        },
      },
      {
        name: 'export_module_data',
        description: 'Export data from a specific module',
        inputSchema: {
          type: 'object',
          properties: {
            moduleName: { type: 'string', description: 'Module to export' },
            format: { 
              type: 'string',
              enum: ['json', 'markdown', 'csv'],
              default: 'json',
              description: 'Export format'
            },
          },
          required: ['moduleName'],
        },
      },
      {
        name: 'import_documentation',
        description: 'Import documentation from external sources',
        inputSchema: {
          type: 'object',
          properties: {
            sourcePath: { 
              type: 'string', 
              description: 'Path to documentation source directory' 
            },
            includeTemplates: { 
              type: 'boolean', 
              default: true,
              description: 'Import documentation templates'
            },
            includeGeneratedDocs: { 
              type: 'boolean', 
              default: true,
              description: 'Import generated documentation'
            },
            includeUserDocs: { 
              type: 'boolean', 
              default: false,
              description: 'Import user-created documentation'
            },
            overwrite: { 
              type: 'boolean', 
              default: false,
              description: 'Overwrite existing files'
            },
          },
          required: ['sourcePath'],
        },
      },
      {
        name: 'import_project_data',
        description: 'Import project data from another Atlas project or export',
        inputSchema: {
          type: 'object',
          properties: {
            sourcePath: { 
              type: 'string', 
              description: 'Path to source project or export directory' 
            },
            selectiveImport: { 
              type: 'array',
              items: { type: 'string' },
              default: [],
              description: 'Specific modules to import (empty = all)'
            },
            createBackup: { 
              type: 'boolean', 
              default: true,
              description: 'Create backup before importing'
            },
            mergeStrategy: { 
              type: 'string',
              enum: ['overwrite', 'skip_existing', 'merge'],
              default: 'skip_existing',
              description: 'How to handle existing data'
            },
          },
          required: ['sourcePath'],
        },
      },
      {
        name: 'bulk_import_templates',
        description: 'Import built-in templates or templates from external sources',
        inputSchema: {
          type: 'object',
          properties: {
            templateType: { 
              type: 'string',
              enum: ['documentation', 'project', 'business', 'all'],
              default: 'all',
              description: 'Type of templates to import'
            },
            source: { 
              type: 'string',
              enum: ['builtin', 'local'],
              default: 'builtin',
              description: 'Source of templates'
            },
            customPath: { 
              type: 'string',
              description: 'Path to custom templates directory (required for local source)'
            },
            overwrite: { 
              type: 'boolean', 
              default: false,
              description: 'Overwrite existing templates'
            },
          },
          required: [],
        },
      },
      {
        name: 'import_external_docs',
        description: 'Import existing documentation with automatic categorization',
        inputSchema: {
          type: 'object',
          properties: {
            sourcePath: { 
              type: 'string', 
              description: 'Path to existing documentation directory' 
            },
            autoCategories: { 
              type: 'boolean', 
              default: true,
              description: 'Automatically categorize documents by type and content'
            },
            preserveStructure: { 
              type: 'boolean', 
              default: true,
              description: 'Preserve original directory structure'
            },
            includeMetadata: { 
              type: 'boolean', 
              default: true,
              description: 'Extract and store document metadata'
            },
            supportedFormats: { 
              type: 'array',
              items: { type: 'string' },
              default: ['md', 'txt', 'rst', 'adoc'],
              description: 'File formats to import'
            },
          },
          required: ['sourcePath'],
        },
      },
    ],
    resources: [],
  };
}

async function generateMarkdownFromData(module: string, data: any): Promise<string> {
  let content = `# ${module.charAt(0).toUpperCase() + module.slice(1)} Data Export\n\n`;
  content += `Exported on: ${new Date().toISOString()}\n\n`;
  
  switch (module) {
    case 'kanban':
      if (data.boards) {
        content += `## Boards\n\n`;
        for (const [id, board] of Object.entries(data.boards) as any) {
          content += `### ${board.name}\n\n`;
          content += `- **ID**: ${id}\n`;
          content += `- **Columns**: ${board.columns.join(', ')}\n`;
          content += `- **Tasks**: ${board.tasks.length}\n\n`;
          
          if (board.tasks.length > 0) {
            content += `#### Tasks\n\n`;
            for (const task of board.tasks) {
              content += `- **${task.title}** (${task.priority})\n`;
              content += `  - Column: ${task.column}\n`;
              content += `  - Status: ${task.status}\n`;
              if (task.description) {
                content += `  - Description: ${task.description}\n`;
              }
              content += `\n`;
            }
          }
        }
      }
      break;
      
    case 'development':
      if (data.features) {
        content += `## Features\n\n`;
        for (const [id, feature] of Object.entries(data.features) as any) {
          content += `### ${feature.name}\n\n`;
          content += `- **Description**: ${feature.description}\n`;
          content += `- **Status**: ${feature.implementationStatus}\n`;
          content += `- **Coverage**: ${feature.testCoverage}%\n`;
          content += `- **Tests**: ${feature.testCases.length}\n\n`;
        }
      }
      break;
      
    default:
      content += '```json\n';
      content += JSON.stringify(data, null, 2);
      content += '\n```\n';
  }
  
  return content;
}

async function fileExists(filePath: string): Promise<boolean> {
  try {
    await fs.access(filePath);
    return true;
  } catch {
    return false;
  }
}

async function generateCSVFromData(module: string, data: any): Promise<string> {
  let csv = '';
  
  switch (module) {
    case 'kanban':
      csv = 'Board,Task,Priority,Column,Status,Description\n';
      if (data.boards) {
        for (const board of Object.values(data.boards) as any) {
          for (const task of board.tasks) {
            csv += `"${board.name}","${task.title}","${task.priority}","${task.column}","${task.status}","${task.description || ''}"\n`;
          }
        }
      }
      break;
      
    case 'development':
      csv = 'Feature,Description,Status,Coverage,Tests\n';
      if (data.features) {
        for (const feature of Object.values(data.features) as any) {
          csv += `"${feature.name}","${feature.description}","${feature.implementationStatus}",${feature.testCoverage},${feature.testCases.length}\n`;
        }
      }
      break;
      
    default:
      csv = 'Error: CSV export not supported for this module\n';
  }
  
  return csv;
}