import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

export class VersionChecker {
  private currentVersion: string;
  
  constructor() {
    try {
      const packagePath = join(__dirname, '..', 'package.json');
      const packageJson = JSON.parse(readFileSync(packagePath, 'utf8'));
      this.currentVersion = packageJson.version;
    } catch {
      this.currentVersion = 'unknown';
    }
  }
  
  getCurrentVersion(): string {
    return this.currentVersion;
  }
  
  async checkForUpdates(): Promise<{
    hasUpdate: boolean;
    currentVersion: string;
    latestVersion?: string;
    updateMessage?: string;
  }> {
    try {
      // Check npm registry for latest version
      const response = await fetch('https://registry.npmjs.org/@living-software/ai-debug-local-mcp/latest');
      const data = await response.json();
      const latestVersion = data.version;
      
      const hasUpdate = this.isNewerVersion(latestVersion, this.currentVersion);
      
      if (hasUpdate) {
        return {
          hasUpdate: true,
          currentVersion: this.currentVersion,
          latestVersion,
          updateMessage: `🔄 **Update Available!**
          
Current: v${this.currentVersion}
Latest: v${latestVersion}

**To update:**
\`\`\`bash
npm install -g @living-software/ai-debug-local-mcp@latest
\`\`\`

**Or use auto-update script:**
\`\`\`bash
curl -sSL https://raw.githubusercontent.com/ai-debug/ai-debug-local-mcp/main/scripts/auto-update.sh | bash
\`\`\`

**New in v${latestVersion}:** Tidewave integration for Phoenix/Rails debugging!`
        };
      }
      
      return {
        hasUpdate: false,
        currentVersion: this.currentVersion
      };
    } catch (error) {
      return {
        hasUpdate: false,
        currentVersion: this.currentVersion
      };
    }
  }
  
  private isNewerVersion(latest: string, current: string): boolean {
    const latestParts = latest.split('.').map(n => parseInt(n));
    const currentParts = current.split('.').map(n => parseInt(n));
    
    for (let i = 0; i < Math.max(latestParts.length, currentParts.length); i++) {
      const latestPart = latestParts[i] || 0;
      const currentPart = currentParts[i] || 0;
      
      if (latestPart > currentPart) return true;
      if (latestPart < currentPart) return false;
    }
    
    return false;
  }
  
  getVersionInfo(): string {
    return `🔧 **AI Debug Local MCP** v${this.currentVersion}

**Features:**
- 🌊 Tidewave Phoenix/Rails integration
- 🎯 Comprehensive QA automation
- 🚀 Real-time debugging
- 📊 Performance auditing
- ♿ Accessibility testing

**Support:** https://github.com/ai-debug/ai-debug-local-mcp/issues`;
  }
}