"""Screenshots of tipin's terminal surfaces, taken from a real terminal.

Builds tipin, sets up a work folder from real files of the Go distribution, types
each command into a plain sh in a tmux pane at a desktop and a phone size, keeps
the pane as tmux printed it (out/screen-*.txt), and draws those cells in a
monospace face to shots/. Needs go, tmux and Playwright for Python.
"""

import html
import os
import shutil
import subprocess
import tempfile
import time

from playwright.sync_api import sync_playwright

TMUX = ["tmux", "-L", "tipin-shots", "-f", "/dev/null"]
SIZES = {"desktop": (1280, 900, 120, 40, 16), "phone": (390, 844, 46, 46, 13)}
GOROOT = subprocess.run(["go", "env", "GOROOT"], capture_output=True, text=True, check=True).stdout.strip()
DOC = os.path.join(GOROOT, "src", "fmt", "doc.go")
PRINT = os.path.join(GOROOT, "src", "fmt", "print.go")


def sh(cwd, command):
    subprocess.run(["sh", "-c", command], cwd=cwd, check=True, capture_output=True)


def setup(name, d):
    """Each surface gets its own folder, prepared with the same commands a person would type."""
    os.makedirs(d)
    if name in ("add", "show-top", "show", "print"):
        shutil.copy(DOC, os.path.join(d, "notes.md"))
    if name in ("show-top", "show", "print"):
        sh(d, 'tipin notes.md 6 "for analogous read akin"')
        sh(d, 'tipin notes.md 11 "for one blank line read two"')
        sh(d, 'tipin notes.md 12 "for The verbs read The verbs, in full"')
    if name == "show":
        # A week later: one slip withdrawn, a new version arrives with a line on
        # top, and line 12 rewritten.
        sh(d, "tipin drop notes.md 2")
        sh(d, "{ echo '// Vendored copy.'; sed 's/^The verbs:$/The verbs are:/' notes.md; } > n && mv n notes.md")
    if name == "check":
        os.makedirs(os.path.join(d, "a"))
        os.makedirs(os.path.join(d, "drafts"))
        os.makedirs(os.path.join(d, "vendor", "fmt"))
        os.makedirs(os.path.join(d, "copies"))
        shutil.copy(DOC, os.path.join(d, "a", "notes.md"))
        shutil.copy(PRINT, os.path.join(d, "vendor", "fmt", "print.go"))
        sh(d, 'tipin a/notes.md 6 "for analogous read akin"')
        sh(d, 'tipin a/notes.md 12 "for The verbs read The verbs, in full"')
        sh(d, "mv a/notes.md drafts/notes-v2.md")
        sh(d, 'tipin vendor/fmt/print.go 230 "for standard output read os.Stdout"')
        sh(d, "cp vendor/fmt/print.go copies/print.go")
        sh(d, "printf garbage > copies/old.tipin")
    return d


def tmux(*args):
    return subprocess.run(TMUX + list(args), check=True, capture_output=True, text=True).stdout


def screen(command, cwd, bindir, cols, rows):
    tmux("new-session", "-d", "-s", "s", "-x", str(cols), "-y", str(rows), "-c", cwd,
         "env", "-i", f"PATH={bindir}:/usr/bin:/bin", "TERM=xterm", "LANG=C.UTF-8", "PS1=$ ", "sh")
    time.sleep(0.5)
    tmux("send-keys", "-t", "s", "-l", command)
    tmux("send-keys", "-t", "s", "Enter")
    for _ in range(100):
        time.sleep(0.2)
        visible = tmux("capture-pane", "-p", "-t", "s")
        if visible.rstrip().split("\n")[-1] == "$":
            break
    else:
        raise SystemExit(f"the prompt did not come back after: {command}")
    tmux("kill-server")
    return visible.rstrip("\n") + "\n"


SURFACES = {
    "usage": "tipin",
    "add": 'tipin notes.md 6 "for analogous read akin"',
    "show-top": "tipin show notes.md | head -n 20",
    "show": "tipin show notes.md",
    "print": "tipin print notes.md",
    "check": "tipin check .",
}


def page(text, size):
    return f"""<!doctype html><meta charset="utf-8"><title>tipin</title>
<style>html,body{{margin:0;background:#FCF0DD;color:#1A1A1A}}
pre{{margin:0;padding:12px;font:{size}px/1.35 "DejaVu Sans Mono",ui-monospace,Menlo,monospace;white-space:pre}}</style>
<pre>{html.escape(text)}</pre>"""


def main():
    os.makedirs("shots", exist_ok=True)
    os.makedirs("out", exist_ok=True)
    subprocess.run(TMUX + ["kill-server"], capture_output=True)
    work = tempfile.mkdtemp(prefix="tipin-shots-")
    bindir = os.path.join(work, "bin")
    subprocess.run(["go", "build", "-o", os.path.join(bindir, "tipin"), "."], check=True)
    os.environ["PATH"] = bindir + ":" + os.environ["PATH"]
    try:
        with sync_playwright() as p:
            browser = p.chromium.launch()
            for label, (w, h, cols, rows, font) in SIZES.items():
                for name, command in SURFACES.items():
                    d = setup(name, os.path.join(work, f"{name}-{label}"))
                    text = screen(command, d, bindir, cols, rows)
                    with open(f"out/screen-{name}-{label}.txt", "w") as f:
                        f.write(text)
                    pg = browser.new_page(viewport={"width": w, "height": h})
                    errors = []
                    pg.on("console", lambda m: errors.append(m.text) if m.type == "error" else None)
                    pg.set_content(page(text, font))
                    wide = pg.evaluate("document.documentElement.scrollWidth")
                    out = f"shots/{name}-{label}.png"
                    pg.screenshot(path=out)
                    print(f"{out} {w}x{h}, {cols}x{rows} pane, page width {wide}, console errors {errors}")
                    pg.close()
            browser.close()
    finally:
        shutil.rmtree(work)


main()
