/**
 * 🌐 VIGTHORIA WEB ENVIRONMENT COMPATIBILITY LAYER
 * 
 * Provides seamless compatibility between desktop and web VS Code environments
 * Handles path resolution differences, caching strategies, and resource loading
 * 
 * Features:
 * - Universal path resolution for desktop/web environments
 * - Service worker cache management for web
 * - Resource URI handling with fallbacks
 * - Environment-specific optimization strategies
 * 
 * @author Vigthoria Compatibility Team
 * @version 2.0.0
 * @since 2025-08-31
 */

const vscode = require('vscode');

class WebEnvironmentCompatibilityLayer {
    constructor() {
        this.isWebEnvironment = this.detectWebEnvironment();
        this.pathResolver = this.initializePathResolver();
        this.cacheManager = this.initializeCacheManager();
        this.resourceManager = this.initializeResourceManager();
        
        console.log(`🌐 Web compatibility layer initialized (Environment: ${this.isWebEnvironment ? 'Web' : 'Desktop'})`);
    }

    /**
     * Detect if running in web VS Code environment
     */
    detectWebEnvironment() {
        try {
            // Check for web-specific indicators
            const isWeb = typeof window !== 'undefined' && 
                         typeof navigator !== 'undefined' &&
                         navigator.userAgent.includes('VS Code');
            
            // Also check VS Code API environment indicators
            const vsCodeEnv = vscode.env.appHost === 'codespaces' || 
                            vscode.env.appHost === 'github.dev' ||
                            vscode.env.remoteName === 'codespaces';
            
            return isWeb || vsCodeEnv || process.env.VSCODE_ENV === 'web';
        } catch (error) {
            console.warn('🌐 Environment detection fallback to desktop mode');
            return false;
        }
    }

    /**
     * Initialize path resolver for cross-environment compatibility
     */
    initializePathResolver() {
        if (this.isWebEnvironment) {
            return {
                join: (...segments) => {
                    // Web environment: use forward slashes
                    return segments.join('/').replace(/\/+/g, '/');
                },
                
                resolve: (filePath) => {
                    // Web environment: resolve relative to workspace
                    if (filePath.startsWith('/')) return filePath;
                    return `/workspace/${filePath}`;
                },
                
                dirname: (filePath) => {
                    const parts = filePath.split('/');
                    return parts.slice(0, -1).join('/') || '/';
                },
                
                basename: (filePath) => {
                    return filePath.split('/').pop() || '';
                },
                
                extname: (filePath) => {
                    const basename = filePath.split('/').pop() || '';
                    const dotIndex = basename.lastIndexOf('.');
                    return dotIndex > 0 ? basename.slice(dotIndex) : '';
                }
            };
        } else {
            // Desktop environment: use Node.js path module
            const path = require('path');
            return path;
        }
    }

    /**
     * Initialize cache manager for web compatibility
     */
    initializeCacheManager() {
        return {
            /**
             * Clear service worker cache for web environment
             */
            clearServiceWorkerCache: async () => {
                if (this.isWebEnvironment && 'serviceWorker' in navigator) {
                    try {
                        const registrations = await navigator.serviceWorker.getRegistrations();
                        for (const registration of registrations) {
                            await registration.unregister();
                        }
                        console.log('🌐 Service worker cache cleared');
                        return true;
                    } catch (error) {
                        console.warn('🌐 Failed to clear service worker cache:', error);
                        return false;
                    }
                }
                return true;
            },

            /**
             * Clear browser cache for web environment
             */
            clearBrowserCache: async () => {
                if (this.isWebEnvironment && 'caches' in window) {
                    try {
                        const cacheNames = await caches.keys();
                        await Promise.all(
                            cacheNames.map(cacheName => caches.delete(cacheName))
                        );
                        console.log('🌐 Browser caches cleared');
                        return true;
                    } catch (error) {
                        console.warn('🌐 Failed to clear browser cache:', error);
                        return false;
                    }
                }
                return true;
            },

            /**
             * Refresh cached resources
             */
            refreshCache: async () => {
                await this.clearServiceWorkerCache();
                await this.clearBrowserCache();
                
                // Force reload of cached modules in web environment
                if (this.isWebEnvironment) {
                    // Add cache-busting timestamp to future requests
                    const timestamp = Date.now();
                    window.vscode_cache_buster = timestamp;
                }
            }
        };
    }

    /**
     * Initialize resource manager for URI handling
     */
    initializeResourceManager() {
        return {
            /**
             * Get resource URI compatible with current environment
             */
            getResourceUri: (webview, resourcePath) => {
                try {
                    if (this.isWebEnvironment) {
                        // Web environment: handle resources differently
                        const workspaceFolder = vscode.workspace.workspaceFolders?.[0];
                        if (workspaceFolder) {
                            const resourceUri = vscode.Uri.joinPath(workspaceFolder.uri, resourcePath);
                            return webview.asWebviewUri(resourceUri);
                        }
                        
                        // Fallback: create URI from path
                        const uri = vscode.Uri.parse(`vscode-resource:/${resourcePath}`);
                        return webview.asWebviewUri(uri);
                    } else {
                        // Desktop environment: standard file URI
                        const path = require('path');
                        const resourceUri = vscode.Uri.file(path.join(__dirname, resourcePath));
                        return webview.asWebviewUri(resourceUri);
                    }
                } catch (error) {
                    console.error('🌐 Resource URI creation failed:', error);
                    // Fallback: return data URI or embedded content
                    return this.getFallbackResourceUri(resourcePath);
                }
            },

            /**
             * Get fallback resource URI for critical resources
             */
            getFallbackResourceUri: (resourcePath) => {
                // Return embedded data URIs for critical resources
                const fallbacks = {
                    'vigthoria-icon.png': 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',
                    'styles.css': 'data:text/css;base64,Ym9keSB7IGZvbnQtZmFtaWx5OiBBcmlhbCwgc2Fucy1zZXJpZjsgfQ==',
                    'script.js': 'data:text/javascript;base64,Y29uc29sZS5sb2coJ0ZhbGxiYWNrIHNjcmlwdCBsb2FkZWQnKTs='
                };
                
                return fallbacks[resourcePath] || 'data:text/plain;base64,';
            },

            /**
             * Load resource content with environment-specific handling
             */
            loadResourceContent: async (resourcePath) => {
                try {
                    if (this.isWebEnvironment) {
                        // Web environment: use fetch API
                        const workspaceFolder = vscode.workspace.workspaceFolders?.[0];
                        if (workspaceFolder) {
                            const resourceUri = vscode.Uri.joinPath(workspaceFolder.uri, resourcePath);
                            const content = await vscode.workspace.fs.readFile(resourceUri);
                            return new TextDecoder().decode(content);
                        }
                        throw new Error('No workspace folder available');
                    } else {
                        // Desktop environment: use fs module
                        const fs = require('fs');
                        const path = require('path');
                        const fullPath = path.join(__dirname, resourcePath);
                        return fs.readFileSync(fullPath, 'utf8');
                    }
                } catch (error) {
                    console.warn(`🌐 Failed to load resource ${resourcePath}:`, error);
                    return this.getFallbackContent(resourcePath);
                }
            },

            /**
             * Get fallback content for resources
             */
            getFallbackContent: (resourcePath) => {
                const fallbacks = {
                    'webview_script.js': `
                        console.log('Vigthoria WebView - Web compatibility mode');
                        const vscode = acquireVsCodeApi();
                        // Minimal functionality for web environment
                    `,
                    'styles.css': `
                        body { 
                            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                            margin: 0; 
                            padding: 20px;
                            background: var(--vscode-editor-background);
                            color: var(--vscode-editor-foreground);
                        }
                    `
                };
                
                return fallbacks[resourcePath] || '';
            }
        };
    }

    /**
     * Get HTML content with environment-specific optimizations
     */
    getCompatibleHtml(webview, htmlContent) {
        if (this.isWebEnvironment) {
            // Web environment optimizations
            htmlContent = this.optimizeForWeb(htmlContent);
        }
        
        // Add environment-specific meta tags
        const envMeta = this.isWebEnvironment 
            ? '<meta name="vigthoria-env" content="web">'
            : '<meta name="vigthoria-env" content="desktop">';
            
        // Add cache busting for web environment
        const cacheBuster = this.isWebEnvironment 
            ? `<script>window.vscode_cache_buster = ${Date.now()};</script>`
            : '';
            
        return `
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                ${envMeta}
                ${cacheBuster}
            </head>
            <body>
                ${htmlContent}
                ${this.getEnvironmentSpecificScript()}
            </body>
            </html>
        `;
    }

    /**
     * Optimize HTML content for web environment
     */
    optimizeForWeb(htmlContent) {
        // Remove desktop-specific features
        htmlContent = htmlContent.replace(/file:\/\/[^"']*/g, '');
        
        // Replace path separators
        htmlContent = htmlContent.replace(/\\/g, '/');
        
        // Add web-specific polyfills
        const webPolyfills = `
            <script>
                // Web environment polyfills
                if (typeof require === 'undefined') {
                    window.require = function(module) {
                        console.warn('Module require not available in web environment:', module);
                        return {};
                    };
                }
            </script>
        `;
        
        return webPolyfills + htmlContent;
    }

    /**
     * Get environment-specific script injection
     */
    getEnvironmentSpecificScript() {
        if (this.isWebEnvironment) {
            return `
                <script>
                    // Web environment compatibility
                    console.log('🌐 Vigthoria running in web environment');
                    
                    // Handle web-specific message passing
                    window.addEventListener('message', (event) => {
                        if (event.data.type === 'webview-ready') {
                            console.log('🌐 WebView ready in web environment');
                        }
                    });
                    
                    // Notify extension of web environment
                    if (typeof vscode !== 'undefined') {
                        vscode.postMessage({
                            type: 'environment-detected',
                            environment: 'web'
                        });
                    }
                </script>
            `;
        } else {
            return `
                <script>
                    // Desktop environment compatibility
                    console.log('🖥️ Vigthoria running in desktop environment');
                    
                    // Notify extension of desktop environment
                    if (typeof vscode !== 'undefined') {
                        vscode.postMessage({
                            type: 'environment-detected',
                            environment: 'desktop'
                        });
                    }
                </script>
            `;
        }
    }

    /**
     * Handle environment-specific messaging
     */
    handleEnvironmentMessage(message) {
        switch (message.type) {
            case 'environment-detected':
                console.log(`🌐 Environment confirmed: ${message.environment}`);
                break;
                
            case 'resource-load-failed':
                console.warn('🌐 Resource load failed, attempting fallback');
                return this.resourceManager.getFallbackResourceUri(message.resource);
                
            case 'cache-refresh-requested':
                return this.cacheManager.refreshCache();
                
            default:
                console.log('🌐 Unknown environment message:', message);
        }
    }

    /**
     * Get environment status for debugging
     */
    getEnvironmentStatus() {
        return {
            isWebEnvironment: this.isWebEnvironment,
            vsCodeHost: vscode.env.appHost,
            remoteName: vscode.env.remoteName,
            platform: process.platform,
            userAgent: typeof navigator !== 'undefined' ? navigator.userAgent : 'N/A',
            cacheSupport: 'caches' in (typeof window !== 'undefined' ? window : {}),
            serviceWorkerSupport: 'serviceWorker' in (typeof navigator !== 'undefined' ? navigator : {})
        };
    }
}

module.exports = { WebEnvironmentCompatibilityLayer };
