"""PyScript Builder's Python: a REPL in the page, for an AI agent in a browser extension, or for you.

Code runs in one namespace, which keeps its names between runs, and may change the page live. It
comes from the page's Python box, or from JavaScript: `await window.pyrepl.run(code)`, which the
page defines. Each run is numbered and kept whole in `window.pyrepl.history`, and goes in the
transcript, from either place, so you see what an agent ran.

Before the REPL starts, it installs the wheels the build's voltron.json lists, so its code may
import Voltron, then voltron_www's device shims, as Voltron's pages do. If that fails, the REPL
starts anyway, and says why.

`explore` gives the namespace its starting names: run `guide()` for the list. When Python is
ready, `<body>` gets `data-ready="true"`.
"""

import asyncio
import contextlib
import io
import json

from js import Object, console, location, window
from pyodide.code import eval_code_async
from pyodide.ffi import create_proxy, to_js
from pyscript import document, when

import dock
import explore
import principles_guard
from voltron_install import install

dock.start()  # The REPL's height: draggable from the first moment the page shows.

document.getElementById("status").textContent = "Installing Voltron's wheels"
try:
    await install(location.href)  # noqa: F704 (PyScript allows top-level await)
    # Before any device library loads: the `serial` stand-in over Web Serial, and a `time.sleep`
    # that doesn't freeze the page. Voltron's own pages do the same.
    from voltron_www import device_shims

    device_shims.install()
    installed = "Voltron's wheels are installed."
except Exception as error:  # Served from www/, with no build, there's no voltron.json.
    installed = f"Voltron's wheels didn't install: {error}."

TRANSCRIPT_LIMIT = 200

scope = explore.namespace()
_last_value = None  # The last run's value, for window.pyrepl.value().
one_at_a_time = asyncio.Lock()  # So two runs' output never mixes.


def element(tag: str, class_name: str = "", text: str = ""):
    node = document.createElement(tag)
    if class_name:
        node.className = class_name
    if text:
        node.textContent = text
    return node


def record(origin: str, code: str, output: str, ok: bool, held: bool = False, notes: str = "") -> int:
    """Keeps the run, whole and numbered, in window.pyrepl.history, and adds it to the transcript.
    If the page's own code removed the transcript, to the console. Returns the run's number."""
    run_id = int(window.pyrepl._record(origin, code, output, ok, notes, held))
    transcript = document.getElementById("transcript")
    if explore.missing(transcript):
        console.log(f"[Run {run_id} · {origin}] {code}\n{output}")
        return run_id
    entry = element("article", "entry")
    entry.dataset.status = "ok" if ok else "error"
    entry.dataset.run = str(run_id)
    outcome = " · held until the principles are read" if held else ("" if ok else " · error")
    entry.append(element("h3", text=f"Run {run_id} · {origin} · {len(output):,} chars{outcome}"))
    entry.append(element("pre", "code", code))
    if output:
        entry.append(element("pre", "output", output))
    if notes:
        entry.append(element("pre", "principles", notes))
    transcript.append(entry)
    while transcript.childElementCount > TRANSCRIPT_LIMIT:
        transcript.firstElementChild.remove()
    # Show the new run from its first line. A run longer than the view would otherwise show only
    # its last lines, with its start scrolled out of sight.
    if entry.offsetHeight > transcript.clientHeight:
        transcript.scrollTop = entry.offsetTop
    else:
        transcript.scrollTop = transcript.scrollHeight
    return run_id


async def run(code: str, origin: str) -> tuple[int, str, bool]:
    """Runs `code` in the namespace. Returns the run's number, what it printed, with the last
    expression's value, and whether it ran without an error."""
    async with one_at_a_time:
        # An import, dropped or chosen by the user, and the page's own controls (pyrepl.action), aren't
        # held or checked: a button the user clicks must keep working through a re-read.
        guarded = not origin.startswith(("Import", "Page action"))
        held = principles_guard.gate(code) if guarded else None
        if held is not None:
            return record(origin, code, held, False, held=True), held, False
        if guarded:
            principles_guard.start_run()
        global _last_value
        _last_value = None
        out, ok = io.StringIO(), True
        with contextlib.redirect_stdout(out), contextlib.redirect_stderr(out):
            try:
                result = await eval_code_async(code, globals=scope, filename=explore.REPL_FILENAME)
                _last_value = result
                if result is not None:
                    print(repr(result))
            except Exception as error:
                ok = False
                out.write(explore.short_traceback(error))
        output = out.getvalue()
        notes = ""
        if guarded:
            try:
                notes = principles_guard.notes(code)
            except Exception as error:  # A check must never break a run.
                console.warn(f"principles_guard: {error!r}")
        return record(origin, code, output, ok, notes=notes), output, ok


async def run_from_javascript(code, origin=None):
    """The runner behind `window.pyrepl.run(code, origin?)`, which the page defines. `origin` labels
    the run in the transcript. The page reads the output from its history, by the run's number."""
    run_id, _, _ = await run(str(code), "JavaScript" if origin is None else str(origin))
    return to_js({"id": run_id}, dict_converter=Object.fromEntries)


async def value_from_javascript(code):
    """The runner behind `window.pyrepl.value(code)`: runs `code`, and returns its last expression's
    value as JSON. A value JSON can't hold comes back as its repr."""
    run_id, _, ok = await run(str(code), "Value")
    try:
        text = json.dumps(_last_value, default=repr)
    except ValueError as error:  # A circular value.
        text = json.dumps(repr(_last_value))
    return to_js({"id": run_id, "ok": ok, "json": text}, dict_converter=Object.fromEntries)


async def run_typed() -> None:
    box = document.getElementById("code")
    code = box.value
    if not code.strip():
        return
    _, _, ok = await run(code, "Typed")
    if ok:
        box.value = ""
    box.focus()


@when("click", "#run")
async def on_run(event) -> None:
    await run_typed()


@when("keydown", "#code")
async def on_key(event) -> None:
    if event.key == "Enter" and (event.ctrlKey or event.metaKey):
        event.preventDefault()
        await run_typed()


window.pyrepl._attach(create_proxy(run_from_javascript), create_proxy(value_from_javascript))
for control in (document.getElementById("code"), document.getElementById("run")):
    control.disabled = False
document.getElementById("status").textContent = f"Ready. {installed}"

# export_project() and import_project(), the page as a drop zone for a project file, and the
# importer for an address ending in #import. It runs imported projects through window.pyrepl, so it
# loads after that.
import builder_io  # noqa: E402

scope.update(builder_io.repl_names())
scope["principles_read"] = principles_guard.principles_read
# With no confirmation word in principles.md, nothing is held.
window.builderGuard.read = principles_guard.confirmation_word() is None
stale = principles_guard.all_md_stale()
if stale:
    document.getElementById("status").textContent += f" {stale}"

document.body.dataset.ready = "true"
