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

let configManager: ConfigManager;

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

  // Add project 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 'init_atlas': {
        const { projectName } = args as { projectName?: string };
        
        const storageManager = configManager.getStorageManager();
        
        try {
          // Check if already initialized
          const existingMarker = await storageManager.loadProjectMarker();
          if (existingMarker) {
            return {
              content: [
                {
                  type: 'text',
                  text: `ℹ️ Project already initialized!\n\n` +
                        `📋 Project: ${existingMarker.projectName}\n` +
                        `🆔 ID: ${existingMarker.projectId}\n` +
                        `📅 Created: ${existingMarker.createdAt}\n` +
                        `📁 Root: ${existingMarker.projectRoot}\n\n` +
                        `To reinitialize, first remove the .atlas file.`,
                },
              ],
              structured: {
                alreadyInitialized: true,
                marker: existingMarker,
              },
            };
          }
          
          // Initialize the project
          const marker = await storageManager.initializeProject(projectName);
          
          // Add .atlas to gitignore if git exists
          const gitignorePath = path.join(process.cwd(), '.gitignore');
          try {
            let gitignoreContent = '';
            try {
              gitignoreContent = await fs.readFile(gitignorePath, 'utf-8');
            } catch {
              // .gitignore doesn't exist yet
            }
            
            if (!gitignoreContent.includes('.atlas')) {
              gitignoreContent += (gitignoreContent && !gitignoreContent.endsWith('\n') ? '\n' : '') + 
                                  '# Atlas MCP marker file\n.atlas\n';
              await fs.writeFile(gitignorePath, gitignoreContent, 'utf-8');
            }
          } catch {
            // Ignore gitignore errors
          }
          
          return {
            content: [
              {
                type: 'text',
                text: `✅ Atlas MCP initialized for project!\n\n` +
                      `📋 Project: ${marker.projectName}\n` +
                      `🆔 ID: ${marker.projectId}\n` +
                      `📁 Root: ${marker.projectRoot}\n` +
                      `📄 Marker: .atlas\n\n` +
                      `All Atlas data will be stored in:\n` +
                      `📂 ${marker.projectRoot}/.atlas/\n\n` +
                      `The .atlas file identifies this as a Atlas project.\n` +
                      `This file has been added to .gitignore.`,
              },
            ],
            structured: {
              initialized: true,
              marker,
            },
          };
        } catch (error) {
          return {
            content: [
              {
                type: 'text',
                text: `❌ Error initializing project: ${(error as Error).message}`,
              },
            ],
          };
        }
      }
      
      case 'check_project_status': {
        const storageManager = configManager.getStorageManager();
        
        try {
          const marker = await storageManager.loadProjectMarker();
          
          if (!marker) {
            return {
              content: [
                {
                  type: 'text',
                  text: `❌ Not a Atlas project!\n\n` +
                        `This directory has not been initialized with Atlas MCP.\n` +
                        `Run 'init_atlas' to initialize this project.`,
                },
              ],
              structured: {
                initialized: false,
              },
            };
          }
          
          // Check storage location
          const location = await storageManager.getStorageLocation();
          
          // Count data files
          let dataFileCount = 0;
          try {
            const modules = await fs.readdir(location.data);
            for (const module of modules) {
              const modulePath = path.join(location.data, module);
              const stat = await fs.stat(modulePath);
              if (stat.isDirectory()) {
                const files = await fs.readdir(modulePath);
                dataFileCount += files.length;
              }
            }
          } catch {
            // Data directory might not exist yet
          }
          
          return {
            content: [
              {
                type: 'text',
                text: `📊 Project Status\n\n` +
                    `📋 Project: ${marker.projectName}\n` +
                    `🆔 ID: ${marker.projectId}\n` +
                    `📅 Initialized: ${marker.createdAt}\n` +
                    `📁 Root: ${marker.projectRoot}\n` +
                    `🗄️ Data files: ${dataFileCount}\n` +
                    `💾 Storage: ${location.base}\n\n` +
                    `✅ This is a valid Atlas project!`,
              },
            ],
            structured: {
              initialized: true,
              marker,
              dataFileCount,
              storageLocation: location,
            },
          };
        } catch (error) {
          return {
            content: [
              {
                type: 'text',
                text: `❌ Error checking project status: ${(error as Error).message}`,
              },
            ],
          };
        }
      }
      
      case 'find_atlas_project': {
        const storageManager = configManager.getStorageManager();
        const projectRoot = storageManager.getProjectRoot();
        
        const marker = await storageManager.loadProjectMarker();
        
        if (!marker) {
          return {
            content: [
              {
                type: 'text',
                text: `🔍 No Atlas project found\n\n` +
                      `Searched from: ${process.cwd()}\n` +
                      `No .atlas marker file found in current or parent directories.\n\n` +
                      `Run 'init_atlas' to initialize a project here.`,
              },
            ],
            structured: {
              found: false,
              searchedFrom: process.cwd(),
            },
          };
        }
        
        return {
          content: [
            {
              type: 'text',
              text: `✅ Found Atlas project!\n\n` +
                    `📋 Project: ${marker.projectName}\n` +
                    `📁 Location: ${projectRoot}\n` +
                    `🆔 ID: ${marker.projectId}\n\n` +
                    (projectRoot !== process.cwd() ? 
                      `ℹ️ Note: You're in a subdirectory. The project root is at:\n${projectRoot}` : 
                      `✅ You're at the project root.`),
            },
          ],
          structured: {
            found: true,
            marker,
            projectRoot,
            currentDir: process.cwd(),
            isAtRoot: projectRoot === process.cwd(),
          },
        };
      }
      
      case 'remove_atlas': {
        const { confirm = false } = args as { confirm?: boolean };
        
        if (!confirm) {
          return {
            content: [
              {
                type: 'text',
                text: `⚠️ Warning: This will remove Atlas from this project!\n\n` +
                      `This action will:\n` +
                      `• Delete the .atlas marker file\n` +
                      `• Remove the .atlas/ data directory\n` +
                      `• Delete all Atlas data for this project\n\n` +
                      `To confirm, run: remove_atlas confirm=true`,
              },
            ],
          };
        }
        
        const storageManager = configManager.getStorageManager();
        const marker = await storageManager.loadProjectMarker();
        
        if (!marker) {
          return {
            content: [
              {
                type: 'text',
                text: `❌ Not a Atlas project - nothing to remove.`,
              },
            ],
          };
        }
        
        try {
          // Remove marker file
          const markerPath = path.join(storageManager.getProjectRoot(), '.atlas');
          await fs.unlink(markerPath);
          
          // Remove data directory
          const location = await storageManager.getStorageLocation();
          await fs.rm(location.base, { recursive: true, force: true });
          
          return {
            content: [
              {
                type: 'text',
                text: `✅ Atlas removed from project\n\n` +
                      `Deleted:\n` +
                      `• .atlas marker file\n` +
                      `• .atlas/ data directory\n\n` +
                      `The project is no longer managed by Atlas MCP.`,
              },
            ],
          };
        } catch (error) {
          return {
            content: [
              {
                type: 'text',
                text: `❌ Error removing Atlas: ${(error as Error).message}`,
              },
            ],
          };
        }
      }
      
      default:
        // Not a project management tool, throw to let other handlers try
        throw new Error(`Tool ${name} not handled by project management module`);
    }
  });

  return {
    tools: [
      {
        name: 'init_atlas',
        description: 'Initialize Atlas MCP in the current project',
        inputSchema: {
          type: 'object',
          properties: {
            projectName: { 
              type: 'string', 
              description: 'Custom project name (defaults to directory name)' 
            },
          },
          required: []
        },
      },
      {
        name: 'check_project_status',
        description: 'Check if current directory is a Atlas project',
        inputSchema: {
          type: 'object',
          properties: {},
          required: []
        },
      },
      {
        name: 'find_atlas_project',
        description: 'Find the nearest Atlas project in parent directories',
        inputSchema: {
          type: 'object',
          properties: {},
          required: []
        },
      },
      {
        name: 'remove_atlas',
        description: 'Remove Atlas MCP from the current project',
        inputSchema: {
          type: 'object',
          properties: {
            confirm: { 
              type: 'boolean', 
              default: false,
              description: 'Confirm removal of all Atlas data' 
            },
          },
          required: []
        },
      },
    ],
    resources: [],
  };
}