"""Does a downloaded copy of the big game work when it is opened from disk?

    python game_copy.py [path to gecko_dragonfly.html]

Tutorial 6 tells the reader to download gecko_dragonfly.html and open it. A copy has no
server beside it, so it must ask the game's public address. This opens the file with a
file:// address in a real browser engine, waits six seconds, and prints how many answers
the page got and where it asked.

With no path given it looks for gecko_dragonfly.html in the folder above this one, where
you would save your download. In the site's source it then looks in spark/gecko_game/.

It needs Playwright for Python: pip install playwright, then playwright install chromium.
"""
import json
import pathlib
import sys

ASSETS = pathlib.Path(__file__).resolve().parent.parent      # the tutorial's files: one folder up from checks/
PLACES = [ASSETS / "gecko_dragonfly.html",                                               # your download
          ASSETS.parent.parent / "spark" / "gecko_game" / "gecko_dragonfly.html"]        # the site's source
READ_STATE = ("() => ({answers: window.fieldBrain.answers, fails: window.fieldBrain.fails,"
              " origin: location.origin, status: document.getElementById('model').textContent})")


def main():
    from playwright.sync_api import sync_playwright
    found = [pathlib.Path(sys.argv[1]).resolve()] if len(sys.argv) > 1 else [place for place in PLACES if place.exists()]
    if not found or not found[0].exists():
        print("There is no gecko_dragonfly.html here. Download it from Tutorial 6, or give its path.")
        return 2
    page_file = found[0]
    asked = {}
    problems = []

    def count(response):
        if response.request.method == "POST":
            key = f"{response.url} {response.status}"
            asked[key] = asked.get(key, 0) + 1

    with sync_playwright() as play:
        browser = play.chromium.launch()
        page = browser.new_page(viewport={"width": 1300, "height": 900})
        page.on("pageerror", lambda error: problems.append("pageerror: " + str(error)))
        page.on("response", count)
        page.goto(page_file.as_uri())
        page.wait_for_timeout(6000)
        state = page.evaluate(READ_STATE)
        browser.close()
    print(json.dumps({"opened": page_file.as_uri(), **state, "asked": asked, "problems": problems}, indent=1))
    return 0 if state["answers"] > 0 and not problems else 1


if __name__ == "__main__":
    sys.exit(main())
