# Authors: The MNE-Python contributors.
# License: BSD-3-Clause
# Copyright the MNE-Python contributors.

import os
from pathlib import Path

from mne.utils import _replace_md5


def generate_contrib_avatars(app, config):
    """Render a template webpage with avatars generated by JS and a GitHub API call."""
    root = Path(app.srcdir)
    infile = root / "sphinxext" / "_avatar_template.html"
    outfile = root / "_templates" / "avatars.html.new"
    if os.getenv("MNE_ADD_CONTRIBUTOR_IMAGE", "false").lower() != "true":
        body = """\
<p>Contributor avators will appear here in full doc builds. Set \
MNE_ADD_CONTRIBUTOR_IMAGE=true in your environment to generate it.</p>"""
    else:
        from selenium import webdriver
        from selenium.common.exceptions import WebDriverException
        from selenium.webdriver.common.by import By
        from selenium.webdriver.support.ui import WebDriverWait

        try:
            options = webdriver.ChromeOptions()
            options.add_argument("--headless=new")
            driver = webdriver.Chrome(options=options)
        except WebDriverException:
            options = webdriver.FirefoxOptions()
            options.add_argument("-headless")
            driver = webdriver.Firefox(options=options)
        driver.get(f"file://{infile}")
        wait = WebDriverWait(driver, 20)
        wait.until(lambda d: d.find_element(by=By.ID, value="contributor-avatars"))
        body = driver.find_element(by=By.TAG_NAME, value="body").get_property(
            "innerHTML"
        )
        assert isinstance(body, str), type(body)
        driver.quit()
    with open(outfile, "w") as fid:
        fid.write(body)
    _replace_md5(str(outfile))


def setup(app):
    """Set up the Sphinx app."""
    app.connect("config-inited", generate_contrib_avatars)
    return
