import os
import sys
import tempfile
import subprocess
import time
import random

class BrowserNotFoundError(Exception):
    pass

class RenderError(Exception):
    pass

def _find_browser() -> str:
    if sys.platform == 'win32':
        paths = [
            r'C:\Program Files\Google\Chrome\Application\chrome.exe',
            r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe',
            r'C:\Program Files\Microsoft\Edge\Application\msedge.exe',
            r'C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe'
        ]
    elif sys.platform == 'darwin':
        paths = ['/Applications/Google Chrome.app/Contents/MacOS/Google Chrome']
    else:
        paths = ['/usr/bin/google-chrome', '/usr/bin/chromium-browser', '/usr/bin/chromium']
        
    for p in paths:
        if os.path.exists(p):
            return p
    raise BrowserNotFoundError("No compatible browser (Chrome/Edge) found on system.")

class CoreImR:
    """
    Advanced configuration class for rendering HTML to images.
    """
    def __init__(self, width: int = 1280, height: int = 720, transparent: bool = False, delay: int = 0, browser_path: str = None):
        self.width = width
        self.height = height
        self.transparent = transparent
        self.delay = delay
        self.browser_path = browser_path or _find_browser()

    def render(self, html: str, output_path: str) -> bool:
        fd, tmp_html = tempfile.mkstemp(suffix=f'_coreimr_{random.randint(1000, 9999)}.html')
        with os.fdopen(fd, 'w', encoding='utf-8') as f:
            f.write(html)
            
        try:
            abs_output = os.path.abspath(output_path)
            cmd = [
                self.browser_path,
                '--headless',
                '--disable-gpu',
                '--hide-scrollbars',
                f'--window-size={self.width},{self.height}',
                f'--screenshot={abs_output}'
            ]
            
            if self.transparent:
                cmd.append('--default-background-color=00000000')
            if self.delay > 0:
                cmd.append(f'--virtual-time-budget={self.delay}')
                
            cmd.append(f'file://{tmp_html}')
            
            result = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            if result.returncode != 0:
                raise RenderError(f"Browser command failed with exit code {result.returncode}")
                
            return True
        finally:
            try:
                os.remove(tmp_html)
            except Exception:
                pass

def render(html: str, output_path: str, **kwargs) -> bool:
    """
    Convenience function to render HTML string to an image file.
    Accepts kwargs: width, height, transparent, delay, browser_path
    """
    instance = CoreImR(**kwargs)
    return instance.render(html, output_path)
