import { promises as fs } from 'fs';
import path from 'path';
export class ClaudeCodeIntegration {
    configManager;
    claudeMdPath;
    memoryPath;
    constructor(configManager) {
        this.configManager = configManager;
        this.claudeMdPath = path.join(process.cwd(), 'CLAUDE.md');
        this.memoryPath = path.join(process.cwd(), '.atlas', 'claude-memory.json');
    }
    async setupIntegration(config, options = {}) {
        const filesCreated = [];
        const enabledFeatures = [];
        if (config.createCLAUDEmd) {
            // Backup existing CLAUDE.md if requested
            if (options.backupExisting) {
                try {
                    await this.createBackup();
                }
                catch {
                    // Backup failed or no file exists, continue
                }
            }
            await this.createCLAUDEmd();
            filesCreated.push('CLAUDE.md');
            enabledFeatures.push('Project documentation');
        }
        if (config.enableProjectMemory) {
            await this.initializeMemory();
            filesCreated.push('.atlas/claude-memory.json');
            enabledFeatures.push('Project memory');
        }
        if (config.enableContextSharing) {
            await this.setupContextSharing();
            enabledFeatures.push('Context sharing');
        }
        if (config.enableCodeSuggestions) {
            enabledFeatures.push('Code suggestions');
        }
        if (config.enableAutoDocumentation) {
            enabledFeatures.push('Auto-documentation');
        }
        return { filesCreated, enabledFeatures };
    }
    async createCLAUDEmd() {
        const existingContent = await this.getExistingCLAUDEmd();
        const sections = await this.generateCLAUDEmdSections();
        if (existingContent) {
            const mergedContent = await this.mergeCLAUDEmdContent(existingContent, sections);
            await fs.writeFile(this.claudeMdPath, mergedContent);
        }
        else {
            const content = this.formatCLAUDEmd(sections);
            await fs.writeFile(this.claudeMdPath, content);
        }
    }
    async getExistingCLAUDEmd() {
        try {
            return await fs.readFile(this.claudeMdPath, 'utf-8');
        }
        catch {
            return null;
        }
    }
    async mergeCLAUDEmdContent(existingContent, atlasSections) {
        // Check if this file was previously managed by Atlas
        const isAtlasManaged = existingContent.includes('Auto-generated by Atlas MCP');
        if (isAtlasManaged) {
            // Replace Atlas sections while preserving user additions
            return this.updateAtlasSections(existingContent, atlasSections);
        }
        else {
            // First time integration - preserve existing content and add Atlas sections
            return this.addAtlasToExisting(existingContent, atlasSections);
        }
    }
    updateAtlasSections(content, sections) {
        let updatedContent = content;
        // Update the timestamp
        const timestampRegex = /Last updated: [^\n]*/;
        updatedContent = updatedContent.replace(timestampRegex, `Last updated: ${new Date().toISOString()}`);
        // Update each Atlas section
        for (const section of sections) {
            const sectionRegex = new RegExp(`(## ${section.title}\\n\\n)[\\s\\S]*?(?=\\n## |\\n---\\n|$)`, 'g');
            const replacement = `$1${section.content}\n\n---\n`;
            if (sectionRegex.test(updatedContent)) {
                updatedContent = updatedContent.replace(sectionRegex, replacement);
            }
            else {
                // Section doesn't exist, add it before the Quick Commands section
                const quickCommandsIndex = updatedContent.indexOf('## Quick Commands for Claude Code');
                if (quickCommandsIndex !== -1) {
                    const newSection = `## ${section.title}\n\n${section.content}\n\n---\n\n`;
                    updatedContent = updatedContent.slice(0, quickCommandsIndex) + newSection + updatedContent.slice(quickCommandsIndex);
                }
                else {
                    // No Quick Commands section, add at the end
                    updatedContent += `\n## ${section.title}\n\n${section.content}\n\n---\n`;
                }
            }
        }
        return updatedContent;
    }
    addAtlasToExisting(existingContent, sections) {
        const atlasHeader = `
---

# 🤖 Atlas MCP Integration

> **Auto-generated by Atlas MCP** - Last updated: ${new Date().toISOString()}
> 
> The sections below are automatically maintained by Atlas MCP.
> Your existing content above is preserved and never modified.

`;
        const atlasSections = sections.map(section => `## ${section.title}\n\n${section.content}\n\n---\n`).join('\n');
        const atlasFooter = `
## Quick Commands for Claude Code

### Common Workflows
- \`create_feature_interactive\` - Start a new feature with TDD workflow
- \`generate_project_context\` - Refresh this documentation
- \`sync_claude_code_context\` - Update project context

### Project Management
- \`check_project_status\` - Get current project status
- \`init_atlas\` - Initialize Atlas in a new project
- \`list_project_templates\` - See available project templates

### Development Tools
- \`write_test\` - Create a new test with TDD guidance
- \`run_tests\` - Execute test suite
- \`create_documentation\` - Generate documentation

### Agent Orchestration
- \`create_agent_session\` - Start multi-agent collaboration
- \`apply_strategy\` - Use pre-built development strategies

### Repository Setup
- \`setup_git_repository\` - Configure Git with best practices
- \`generate_github_actions\` - Create CI/CD workflows
- \`setup_pre_commit_hooks\` - Configure code quality hooks

---

> 💡 **Tip**: Ask Claude Code to "follow our TDD workflow" or "use Atlas tools" for context-aware assistance.
`;
        return existingContent + atlasHeader + atlasSections + atlasFooter;
    }
    async generateCLAUDEmdSections() {
        const sections = [];
        // Project Overview
        sections.push({
            title: 'Project Overview',
            content: await this.generateProjectOverview(),
            priority: 1,
        });
        // Atlas MCP Integration
        sections.push({
            title: 'Atlas MCP Integration',
            content: await this.generateAtlasSection(),
            priority: 2,
        });
        // Development Workflows
        sections.push({
            title: 'Development Workflows',
            content: await this.generateWorkflowsSection(),
            priority: 3,
        });
        // Code Conventions
        sections.push({
            title: 'Code Conventions',
            content: await this.generateConventionsSection(),
            priority: 4,
        });
        // Available Tools
        sections.push({
            title: 'Available Atlas Tools',
            content: await this.generateToolsSection(),
            priority: 5,
        });
        // Project Status
        sections.push({
            title: 'Current Project Status',
            content: await this.generateStatusSection(),
            priority: 6,
        });
        // Data Access Rules
        sections.push({
            title: 'Data Access Rules',
            content: await this.generateDataAccessRulesSection(),
            priority: 7,
        });
        return sections.sort((a, b) => a.priority - b.priority);
    }
    formatCLAUDEmd(sections) {
        const header = `# Claude Code Project Configuration

This file provides Claude Code with comprehensive context about this project, 
including Atlas MCP integration, development workflows, and current status.

> 🤖 **Auto-generated by Atlas MCP** - Last updated: ${new Date().toISOString()}

---

`;
        const content = sections.map(section => `## ${section.title}\n\n${section.content}\n\n---\n`).join('\n');
        const footer = `
## Quick Commands for Claude Code

### Common Workflows
- \`create_feature_interactive\` - Start a new feature with TDD workflow
- \`generate_project_context\` - Refresh this documentation
- \`sync_claude_code_context\` - Update project context

### Project Management
- \`check_project_status\` - Get current project status
- \`init_atlas\` - Initialize Atlas in a new project
- \`list_project_templates\` - See available project templates

### Development Tools
- \`write_test\` - Create a new test with TDD guidance
- \`run_tests\` - Execute test suite
- \`create_documentation\` - Generate documentation

### Agent Orchestration
- \`create_agent_session\` - Start multi-agent collaboration
- \`apply_strategy\` - Use pre-built development strategies

---

> 💡 **Tip**: Ask Claude Code to "follow our TDD workflow" or "use Atlas tools" for context-aware assistance.
`;
        return header + content + footer;
    }
    async generateProjectOverview() {
        const storageManager = this.configManager.getStorageManager();
        let overview = '';
        try {
            const marker = await storageManager.loadProjectMarker();
            if (marker) {
                overview = `**Project**: ${marker.projectName}
**ID**: ${marker.projectId}
**Root**: ${marker.projectRoot}
**Initialized**: ${marker.createdAt}

`;
            }
        }
        catch {
            overview = '**Status**: Project not yet initialized with Atlas MCP\n\n';
        }
        // Detect project type
        try {
            const packageJson = await fs.readFile(path.join(process.cwd(), 'package.json'), 'utf-8');
            const pkg = JSON.parse(packageJson);
            overview += `**Type**: ${pkg.type || 'Node.js'} project
**Dependencies**: ${Object.keys(pkg.dependencies || {}).length}
**Dev Dependencies**: ${Object.keys(pkg.devDependencies || {}).length}

`;
        }
        catch {
            overview += '**Type**: Generic project\n\n';
        }
        overview += `**Purpose**: This project uses Atlas MCP for comprehensive project management, 
including TDD enforcement, agent orchestration, and documentation generation.`;
        return overview;
    }
    async generateAtlasSection() {
        return `This project is enhanced with **Atlas MCP**, providing:

### Core Features
- 🧪 **Test-Driven Development (TDD)** enforcement
- 📋 **Kanban board** management  
- 🤖 **Agent orchestration** for complex tasks
- 📚 **Auto-documentation** generation
- 🔍 **Code intelligence** and semantic search
- 🚀 **Project templates** and initialization

### Storage Location
- Data stored in: \`.atlas/\` directory
- Configuration: \`.atlas/config/\`
- Documentation: Always saved to project root

### Integration Benefits
- **Context-aware**: Claude Code understands your project structure and workflows
- **TDD-first**: All development follows test-driven principles
- **Collaborative**: Multi-agent sessions for complex problem solving
- **Documented**: Automatic documentation generation and maintenance`;
    }
    async generateWorkflowsSection() {
        const workflows = await this.getAvailableWorkflows();
        let section = `### Test-Driven Development (TDD)

**Our TDD Process:**
1. 🔴 **Red**: Write a failing test first
2. 🟢 **Green**: Write minimal code to pass
3. 🔵 **Refactor**: Improve code while keeping tests green

**TDD Commands:**
- \`write_test\` - Create new test cases
- \`run_tests\` - Execute test suite
- \`tdd_cycle\` - Guide through complete TDD cycle

### Git Workflow

**Branch Strategy:**
- \`main\` - Production-ready code
- \`develop\` - Integration branch
- \`feature/*\` - Feature development
- \`hotfix/*\` - Emergency fixes

### Available Workflows

`;
        workflows.forEach(workflow => {
            section += `#### ${workflow.workflowType}
${workflow.description}

**Steps:**
${workflow.steps.map((step, i) => `${i + 1}. ${step}`).join('\n')}

**Tools:** ${workflow.tools.join(', ')}

`;
        });
        return section;
    }
    async generateConventionsSection() {
        return `### Code Style
- **Language**: TypeScript with strict mode
- **Formatting**: Prettier with 2-space indentation
- **Linting**: ESLint with recommended rules
- **Testing**: Jest with TDD practices

### File Organization
\`\`\`
src/
├── modules/           # Feature modules
├── utils/            # Shared utilities  
├── types/            # Type definitions
├── tests/            # Test files
└── config/           # Configuration

docs/                 # Documentation
.atlas/           # Atlas MCP data
\`\`\`

### Naming Conventions
- **Files**: kebab-case (\`user-service.ts\`)
- **Functions**: camelCase (\`getUserById\`)
- **Classes**: PascalCase (\`UserService\`)
- **Constants**: UPPER_SNAKE_CASE (\`API_BASE_URL\`)

### Commit Messages
- **Format**: \`type(scope): description\`
- **Types**: feat, fix, docs, style, refactor, test, chore
- **Example**: \`feat(auth): add JWT token validation\``;
    }
    async generateToolsSection() {
        return `### Project Management
- \`init_atlas\` - Initialize Atlas in project
- \`check_project_status\` - Get project status
- \`create_board\` - Create Kanban board
- \`add_task\` - Add task to board

### Development Tools
- \`write_test\` - Create test with TDD guidance
- \`run_tests\` - Execute test suite
- \`setup_tdd_cycle\` - Initialize TDD workflow
- \`create_feature_interactive\` - Start new feature

### Documentation
- \`create_documentation\` - Generate docs
- \`update_readme\` - Update README.md
- \`generate_api_docs\` - Create API documentation

### Agent Orchestration
- \`create_agent_session\` - Start multi-agent session
- \`apply_strategy\` - Use development strategy
- \`assign_agent_task\` - Delegate to specialist agent

### Code Intelligence
- \`analyze_codebase\` - Perform semantic analysis
- \`find_similar_code\` - Find code patterns
- \`suggest_refactoring\` - Get refactoring suggestions

### Repository Setup
- \`setup_git_repository\` - Configure Git with best practices
- \`generate_github_actions\` - Create CI/CD workflows
- \`setup_pre_commit_hooks\` - Configure code quality hooks`;
    }
    async generateStatusSection() {
        const storageManager = this.configManager.getStorageManager();
        let status = '';
        try {
            const marker = await storageManager.loadProjectMarker();
            if (marker) {
                status = `✅ **Atlas Initialized**
- Project ID: ${marker.projectId}
- Initialized: ${new Date(marker.createdAt).toLocaleDateString()}

`;
            }
            else {
                status = `❌ **Not Initialized**
- Run \`init_atlas\` to initialize Atlas MCP

`;
            }
        }
        catch {
            status = '❓ **Status Unknown**\n\n';
        }
        // Check for key files
        const checks = [
            { file: 'package.json', description: 'Node.js project' },
            { file: 'tsconfig.json', description: 'TypeScript configuration' },
            { file: '.gitignore', description: 'Git ignore rules' },
            { file: 'README.md', description: 'Project documentation' },
            { file: 'jest.config.js', description: 'Test configuration' },
        ];
        status += '**Project Health:**\n';
        for (const check of checks) {
            try {
                await fs.access(path.join(process.cwd(), check.file));
                status += `✅ ${check.description}\n`;
            }
            catch {
                status += `❌ ${check.description}\n`;
            }
        }
        status += `\n**Last Updated**: ${new Date().toISOString()}`;
        return status;
    }
    async generateProjectContext(options) {
        const sections = [];
        if (options.includeStructure) {
            sections.push({
                title: 'Project Structure',
                content: await this.generateProjectStructure(),
                priority: 1,
            });
        }
        if (options.includeWorkflows) {
            sections.push({
                title: 'Development Workflows',
                content: await this.generateWorkflowsSection(),
                priority: 2,
            });
        }
        if (options.includeConventions) {
            sections.push({
                title: 'Code Conventions',
                content: await this.generateConventionsSection(),
                priority: 3,
            });
        }
        if (options.includeProgress) {
            sections.push({
                title: 'Current Progress',
                content: await this.generateProgressSection(),
                priority: 4,
            });
        }
        const markdown = this.formatCLAUDEmd(sections);
        return { markdown, sections };
    }
    async createWorkflow(workflow) {
        const fullWorkflow = {
            workflowType: workflow.workflowType || 'custom',
            description: workflow.description || 'Custom workflow',
            steps: workflow.steps || [],
            tools: workflow.tools || [],
            examples: workflow.examples || [],
            prerequisites: workflow.prerequisites || [],
        };
        // Save to memory
        await this.addWorkflowToMemory(fullWorkflow);
        return fullWorkflow;
    }
    async addWorkflowToCLAUDEmd(workflow) {
        let content = '';
        try {
            content = await fs.readFile(this.claudeMdPath, 'utf-8');
        }
        catch {
            await this.createCLAUDEmd();
            content = await fs.readFile(this.claudeMdPath, 'utf-8');
        }
        const workflowSection = `
#### ${workflow.workflowType}
${workflow.description}

**Steps:**
${workflow.steps.map((step, i) => `${i + 1}. ${step}`).join('\n')}

**Tools:** ${workflow.tools.join(', ')}
${workflow.prerequisites?.length ? `\n**Prerequisites:** ${workflow.prerequisites.join(', ')}` : ''}

`;
        // Find workflows section and add
        const workflowsIndex = content.indexOf('### Available Workflows');
        if (workflowsIndex !== -1) {
            const nextSectionIndex = content.indexOf('\n## ', workflowsIndex);
            const insertIndex = nextSectionIndex !== -1 ? nextSectionIndex : content.length;
            content = content.slice(0, insertIndex) + workflowSection + content.slice(insertIndex);
        }
        else {
            content += `\n### Available Workflows\n${workflowSection}`;
        }
        await fs.writeFile(this.claudeMdPath, content);
    }
    async syncContext() {
        const result = {
            structureUpdated: false,
            tasksUpdated: false,
            conventionsUpdated: false,
            docsUpdated: false,
            filesUpdated: [],
        };
        try {
            await this.createCLAUDEmd();
            result.docsUpdated = true;
            result.filesUpdated.push('CLAUDE.md');
        }
        catch {
            // Ignore errors
        }
        try {
            await this.updateMemory();
            result.structureUpdated = true;
            result.filesUpdated.push('.atlas/claude-memory.json');
        }
        catch {
            // Ignore errors
        }
        return result;
    }
    async generateSuggestions(request) {
        const suggestions = [];
        // Base suggestions based on request type
        switch (request.requestType) {
            case 'feature':
                suggestions.push({
                    title: 'Start with TDD',
                    description: 'Begin feature development with test-driven approach using our TDD workflow',
                    command: 'create_feature_interactive',
                    priority: 'high',
                    category: 'Development',
                });
                break;
            case 'testing':
                suggestions.push({
                    title: 'Write Tests First',
                    description: 'Create comprehensive tests before implementation',
                    command: 'write_test',
                    priority: 'high',
                    category: 'Testing',
                });
                break;
            case 'documentation':
                suggestions.push({
                    title: 'Generate Documentation',
                    description: 'Create comprehensive documentation for this module',
                    command: 'create_documentation',
                    priority: 'medium',
                    category: 'Documentation',
                });
                break;
            case 'refactor':
                suggestions.push({
                    title: 'Use Agent Orchestration',
                    description: 'Complex refactoring benefits from multi-agent approach',
                    command: 'create_agent_session',
                    priority: 'medium',
                    category: 'Refactoring',
                });
                break;
        }
        // Context-specific suggestions
        if (request.currentFile) {
            if (request.currentFile.includes('.test.') || request.currentFile.includes('.spec.')) {
                suggestions.push({
                    title: 'Run Specific Tests',
                    description: 'Execute tests for this file',
                    command: 'run_tests',
                    priority: 'high',
                    category: 'Testing',
                });
            }
        }
        return suggestions;
    }
    async generateProjectStructure() {
        // Implementation would scan the project directory
        return `\`\`\`
src/
├── modules/          # Feature modules
├── config/           # Configuration files
├── utils/            # Shared utilities
├── types/            # TypeScript definitions
└── tests/            # Test files

docs/                 # Documentation
.atlas/           # Atlas MCP data
\`\`\``;
    }
    async generateProgressSection() {
        return `**Current Sprint Status:**
- 🚧 Repository setup tools (in progress)
- ✅ Project templates completed
- ⏳ Business guidance tools (pending)
- ⏳ Agile management features (pending)

**Recent Updates:**
- Added comprehensive project templates
- Implemented agent orchestration
- Enhanced Claude Code integration

**Next Steps:**
1. Complete repository setup tools
2. Add security enhancements
3. Implement memory management
4. Build business guidance tools`;
    }
    async getAvailableWorkflows() {
        // Return some default workflows
        return [
            {
                workflowType: 'feature-development',
                description: 'Complete feature development with TDD approach',
                steps: [
                    'Write failing tests for the feature',
                    'Implement minimal code to pass tests',
                    'Refactor and optimize',
                    'Update documentation',
                    'Create pull request',
                ],
                tools: ['write_test', 'run_tests', 'create_documentation'],
            },
            {
                workflowType: 'bug-fix',
                description: 'Systematic approach to fixing bugs',
                steps: [
                    'Reproduce the bug with a test',
                    'Identify root cause',
                    'Fix with minimal changes',
                    'Verify fix with tests',
                    'Update documentation if needed',
                ],
                tools: ['write_test', 'run_tests', 'analyze_codebase'],
            },
        ];
    }
    async setupContextSharing() {
        // Implementation for context sharing setup
    }
    async initializeMemory() {
        const memory = {
            recentFiles: [],
            commonPatterns: [],
            conventions: {},
            workflows: [],
            lastUpdated: new Date().toISOString(),
        };
        const storageManager = this.configManager.getStorageManager();
        await storageManager.ensureStorageDirectories();
        await fs.writeFile(this.memoryPath, JSON.stringify(memory, null, 2));
    }
    async addWorkflowToMemory(workflow) {
        try {
            const memory = JSON.parse(await fs.readFile(this.memoryPath, 'utf-8'));
            memory.workflows.push(workflow);
            memory.lastUpdated = new Date().toISOString();
            await fs.writeFile(this.memoryPath, JSON.stringify(memory, null, 2));
        }
        catch {
            // Memory file doesn't exist, initialize it
            await this.initializeMemory();
            await this.addWorkflowToMemory(workflow);
        }
    }
    async updateMemory() {
        try {
            const memory = JSON.parse(await fs.readFile(this.memoryPath, 'utf-8'));
            memory.lastUpdated = new Date().toISOString();
            // Add logic to update recent files, patterns, etc.
            await fs.writeFile(this.memoryPath, JSON.stringify(memory, null, 2));
        }
        catch {
            await this.initializeMemory();
        }
    }
    async generateDataAccessRulesSection() {
        return `### 🚨 CRITICAL: Data Access Rules

**The \`.atlas/\` directory is PRIVATE to Atlas MCP**

⛔ **NEVER** access \`.atlas/\` directly in your code or file operations
✅ **ALWAYS** use Atlas MCP tools to interact with project data

### Correct Data Access Patterns

#### ❌ INCORRECT - Direct File Access
\`\`\`typescript
// WRONG - Never do this!
const data = fs.readFileSync('.atlas/boards.json');
const config = require('.atlas/config/project.json');
await fs.writeFile('.atlas/memory.json', content);
\`\`\`

#### ✅ CORRECT - Using MCP Tools
\`\`\`typescript
// RIGHT - Always use MCP tools
const boards = await mcp.call('list_boards');
const status = await mcp.call('check_project_status');
const memory = await mcp.call('search_memories', { query: 'feature' });
\`\`\`

### Available Data Access Tools

**Project Data:**
- \`check_project_status\` - Get project configuration and status
- \`init_atlas\` - Initialize project with proper structure

**Task Management:**
- \`list_boards\` - View kanban boards
- \`get_tasks\` - Retrieve tasks from boards
- \`add_task\` - Create new tasks
- \`update_task\` - Modify existing tasks

**Memory & Context:**
- \`store_memory\` - Save project knowledge
- \`search_memories\` - Query stored memories
- \`get_project_context\` - Retrieve project context

**Business Data:**
- \`perform_business_review\` - Get comprehensive business analysis
- \`get_business_guidance\` - Access business recommendations

**Development Data:**
- \`run_tests\` - Get test results
- \`analyze_code_quality\` - Access code metrics
- \`track_code_metrics\` - View historical metrics

### Why This Matters

1. **Data Integrity**: MCP tools ensure data consistency and validation
2. **Version Compatibility**: Tools handle data format changes automatically
3. **Project Isolation**: Each project's data remains properly isolated
4. **Security**: Access control and validation are enforced
5. **Consistency**: All data operations follow the same patterns

### Getting Help

If you need to access data not available through existing tools:
1. First check if a tool already exists: \`list_available_tools\`
2. Request a new tool if needed
3. Never bypass the MCP layer

Remember: The MCP server is the single source of truth for all project data!`;
    }
    async checkExistingCLAUDEmd() {
        try {
            const content = await fs.readFile(this.claudeMdPath, 'utf-8');
            const wasAtlasManaged = content.includes('Auto-generated by Atlas MCP');
            return {
                exists: true,
                wasAtlasManaged,
                backupCreated: false, // Will be set during setup if backup is created
            };
        }
        catch {
            return {
                exists: false,
                wasAtlasManaged: false,
                backupCreated: false,
            };
        }
    }
    async createBackup() {
        try {
            const content = await fs.readFile(this.claudeMdPath, 'utf-8');
            const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
            const backupPath = path.join(process.cwd(), `.atlas`, `claude-backup-${timestamp}.md`);
            // Ensure backup directory exists
            await fs.mkdir(path.dirname(backupPath), { recursive: true });
            await fs.writeFile(backupPath, content);
            return {
                backupPath,
                timestamp: new Date().toISOString(),
            };
        }
        catch (error) {
            throw new Error(`Failed to create backup: ${error.message}`);
        }
    }
    async restoreFromBackup(backupPath) {
        let actualBackupPath = backupPath;
        if (!actualBackupPath) {
            // Find the most recent backup
            const backupDir = path.join(process.cwd(), '.atlas');
            try {
                const files = await fs.readdir(backupDir);
                const backups = files
                    .filter(f => f.startsWith('claude-backup-') && f.endsWith('.md'))
                    .sort()
                    .reverse();
                if (backups.length === 0) {
                    throw new Error('No backups found');
                }
                actualBackupPath = path.join(backupDir, backups[0]);
            }
            catch {
                throw new Error('No backup directory or backups found');
            }
        }
        try {
            const backupContent = await fs.readFile(actualBackupPath, 'utf-8');
            await fs.writeFile(this.claudeMdPath, backupContent);
            return {
                backupPath: actualBackupPath,
                timestamp: new Date().toISOString(),
            };
        }
        catch (error) {
            throw new Error(`Failed to restore backup: ${error.message}`);
        }
    }
}
//# sourceMappingURL=integration.js.map