"""Example: Visual Regression Testing with Screenshot Comparison."""

import os
import shutil
from browser_hybrid import Browser

def main():
    # 1. Initialize browser
    browser = Browser()
    
    # Define paths
    baseline_path = "example_baseline.png"
    current_path = "example_current.png"
    diff_path = "example_diff.png"
    
    try:
        # --- PHASE 1: Capture Baseline ---
        print("--- PHASE 1: Capturing Baseline ---")
        browser.goto("https://example.com")
        
        # Take a baseline screenshot
        browser.screenshot(baseline_path)
        print(f"Captured baseline to {baseline_path}")
        
        # --- PHASE 2: Compare Identical Page ---
        print("\n--- PHASE 2: Comparing Identical Page ---")
        # Same page, should match exactly (0.0% difference)
        result = browser.screenshot_and_compare(current_path, baseline_path)
        
        print(f"Match: {result.match}")
        print(f"Difference: {result.diff_percentage:.2f}% ({result.diff_pixels} pixels)")
        
        # --- PHASE 3: Detect Changes ---
        print("\n--- PHASE 3: Detecting Changes (Modified Page) ---")
        
        # Let's modify the page content using JavaScript to simulate a UI change
        browser.evaluate("document.querySelector('h1').innerText = 'Changed Heading';")
        browser.evaluate("document.body.style.backgroundColor = 'lightgray';")
        
        # Compare and generate a diff image
        result = browser.screenshot_and_compare(
            path=current_path, 
            baseline=baseline_path, 
            threshold=0.01,  # Allow 0.01% for small variations
            output_diff=diff_path
        )
        
        print(f"Match: {result.match}")
        print(f"Difference: {result.diff_percentage:.2f}% ({result.diff_pixels} pixels)")
        
        if not result.match:
            print("Visual regression detected!")
            print(f"Diff image saved to {diff_path}")
            
        # --- PHASE 4: Visual Assertions ---
        print("\n--- PHASE 4: Visual Assertions ---")
        
        try:
            # This will raise AssertionError because we changed the heading
            browser.assert_visual_match(baseline_path, threshold=0.01)
        except AssertionError as e:
            print(f"Caught expected assertion error: {e}")

    finally:
        # Cleanup
        for path in [baseline_path, current_path, diff_path]:
            if os.path.exists(path):
                os.remove(path)
                print(f"Cleaned up {path}")

if __name__ == "__main__":
    main()
