import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import { WorkspaceDataStore } from './store.js';
import { ConfigManager } from '../../config/config-manager.js';

let workspaceStore: WorkspaceDataStore;
let configManager: ConfigManager;

export async function setupWorkspaceTools(server: Server, config?: ConfigManager) {
  configManager = config || new ConfigManager();
  workspaceStore = new WorkspaceDataStore(configManager);
  await workspaceStore.init();

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

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

    switch (name) {
      case 'create_workspace': {
        const { name: workspaceName, rootPath, description } = args as {
          name: string;
          rootPath?: string;
          description?: string;
        };
        
        const resolvedPath = rootPath || process.cwd();
        const workspace = workspaceStore.createWorkspace(workspaceName, resolvedPath, description);
        
        // Auto-detect repositories
        const detectedRepos = await workspaceStore.detectRepositories(resolvedPath);
        for (const repo of detectedRepos) {
          workspaceStore.addRepository(workspace.id, repo);
        }
        
        await workspaceStore.save();
        
        return {
          content: [
            {
              type: 'text',
              text: `✅ Workspace "${workspace.name}" created\n` +
                    `📁 Root: ${workspace.rootPath}\n` +
                    `📦 Detected ${detectedRepos.length} repositories`,
            },
          ],
        };
      }
      
      case 'add_repository': {
        const { workspaceName, name: repoName, path: repoPath, primary } = args as {
          workspaceName: string;
          name: string;
          path: string;
          primary?: boolean;
        };
        
        const repo = workspaceStore.addRepository(workspaceName, {
          name: repoName,
          path: repoPath,
          type: 'git',
          primary,
        });
        
        if (!repo) {
          return {
            content: [
              {
                type: 'text',
                text: `❌ Workspace "${workspaceName}" not found`,
              },
            ],
          };
        }
        
        await workspaceStore.save();
        
        return {
          content: [
            {
              type: 'text',
              text: `✅ Repository "${repo.name}" added to workspace\n` +
                    `📁 Path: ${repo.path}${repo.primary ? ' (Primary)' : ''}`,
            },
          ],
        };
      }
      
      case 'list_repositories': {
        const { workspaceName } = args as { workspaceName?: string };
        
        const workspace = workspaceName 
          ? workspaceStore.getWorkspace(workspaceName)
          : workspaceStore.getActiveWorkspace();
        
        if (!workspace) {
          return {
            content: [
              {
                type: 'text',
                text: `❌ No workspace found`,
              },
            ],
          };
        }
        
        const repoList = workspace.repositories.map(repo => 
          `📦 ${repo.name}${repo.primary ? ' (Primary)' : ''}\n   📁 ${repo.path}\n   🔄 Last sync: ${repo.lastSync?.toLocaleString()}`
        ).join('\n\n');
        
        return {
          content: [
            {
              type: 'text',
              text: `Repositories in "${workspace.name}":\n\n${repoList || 'No repositories added yet'}`,
            },
          ],
        };
      }
      
      case 'switch_workspace': {
        const { workspaceName } = args as { workspaceName: string };
        
        const success = workspaceStore.setActiveWorkspace(workspaceName);
        
        if (!success) {
          return {
            content: [
              {
                type: 'text',
                text: `❌ Workspace "${workspaceName}" not found`,
              },
            ],
          };
        }
        
        await workspaceStore.save();
        
        return {
          content: [
            {
              type: 'text',
              text: `✅ Switched to workspace "${workspaceName}"`,
            },
          ],
        };
      }
      
      default:
        // Not a workspace tool, let other handlers process it
        return null as any;
    }
  });

  return {
    tools: [
      {
        name: 'create_workspace',
        description: 'Create a new multi-repository workspace',
        inputSchema: {
          type: 'object',
          properties: {
            name: { type: 'string' },
            rootPath: { type: 'string', description: 'Root directory path (defaults to current directory)' },
            description: { type: 'string' },
          },
          required: ['name'],
        },
      },
      {
        name: 'add_repository',
        description: 'Add a repository to a workspace',
        inputSchema: {
          type: 'object',
          properties: {
            workspaceName: { type: 'string' },
            name: { type: 'string' },
            path: { type: 'string' },
            primary: { type: 'boolean', default: false },
          },
          required: ['workspaceName', 'name', 'path'],
        },
      },
      {
        name: 'list_repositories',
        description: 'List repositories in a workspace',
        inputSchema: {
          type: 'object',
          properties: {
            workspaceName: { type: 'string', description: 'Workspace name (defaults to active workspace)' },
          },
          required: [],
        },
      },
      {
        name: 'switch_workspace',
        description: 'Switch to a different workspace',
        inputSchema: {
          type: 'object',
          properties: {
            workspaceName: { type: 'string' },
          },
          required: ['workspaceName'],
        },
      },
    ],
    resources: [
      {
        uri: 'atlas://workspace/active',
        name: 'Active Workspace',
        description: 'Currently active workspace configuration',
        mimeType: 'application/json',
      },
      {
        uri: 'atlas://workspace/all',
        name: 'All Workspaces',
        description: 'List of all configured workspaces',
        mimeType: 'application/json',
      },
    ],
  };
}