#!/bin/bash

# Website Color and Font Analyzer Setup Script
# This script sets up the environment for the website analysis tool

echo "🎨 Website Color and Font Analyzer Setup"
echo "========================================"

# Check if Python is installed
if ! command -v python3 &> /dev/null; then
    echo "❌ Python 3 is not installed. Please install Python 3.7+ first."
    exit 1
fi

echo "✅ Python 3 found: $(python3 --version)"

# Check if pip is installed
if ! command -v pip3 &> /dev/null; then
    echo "❌ pip3 is not installed. Please install pip first."
    exit 1
fi

echo "✅ pip3 found"

# Check for Google Chrome
if ! command -v google-chrome &> /dev/null && ! command -v chrome &> /dev/null && ! command -v chromium &> /dev/null; then
    echo "⚠️  Google Chrome/Chromium not found. This is required for Selenium WebDriver."
    echo "📥 To install Chrome:"
    echo "   Ubuntu/Debian: wget -q -O - https://dl.google.com/linux/linux_signing_key.pub | sudo apt-key add -"
    echo "                   sudo apt-get update && sudo apt-get install google-chrome-stable"
    echo "   macOS: brew install --cask google-chrome"
    echo "   Windows: Download from https://www.google.com/chrome/"
    echo ""
    read -p "🤔 Continue without Chrome? (website analysis will not work) (y/n): " continue_without_chrome
    if [[ $continue_without_chrome != "y" && $continue_without_chrome != "Y" ]]; then
        echo "❌ Setup cancelled. Please install Chrome first."
        exit 1
    fi
else
    if command -v google-chrome &> /dev/null; then
        echo "✅ Google Chrome found: $(google-chrome --version)"
    elif command -v chrome &> /dev/null; then
        echo "✅ Chrome found: $(chrome --version)"
    else
        echo "✅ Chromium found: $(chromium --version)"
    fi
fi

# Create virtual environment (optional but recommended)
read -p "🤔 Do you want to create a virtual environment? (recommended) (y/n): " create_venv

if [[ $create_venv == "y" || $create_venv == "Y" ]]; then
    echo "📦 Creating virtual environment..."
    python3 -m venv website_analyzer_env
    source website_analyzer_env/bin/activate
    echo "✅ Virtual environment created and activated"
    echo "💡 To activate in future sessions: source website_analyzer_env/bin/activate"
fi

# Install Python dependencies
echo "📥 Installing Python dependencies..."

# Core dependencies
echo "📦 Installing core libraries..."
pip3 install requests beautifulsoup4 Pillow lxml

if [ $? -ne 0 ]; then
    echo "❌ Failed to install core dependencies"
    exit 1
fi

# Selenium for web scraping
echo "📦 Installing Selenium WebDriver..."
pip3 install selenium

if [ $? -ne 0 ]; then
    echo "❌ Failed to install Selenium"
    exit 1
fi

# CSS parser for CSS analysis
echo "📦 Installing CSS parser..."
pip3 install css-parser

if [ $? -eq 0 ]; then
    echo "✅ CSS parser installed successfully"
else
    echo "⚠️  CSS parser installation failed (basic CSS parsing will still work)"
fi

# Optional: WebDriver manager for automatic driver management
echo "📦 Installing WebDriver Manager (optional)..."
pip3 install webdriver-manager

if [ $? -eq 0 ]; then
    echo "✅ WebDriver Manager installed (automatic ChromeDriver management)"
else
    echo "⚠️  WebDriver Manager installation failed (manual ChromeDriver setup may be needed)"
fi

# Optional: Additional color analysis libraries
echo "📦 Installing optional color analysis libraries..."
pip3 install colorthief extcolors

if [ $? -eq 0 ]; then
    echo "✅ Advanced color analysis libraries installed"
else
    echo "⚠️  Some optional libraries failed to install (core functionality will still work)"
fi

# Make the script executable
chmod +x website_analyzer.py
echo "✅ Made website_analyzer.py executable"

# Create output directories
echo "📁 Creating output directories..."
mkdir -p website_analysis/{colors,fonts,palettes,screenshots,css,reports}
echo "✅ Output directories created"

# Test installation
echo "🧪 Testing installation..."

# Test Python imports
python3 -c "
import sys
try:
    import requests
    print('✅ requests imported successfully')
except ImportError:
    print('❌ requests import failed')

try:
    import selenium
    print('✅ selenium imported successfully') 
except ImportError:
    print('❌ selenium import failed')

try:
    import bs4
    print('✅ beautifulsoup4 imported successfully')
except ImportError:
    print('❌ beautifulsoup4 import failed')

try:
    import PIL
    print('✅ Pillow imported successfully')
except ImportError:
    print('❌ Pillow import failed')

try:
    import css_parser
    print('✅ css-parser imported successfully')
except ImportError:
    print('⚠️  css-parser import failed (basic CSS parsing will still work)')

# Test color science modules
try:
    import colorsys
    print('✅ colorsys (built-in) available')
except ImportError:
    print('❌ colorsys not available')
"

# Test Chrome/ChromeDriver
echo ""
echo "🔍 Testing Chrome WebDriver setup..."
python3 -c "
try:
    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    
    chrome_options = Options()
    chrome_options.add_argument('--headless')
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')
    
    driver = webdriver.Chrome(options=chrome_options)
    driver.get('https://www.google.com')
    title = driver.title
    driver.quit()
    print(f'✅ Chrome WebDriver test successful (page title: {title[:30]}...)')
except Exception as e:
    print(f'❌ Chrome WebDriver test failed: {e}')
    print('💡 This may be normal if ChromeDriver needs to be downloaded on first use')
"

# Test color analysis capabilities
echo ""
echo "🎨 Testing color analysis capabilities..."
python3 -c "
import colorsys

# Test color conversion
try:
    # Test HSL to RGB conversion
    h, l, s = 0.5, 0.5, 0.5
    r, g, b = colorsys.hls_to_rgb(h, l, s)
    print(f'✅ Color conversion test successful: HSL({h},{l},{s}) -> RGB({r:.2f},{g:.2f},{b:.2f})')
except Exception as e:
    print(f'❌ Color conversion test failed: {e}')

# Test hex color parsing
try:
    import re
    hex_pattern = r'#([0-9a-fA-F]{3,6})'
    test_css = 'color: #ff5722; background: #ffffff;'
    colors = re.findall(hex_pattern, test_css)
    print(f'✅ CSS color extraction test successful: found {len(colors)} colors')
except Exception as e:
    print(f'❌ CSS color extraction test failed: {e}')
"

echo ""
echo "🎉 Setup completed!"
echo ""
echo "📖 Usage examples:"
echo '   python3 website_analyzer.py analyze https://example.com'
echo '   python3 website_analyzer.py palette https://dribbble.com'
echo '   python3 website_analyzer.py stats'
echo ""
echo "🔧 Additional setup notes:"
echo "   • First run may take longer as ChromeDriver downloads automatically"
echo "   • For best results, ensure target websites are publicly accessible"
echo "   • Color analysis works best with CSS-heavy sites"
echo "   • Screenshots require sufficient disk space"
echo ""
echo "📚 For more information, see README.md"

# Check if everything is working
echo ""
echo "🔍 System check summary:"
echo "========================="
python3 -c "
import sys

def check_import(module_name):
    try:
        __import__(module_name)
        return '✅ Available'
    except ImportError:
        return '❌ Not found'

def check_command(cmd):
    import subprocess
    try:
        subprocess.run([cmd, '--version'], capture_output=True, check=True, timeout=5)
        return '✅ Available'
    except:
        return '❌ Not found'

print(f'Python: ✅ {sys.version.split()[0]}')
print(f'requests: {check_import('requests')}')
print(f'selenium: {check_import('selenium')}')
print(f'beautifulsoup4: {check_import('bs4')}')
print(f'Pillow: {check_import('PIL')}')
print(f'css-parser: {check_import('css_parser')}')
print(f'colorsys: {check_import('colorsys')}')

# Check Chrome
import subprocess
chrome_available = False
for cmd in ['google-chrome', 'chrome', 'chromium']:
    try:
        subprocess.run([cmd, '--version'], capture_output=True, check=True, timeout=5)
        chrome_available = True
        break
    except:
        continue

print(f'Chrome/Chromium: {'✅ Available' if chrome_available else '❌ Not found'}')

# Check output directory
import os
if os.path.exists('website_analysis'):
    print('Output directory: ✅ Created')
else:
    print('Output directory: ❌ Not found')
"

echo ""
echo "🚀 Ready to analyze website colors and fonts!"
echo ""
echo "⚠️  Important reminders:"
echo "   • Respect website terms of service and robots.txt"
echo "   • Use reasonable delays between requests"
echo "   • Consider website performance impact"
echo "   • Some colors/fonts may be in images (not extracted)"
echo ""
echo "🆘 If you encounter issues:"
echo "   • Check that Chrome is installed and updated"
echo "   • Verify internet connection and website accessibility"
echo "   • Ensure sufficient disk space for screenshots and CSS files"
echo "   • See README.md for detailed troubleshooting guide"

# Create a simple test script
echo ""
echo "📝 Creating test script..."
cat > test_analyzer.py << 'EOF'
#!/usr/bin/env python3
"""
Quick test script for Website Analyzer
"""

def test_color_analysis():
    """Test basic color analysis functions"""
    import colorsys
    import re
    
    print("🎨 Testing color analysis...")
    
    # Test color conversion
    try:
        h, l, s = 0.6, 0.5, 0.8  # Blue hue
        r, g, b = colorsys.hls_to_rgb(h, l, s)
        hex_color = f"#{int(r*255):02x}{int(g*255):02x}{int(b*255):02x}"
        print(f"   Color conversion: HSL -> RGB -> Hex = {hex_color}")
    except Exception as e:
        print(f"   ❌ Color conversion failed: {e}")
        return False
        
    # Test CSS color extraction
    try:
        test_css = """
        body { color: #333333; background-color: #ffffff; }
        .header { background: rgb(255, 87, 34); }
        .footer { color: hsl(210, 50%, 90%); }
        """
        
        hex_colors = re.findall(r'#([0-9a-fA-F]{3,6})', test_css)
        rgb_colors = re.findall(r'rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)', test_css)
        hsl_colors = re.findall(r'hsl\s*\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)', test_css)
        
        print(f"   CSS parsing: Found {len(hex_colors)} hex, {len(rgb_colors)} RGB, {len(hsl_colors)} HSL colors")
        
    except Exception as e:
        print(f"   ❌ CSS parsing failed: {e}")
        return False
        
    print("   ✅ Color analysis test passed")
    return True

def test_selenium_basic():
    """Test basic Selenium functionality"""
    print("🔧 Testing Selenium...")
    
    try:
        from selenium import webdriver
        from selenium.webdriver.chrome.options import Options
        
        chrome_options = Options()
        chrome_options.add_argument('--headless')
        chrome_options.add_argument('--no-sandbox')
        chrome_options.add_argument('--disable-dev-shm-usage')
        chrome_options.add_argument('--disable-gpu')
        
        print("   Initializing Chrome WebDriver...")
        driver = webdriver.Chrome(options=chrome_options)
        
        print("   Loading test page...")
        driver.get('data:text/html,<html><body style="color:red;background:blue;font-family:Arial">Test</body></html>')
        
        # Test style extraction
        body = driver.find_element("tag name", "body")
        color = body.value_of_css_property("color")
        background = body.value_of_css_property("background-color")
        font = body.value_of_css_property("font-family")
        
        print(f"   Extracted styles: color={color}, background={background}, font={font}")
        
        driver.quit()
        print("   ✅ Selenium test passed")
        return True
        
    except Exception as e:
        print(f"   ❌ Selenium test failed: {e}")
        return False

if __name__ == "__main__":
    print("🧪 Running Website Analyzer Tests")
    print("=================================")
    
    success = True
    success &= test_color_analysis()
    success &= test_selenium_basic()
    
    print("")
    if success:
        print("🎉 All tests passed! Website Analyzer is ready to use.")
        print("📝 Try: python3 website_analyzer.py analyze https://example.com")
    else:
        print("❌ Some tests failed. Check the error messages above.")
        print("💡 See README.md for troubleshooting help.")
EOF

chmod +x test_analyzer.py
echo "✅ Test script created: test_analyzer.py"
echo "   Run with: python3 test_analyzer.py" 