import { CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import { ConfigManager } from '../../config/config-manager.js';
import { WorkspaceDataStore } from '../workspace/store.js';
import path from 'path';
import { NodeFileSystemAdapter } from './file-system-adapter.js';
let configManager;
let workspaceStore;
let fsAdapter;
// Helper function to get repository context
async function getRepositoryContext(repositoryName) {
    const workspace = workspaceStore.getActiveWorkspace();
    if (!workspace) {
        // Single repository mode
        return {
            targetPath: process.cwd()
        };
    }
    let repository;
    if (repositoryName) {
        repository = workspace.repositories.find(r => r.name === repositoryName);
        if (!repository) {
            throw new Error(`Repository "${repositoryName}" not found in workspace "${workspace.name}"`);
        }
    }
    else {
        // Try to detect current repository from working directory
        const currentPath = process.cwd();
        repository = workspace.repositories.find(r => currentPath.startsWith(path.resolve(r.path)));
        // Default to primary repository if no match found
        if (!repository) {
            repository = workspace.repositories.find(r => r.primary) || workspace.repositories[0];
        }
    }
    const targetPath = repository ? path.resolve(repository.path) : workspace.rootPath;
    return {
        repository,
        workspace,
        targetPath
    };
}
export async function setupDocumentationTools(server, config, fs, workspace) {
    configManager = config || new ConfigManager();
    workspaceStore = workspace || new WorkspaceDataStore(configManager);
    if (!workspace) {
        await workspaceStore.init();
    }
    fsAdapter = fs || new NodeFileSystemAdapter();
    // Add documentation tool handlers
    server.setRequestHandler(CallToolRequestSchema, async (request) => {
        const { name, arguments: args } = request.params;
        if (!args) {
            throw new Error('No arguments provided');
        }
        switch (name) {
            case 'generate_readme': {
                const { projectName, description, features = [], techStack = [], installInstructions, usageExamples, repository } = args;
                const { repository: repoContext, workspace, targetPath } = await getRepositoryContext(repository);
                // Use repository-specific path or fall back to storage manager
                const readmePath = repoContext
                    ? path.join(targetPath, 'README.md')
                    : configManager.getStorageManager().getProjectFilePath('README.md');
                // Check if README already exists
                let existingContent = '';
                try {
                    existingContent = await fsAdapter.readFile(readmePath, 'utf-8');
                }
                catch (error) {
                    // File doesn't exist, which is fine
                }
                // Generate README content
                const readmeContent = generateReadmeContent({
                    projectName,
                    description,
                    features,
                    techStack,
                    installInstructions,
                    usageExamples,
                });
                // Save to user's project
                await fsAdapter.writeFile(readmePath, readmeContent, 'utf-8');
                return {
                    content: [
                        {
                            type: 'text',
                            text: `✅ README.md ${existingContent ? 'updated' : 'created'}${repoContext ? ` for repository "${repoContext.name}"` : ' in your project root'}!\n\n` +
                                `📄 Location: ${readmePath}\n` +
                                `${repoContext ? `📦 Repository: ${repoContext.name} (${repoContext.path})\n` : ''}` +
                                `${workspace ? `🏢 Workspace: ${workspace.name}\n` : ''}` +
                                `📝 Sections included:\n` +
                                `  • Project overview\n` +
                                `  • Features (${features.length} items)\n` +
                                `  • Tech stack (${techStack.length} items)\n` +
                                `  • Installation instructions\n` +
                                `  • Usage examples`,
                        },
                    ],
                    structured: {
                        file: 'README.md',
                        path: readmePath,
                        created: !existingContent,
                        repository: repoContext?.name,
                        workspace: workspace?.name,
                        sections: ['overview', 'features', 'tech-stack', 'installation', 'usage'],
                    },
                };
            }
            case 'generate_claude_config': {
                const { tddMode = 'strict', testCommand = 'npm test', lintCommand = 'npm run lint', buildCommand = 'npm run build', customInstructions = [], repository } = args;
                const { repository: repoContext, workspace, targetPath } = await getRepositoryContext(repository);
                // Use repository-specific path or fall back to storage manager
                const claudePath = repoContext
                    ? path.join(targetPath, 'CLAUDE.md')
                    : configManager.getStorageManager().getProjectFilePath('CLAUDE.md');
                const claudeContent = generateClaudeConfig({
                    tddMode,
                    testCommand,
                    lintCommand,
                    buildCommand,
                    customInstructions,
                });
                await fsAdapter.writeFile(claudePath, claudeContent, 'utf-8');
                return {
                    content: [
                        {
                            type: 'text',
                            text: `✅ CLAUDE.md created${repoContext ? ` for repository "${repoContext.name}"` : ' in your project root'}!\n\n` +
                                `📄 Location: ${claudePath}\n` +
                                `${repoContext ? `📦 Repository: ${repoContext.name}\n` : ''}` +
                                `${workspace ? `🏢 Workspace: ${workspace.name}\n` : ''}` +
                                `🤖 Claude Code will now:\n` +
                                `  • Enforce ${tddMode} TDD mode\n` +
                                `  • Run tests with: ${testCommand}\n` +
                                `  • Run linting with: ${lintCommand}\n` +
                                `  • Build project with: ${buildCommand}\n` +
                                (customInstructions.length > 0 ?
                                    `  • Follow ${customInstructions.length} custom instructions\n` : ''),
                        },
                    ],
                    structured: {
                        file: 'CLAUDE.md',
                        path: claudePath,
                        repository: repoContext?.name,
                        workspace: workspace?.name,
                        config: {
                            tddMode,
                            testCommand,
                            lintCommand,
                            buildCommand,
                            customInstructions,
                        },
                    },
                };
            }
            case 'create_documentation': {
                const { type, title, content, repository } = args;
                const { repository: repoContext, workspace, targetPath } = await getRepositoryContext(repository);
                // Determine file path based on type
                const filename = type === 'custom'
                    ? `${title.toLowerCase().replace(/\s+/g, '-')}.md`
                    : `${type.toUpperCase()}.md`;
                // Use repository-specific docs path or fall back to storage manager
                const docPath = repoContext
                    ? path.join(targetPath, 'docs', filename)
                    : configManager.getStorageManager().getProjectFilePath('docs', filename);
                // Ensure docs directory exists
                await fsAdapter.mkdir(path.dirname(docPath), { recursive: true });
                // Format content with proper markdown
                const formattedContent = `# ${title}\n\n${content}`;
                await fsAdapter.writeFile(docPath, formattedContent, 'utf-8');
                return {
                    content: [
                        {
                            type: 'text',
                            text: `✅ Documentation created: ${filename}${repoContext ? ` for repository "${repoContext.name}"` : ''}\n\n` +
                                `📄 Location: ${docPath}\n` +
                                `${repoContext ? `📦 Repository: ${repoContext.name}\n` : ''}` +
                                `${workspace ? `🏢 Workspace: ${workspace.name}\n` : ''}` +
                                `📝 Type: ${type}\n` +
                                `📏 Size: ${formattedContent.length} characters`,
                        },
                    ],
                    structured: {
                        file: filename,
                        path: docPath,
                        type,
                        title,
                        repository: repoContext?.name,
                        workspace: workspace?.name,
                        size: formattedContent.length,
                    },
                };
            }
            case 'list_repositories_docs': {
                const { workspaceName } = args;
                const workspace = workspaceName
                    ? workspaceStore.getWorkspace(workspaceName)
                    : workspaceStore.getActiveWorkspace();
                if (!workspace) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ No workspace found${workspaceName ? ` named "${workspaceName}"` : ''}`,
                            },
                        ],
                    };
                }
                const docsInfo = [];
                for (const repo of workspace.repositories) {
                    const repoDocsPath = path.join(repo.path, 'docs');
                    const readmePath = path.join(repo.path, 'README.md');
                    const claudePath = path.join(repo.path, 'CLAUDE.md');
                    const docs = [];
                    // Check for README
                    try {
                        await fsAdapter.access(readmePath);
                        docs.push('README.md');
                    }
                    catch { }
                    // Check for CLAUDE.md
                    try {
                        await fsAdapter.access(claudePath);
                        docs.push('CLAUDE.md');
                    }
                    catch { }
                    // Check docs directory
                    try {
                        const docFiles = await fsAdapter.readdir(repoDocsPath);
                        docs.push(...docFiles.filter(f => f.endsWith('.md')).map(f => `docs/${f}`));
                    }
                    catch { }
                    docsInfo.push({
                        repository: repo.name,
                        path: repo.path,
                        docs,
                        primary: repo.primary || false,
                    });
                }
                const docsText = docsInfo.map(info => `📦 ${info.repository}${info.primary ? ' (Primary)' : ''}\n` +
                    `   📁 ${info.path}\n` +
                    `   📄 Documentation: ${info.docs.length > 0 ? info.docs.join(', ') : 'None found'}`).join('\n\n');
                return {
                    content: [
                        {
                            type: 'text',
                            text: `📚 Documentation across repositories in "${workspace.name}":\n\n${docsText}`,
                        },
                    ],
                    structured: {
                        workspace: workspace.name,
                        repositories: docsInfo,
                    },
                };
            }
            case 'generate_cross_repo_readme': {
                const { workspaceName, projectName, description, includeAllRepos = true, repositories = [] } = args;
                const workspace = workspaceName
                    ? workspaceStore.getWorkspace(workspaceName)
                    : workspaceStore.getActiveWorkspace();
                if (!workspace) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ No workspace found${workspaceName ? ` named "${workspaceName}"` : ''}`,
                            },
                        ],
                    };
                }
                const targetRepos = includeAllRepos
                    ? workspace.repositories
                    : workspace.repositories.filter(r => repositories.includes(r.name));
                // Generate workspace-level README
                const readmeContent = generateWorkspaceReadme({
                    projectName,
                    description,
                    workspace,
                    repositories: targetRepos,
                });
                const readmePath = path.join(workspace.rootPath, 'README.md');
                await fsAdapter.writeFile(readmePath, readmeContent, 'utf-8');
                return {
                    content: [
                        {
                            type: 'text',
                            text: `✅ Cross-repository README.md created for workspace "${workspace.name}"!\n\n` +
                                `📄 Location: ${readmePath}\n` +
                                `🏢 Workspace: ${workspace.name}\n` +
                                `📦 Repositories included: ${targetRepos.length}\n` +
                                `   ${targetRepos.map(r => `• ${r.name}${r.primary ? ' (Primary)' : ''}`).join('\n   ')}\n\n` +
                                `🔗 The README includes links and descriptions for all repositories in your workspace.`,
                        },
                    ],
                    structured: {
                        file: 'README.md',
                        path: readmePath,
                        workspace: workspace.name,
                        repositories: targetRepos.map(r => ({ name: r.name, path: r.path, primary: r.primary })),
                    },
                };
            }
            case 'sync_docs_across_repos': {
                const { workspaceName, docType = 'contributing', sourceRepository, targetRepositories = [] } = args;
                const workspace = workspaceName
                    ? workspaceStore.getWorkspace(workspaceName)
                    : workspaceStore.getActiveWorkspace();
                if (!workspace) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ No workspace found${workspaceName ? ` named "${workspaceName}"` : ''}`,
                            },
                        ],
                    };
                }
                const sourceRepo = workspace.repositories.find(r => r.name === sourceRepository);
                if (!sourceRepo) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Source repository "${sourceRepository}" not found in workspace`,
                            },
                        ],
                    };
                }
                const filename = docType === 'custom' ? 'SHARED.md' : `${docType.toUpperCase()}.md`;
                const sourcePath = path.join(sourceRepo.path, 'docs', filename);
                // Read source document
                let sourceContent;
                try {
                    sourceContent = await fsAdapter.readFile(sourcePath, 'utf-8');
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Source document not found: ${sourcePath}`,
                            },
                        ],
                    };
                }
                const targetRepos = targetRepositories.length > 0
                    ? workspace.repositories.filter(r => targetRepositories.includes(r.name))
                    : workspace.repositories.filter(r => r.name !== sourceRepository);
                const syncedRepos = [];
                for (const repo of targetRepos) {
                    const targetPath = path.join(repo.path, 'docs', filename);
                    // Ensure docs directory exists
                    await fsAdapter.mkdir(path.dirname(targetPath), { recursive: true });
                    // Copy content with repository-specific modifications
                    const repoSpecificContent = sourceContent.replace(new RegExp(sourceRepository, 'g'), repo.name);
                    await fsAdapter.writeFile(targetPath, repoSpecificContent, 'utf-8');
                    syncedRepos.push({
                        name: repo.name,
                        path: targetPath,
                    });
                }
                return {
                    content: [
                        {
                            type: 'text',
                            text: `✅ Documentation synced across repositories!\n\n` +
                                `📄 Document: ${filename}\n` +
                                `📦 Source: ${sourceRepository}\n` +
                                `🔄 Synced to ${syncedRepos.length} repositories:\n` +
                                `${syncedRepos.map(r => `   • ${r.name}: ${r.path}`).join('\n')}\n\n` +
                                `💡 Repository names have been automatically updated in the synced documents.`,
                        },
                    ],
                    structured: {
                        docType,
                        filename,
                        sourceRepository,
                        syncedRepositories: syncedRepos,
                        workspace: workspace.name,
                    },
                };
            }
            default:
                // Not a documentation tool
                return null;
        }
    });
    return {
        tools: [
            {
                name: 'generate_readme',
                description: 'Generate a professional README.md for your project or specific repository',
                inputSchema: {
                    type: 'object',
                    properties: {
                        projectName: { type: 'string', description: 'Name of the project' },
                        description: { type: 'string', description: 'Project description' },
                        features: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'List of key features'
                        },
                        techStack: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'Technologies used'
                        },
                        installInstructions: { type: 'string', description: 'How to install the project' },
                        usageExamples: { type: 'string', description: 'Usage examples' },
                        repository: { type: 'string', description: 'Target repository name (for multi-repo workspaces)' },
                    },
                    required: ['projectName', 'description'],
                },
            },
            {
                name: 'generate_claude_config',
                description: 'Generate CLAUDE.md configuration for Claude Code in a specific repository',
                inputSchema: {
                    type: 'object',
                    properties: {
                        tddMode: {
                            type: 'string',
                            enum: ['strict', 'moderate', 'off'],
                            default: 'strict',
                            description: 'TDD enforcement level'
                        },
                        testCommand: { type: 'string', default: 'npm test', description: 'Command to run tests' },
                        lintCommand: { type: 'string', default: 'npm run lint', description: 'Command to run linter' },
                        buildCommand: { type: 'string', default: 'npm run build', description: 'Command to build project' },
                        customInstructions: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'Custom instructions for Claude'
                        },
                        repository: { type: 'string', description: 'Target repository name (for multi-repo workspaces)' },
                    },
                    required: [],
                },
            },
            {
                name: 'create_documentation',
                description: 'Create documentation files in your project or specific repository',
                inputSchema: {
                    type: 'object',
                    properties: {
                        type: {
                            type: 'string',
                            enum: ['api', 'architecture', 'contributing', 'changelog', 'custom'],
                            description: 'Type of documentation'
                        },
                        title: { type: 'string', description: 'Document title' },
                        content: { type: 'string', description: 'Document content in markdown' },
                        repository: { type: 'string', description: 'Target repository name (for multi-repo workspaces)' },
                    },
                    required: ['type', 'title', 'content'],
                },
            },
            {
                name: 'list_repositories_docs',
                description: 'List documentation across all repositories in a workspace',
                inputSchema: {
                    type: 'object',
                    properties: {
                        workspaceName: { type: 'string', description: 'Workspace name (defaults to active workspace)' },
                    },
                    required: [],
                },
            },
            {
                name: 'generate_cross_repo_readme',
                description: 'Generate a workspace-level README that covers multiple repositories',
                inputSchema: {
                    type: 'object',
                    properties: {
                        workspaceName: { type: 'string', description: 'Workspace name (defaults to active workspace)' },
                        projectName: { type: 'string', description: 'Name of the overall project' },
                        description: { type: 'string', description: 'Project description' },
                        includeAllRepos: { type: 'boolean', default: true, description: 'Include all repositories in workspace' },
                        repositories: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'Specific repositories to include (if includeAllRepos is false)'
                        },
                    },
                    required: ['projectName', 'description'],
                },
            },
            {
                name: 'sync_docs_across_repos',
                description: 'Synchronize documentation from one repository to others in the workspace',
                inputSchema: {
                    type: 'object',
                    properties: {
                        workspaceName: { type: 'string', description: 'Workspace name (defaults to active workspace)' },
                        docType: {
                            type: 'string',
                            enum: ['contributing', 'code-of-conduct', 'security', 'custom'],
                            default: 'contributing',
                            description: 'Type of document to sync'
                        },
                        sourceRepository: { type: 'string', description: 'Repository containing the source document' },
                        targetRepositories: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'Target repositories (defaults to all other repos in workspace)'
                        },
                    },
                    required: ['sourceRepository'],
                },
            },
        ],
        resources: [],
    };
}
function generateReadmeContent(options) {
    const { projectName, description, features, techStack, installInstructions, usageExamples } = options;
    let content = `# ${projectName}\n\n${description}\n\n`;
    if (features.length > 0) {
        content += `## Features\n\n${features.map(f => `- ${f}`).join('\n')}\n\n`;
    }
    if (techStack.length > 0) {
        content += `## Tech Stack\n\n${techStack.map(t => `- ${t}`).join('\n')}\n\n`;
    }
    content += `## Installation\n\n${installInstructions || '```bash\nnpm install\n```'}\n\n`;
    content += `## Usage\n\n${usageExamples || '```bash\nnpm start\n```'}\n\n`;
    content += `## Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\n\n`;
    content += `## License\n\nThis project is licensed under the MIT License.\n`;
    return content;
}
function generateWorkspaceReadme(options) {
    const { projectName, description, workspace, repositories } = options;
    let content = `# ${projectName}\n\n${description}\n\n`;
    content += `## Multi-Repository Workspace\n\n`;
    content += `This project consists of multiple repositories organized in a workspace structure:\n\n`;
    repositories.forEach(repo => {
        content += `### 📦 ${repo.name}${repo.primary ? ' (Primary)' : ''}\n\n`;
        content += `**Location**: \`${repo.path}\`\n\n`;
        // Try to read repository-specific README if it exists
        const repoReadmePath = path.join(repo.path, 'README.md');
        content += `[Repository README](${path.relative(workspace.rootPath, repoReadmePath)})\n\n`;
    });
    content += `## Getting Started\n\n`;
    content += `1. Clone all repositories:\n\`\`\`bash\n`;
    repositories.forEach(repo => {
        if (repo.remote) {
            content += `git clone ${repo.remote} ${repo.name}\n`;
        }
    });
    content += `\`\`\`\n\n`;
    content += `2. Navigate to the primary repository:\n\`\`\`bash\n`;
    const primaryRepo = repositories.find(r => r.primary) || repositories[0];
    content += `cd ${primaryRepo.name}\n\`\`\`\n\n`;
    content += `## Repository Dependencies\n\n`;
    repositories.forEach(repo => {
        if (repo.dependencies && repo.dependencies.length > 0) {
            content += `- **${repo.name}**: depends on ${repo.dependencies.join(', ')}\n`;
        }
    });
    if (repositories.every(r => !r.dependencies || r.dependencies.length === 0)) {
        content += `No inter-repository dependencies defined.\n`;
    }
    content += `\n## Workspace Management\n\n`;
    content += `This workspace is managed by [Atlas MCP](https://github.com/yourusername/atlas).\n\n`;
    content += `**Workspace Name**: ${workspace.name}\n`;
    content += `**Root Path**: ${workspace.rootPath}\n`;
    content += `**Repositories**: ${repositories.length}\n\n`;
    return content;
}
function generateClaudeConfig(options) {
    const { tddMode, testCommand, lintCommand, buildCommand, customInstructions } = options;
    let content = `# Claude Code Configuration\n\n`;
    content += `This file configures Claude Code's behavior for this project.\n\n`;
    content += `## Development Workflow\n\n`;
    content += `### Test-Driven Development (TDD)\n\n`;
    content += `**Mode**: ${tddMode}\n\n`;
    if (tddMode === 'strict') {
        content += `- Always write tests before implementation\n`;
        content += `- Ensure all tests are failing before writing code\n`;
        content += `- Follow Red-Green-Refactor cycle strictly\n\n`;
    }
    else if (tddMode === 'moderate') {
        content += `- Prefer writing tests first\n`;
        content += `- Ensure good test coverage\n`;
        content += `- Refactor with confidence\n\n`;
    }
    content += `### Commands\n\n`;
    content += `- **Run tests**: \`${testCommand}\`\n`;
    content += `- **Lint code**: \`${lintCommand}\`\n`;
    content += `- **Build project**: \`${buildCommand}\`\n\n`;
    content += `## Project Guidelines\n\n`;
    content += `1. Follow existing code patterns and conventions\n`;
    content += `2. Maintain consistent code style\n`;
    content += `3. Write meaningful commit messages\n`;
    content += `4. Keep documentation up to date\n`;
    if (customInstructions.length > 0) {
        content += `\n## Custom Instructions\n\n`;
        customInstructions.forEach((instruction, index) => {
            content += `${index + 1}. ${instruction}\n`;
        });
    }
    content += `\n## Atlas MCP Integration\n\n`;
    content += `This project uses Atlas MCP for project management. Available tools:\n\n`;
    content += `- Kanban boards for task management\n`;
    content += `- TDD enforcement and tracking\n`;
    content += `- Code intelligence and analysis\n`;
    content += `- Documentation generation\n`;
    return content;
}
//# sourceMappingURL=index.js.map