#!/bin/bash

echo "🎨 SamCloud FileBrowser - Live Development Server"
echo "================================================="
echo ""

# Project paths
PROJECT_DIR="/Volumes/SamMgmt/Containers/SamCloud FileBrowser"
CSS_FILE="$PROJECT_DIR/src/frontend/src/css/_samcloud.css"
PORT=8385

echo "📁 Project: $PROJECT_DIR"
echo "🎨 CSS File: $CSS_FILE"
echo "🌐 Dev Server: http://localhost:$PORT"
echo "🔗 FileBrowser: http://localhost:8383"
echo ""

# Create a simple HTTP server that serves the CSS file with live reload
cat > /tmp/live-css-server.py << 'EOF'
#!/usr/bin/env python3
import http.server
import socketserver
import os
import sys
from urllib.parse import urlparse

class LiveCSSHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/samcloud.css':
            # Serve the CSS file with no-cache headers
            css_file = sys.argv[1] if len(sys.argv) > 1 else '_samcloud.css'
            try:
                with open(css_file, 'r') as f:
                    css_content = f.read()
                
                self.send_response(200)
                self.send_header('Content-type', 'text/css')
                self.send_header('Cache-Control', 'no-cache, no-store, must-revalidate')
                self.send_header('Pragma', 'no-cache')
                self.send_header('Expires', '0')
                self.send_header('Access-Control-Allow-Origin', '*')
                self.end_headers()
                
                self.wfile.write(css_content.encode('utf-8'))
                print(f"✅ Served CSS file: {css_file}")
                
            except FileNotFoundError:
                self.send_error(404, f"CSS file not found: {css_file}")
        
        elif self.path == '/reload-script.js':
            # Serve a live reload script
            script = '''
// SamCloud Live CSS Reload
(function() {
    let lastModified = 0;
    
    function reloadCSS() {
        fetch('/samcloud.css?t=' + Date.now())
            .then(response => response.text())
            .then(css => {
                // Remove existing live CSS
                const existing = document.getElementById('live-samcloud-css');
                if (existing) existing.remove();
                
                // Add new CSS
                const style = document.createElement('style');
                style.id = 'live-samcloud-css';
                style.textContent = css;
                document.head.appendChild(style);
                
                console.log('🎨 SamCloud CSS reloaded!');
            })
            .catch(err => console.log('CSS reload failed:', err));
    }
    
    // Check for updates every 2 seconds
    setInterval(() => {
        fetch('/samcloud.css', { method: 'HEAD' })
            .then(response => {
                const modified = response.headers.get('last-modified');
                if (modified && modified !== lastModified) {
                    lastModified = modified;
                    reloadCSS();
                }
            });
    }, 2000);
    
    // Initial load
    reloadCSS();
    
    console.log('🚀 SamCloud Live CSS Reload active!');
})();
            '''
            
            self.send_response(200)
            self.send_header('Content-type', 'application/javascript')
            self.send_header('Cache-Control', 'no-cache')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            self.wfile.write(script.encode('utf-8'))
        
        else:
            # Serve a simple instructions page
            html = f'''
<!DOCTYPE html>
<html>
<head>
    <title>SamCloud CSS Live Development</title>
    <style>
        body {{ font-family: -apple-system, SF Pro Display, sans-serif; margin: 40px; }}
        .container {{ max-width: 600px; }}
        code {{ background: #f5f5f5; padding: 2px 6px; border-radius: 4px; }}
        .step {{ margin: 20px 0; padding: 15px; background: #f8f9fa; border-radius: 8px; }}
    </style>
</head>
<body>
    <div class="container">
        <h1>🎨 SamCloud CSS Live Development</h1>
        
        <div class="step">
            <h3>Step 1: Add Live Reload Script</h3>
            <p>Add this script to your FileBrowser page:</p>
            <code>&lt;script src="http://localhost:{PORT}/reload-script.js"&gt;&lt;/script&gt;</code>
        </div>
        
        <div class="step">
            <h3>Step 2: Open Developer Console</h3>
            <p>In your browser, open Developer Tools and run:</p>
            <code>
            const script = document.createElement('script');<br>
            script.src = 'http://localhost:{PORT}/reload-script.js';<br>
            document.head.appendChild(script);
            </code>
        </div>
        
        <div class="step">
            <h3>Step 3: Edit CSS</h3>
            <p>Now edit your CSS file and see changes instantly!</p>
            <p>CSS File: <code>{sys.argv[1] if len(sys.argv) > 1 else '_samcloud.css'}</code></p>
        </div>
        
        <p><strong>🔗 FileBrowser:</strong> <a href="http://localhost:8383" target="_blank">http://localhost:8383</a></p>
        <p><strong>🎨 Live CSS:</strong> <a href="/samcloud.css" target="_blank">http://localhost:{PORT}/samcloud.css</a></p>
    </div>
</body>
</html>
            '''
            
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(html.encode('utf-8'))

if __name__ == "__main__":
    PORT = 8385
    Handler = LiveCSSHandler
    
    with socketserver.TCPServer(("", PORT), Handler) as httpd:
        print(f"🚀 Live CSS server started at http://localhost:{PORT}")
        print(f"🎨 Serving CSS file: {sys.argv[1] if len(sys.argv) > 1 else '_samcloud.css'}")
        print("🛑 Press Ctrl+C to stop")
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\\n🛑 Server stopped")
EOF

# Make the Python server executable
chmod +x /tmp/live-css-server.py

echo "🚀 Starting live CSS development server..."
echo "📝 Edit your CSS file and see changes instantly!"
echo "🛑 Press Ctrl+C to stop the server"
echo ""

# Start the server
cd "$PROJECT_DIR/src/frontend/src/css"
python3 /tmp/live-css-server.py "$CSS_FILE"
