"""Compare tmux pane and attached-client screens, then click after a resize."""

from __future__ import annotations

import argparse
import asyncio
import contextlib
import functools
import os
import pathlib
import shutil
import subprocess
import sys
import tempfile
import time

from libvt.aio import open_pty
from libvt.contrib.tmux import (
    build_tmux_capture_command,
    parse_tmux_version,
    tmux_profile,
)
from libvt.input import MouseAction, MouseButton, MouseEvent
from libvt.profiles import XTERM_PROFILE
from libvt.style import AnsiColor

START = (12, 84)
RESIZED = (14, 68)
PIN = (2, 3)


def _check(condition: bool, message: str) -> None:
    if not condition:
        raise AssertionError(message)


async def _run(*argv: str, env: dict[str, str], check: bool = True) -> str:
    """Read both pipes while the attached client continues to receive output."""
    proc = await asyncio.create_subprocess_exec(
        *argv, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=env
    )
    try:
        async with asyncio.timeout(5):
            output, error = await proc.communicate()
    finally:
        if proc.returncode is None:
            with contextlib.suppress(ProcessLookupError):
                proc.kill()
            await proc.communicate()
    if check and proc.returncode:
        raise subprocess.CalledProcessError(proc.returncode, argv, output, error)
    return output.decode().removesuffix("\n")


def _guest(role: str, trigger: str | None = None) -> None:
    if sys.platform == "win32":
        msg = "The tmux example requires a POSIX terminal"
        raise NotImplementedError(msg)

    import tty

    if role == "archive":
        for number in range(32):
            sys.stdout.write(f"Ledger entry {number:02}\n")
        sys.stdout.write("ARCHIVE LIVE\n")
        sys.stdout.flush()
        if trigger is not None:
            marker = pathlib.Path(trigger)
            while not marker.exists():
                time.sleep(0.01)
            sys.stdout.write("\x1b[2J\x1b[3J\x1b[HARCHIVE UPDATED\n")
            sys.stdout.flush()
        sys.stdin.read()
        return

    tty.setraw(0)
    os.write(1, b"\x1b[?1000;1006hPicker READY\x1b[3;4H[Pin]")
    for label, edge, line in (("press", b"M", 5), ("release", b"m", 6)):
        packet = bytearray()
        while (byte := os.read(0, 1)) not in (b"M", b"m"):
            if not byte:
                msg = "Incomplete mouse report"
                raise EOFError(msg)
            packet.extend(byte)
        _check(packet.startswith(b"\x1b[<") and byte == edge, f"Mouse bytes {packet!r}")
        button, col, row = map(int, packet[3:].split(b";"))
        _check(button == 0, f"Expected the left mouse button, received {button}")
        os.write(
            1, f"\x1b[{line};1HPicker {label} row={row - 1} col={col - 1};".encode()
        )
    key = os.read(0, 1)
    os.write(1, b"\x1b[7;1HPicker key " + key)
    sys.stdin.read()


async def _demo(
    binary: str,
    version: str,
    *,
    stale_origin: bool,
    no_focus_on_click: bool = False,
) -> None:
    env = dict(os.environ, TERM="xterm-256color")
    env.pop("TMUX", None)
    env.pop("TMUX_PANE", None)
    profile = tmux_profile(version)

    with tempfile.TemporaryDirectory(prefix="vt-tmux-") as folder:
        env["TMPDIR"] = folder
        socket = pathlib.Path(folder) / "s"
        trigger = pathlib.Path(folder) / "advance"
        server = [binary, "-u", "-S", str(socket), "-f", "/dev/null"]

        tm = functools.partial(_run, *server, env=env)

        commands = await tm("list-commands", "capture-pane")
        flags = commands.partition("[")[2].partition("]")[0]
        if "N" not in flags:
            msg = "This example requires a tmux build with capture-pane -N"
            raise RuntimeError(msg)

        async def geometry(pane: str) -> tuple[int, int, int, int]:
            value = await tm(
                "display-message",
                "-p",
                "-t",
                pane,
                "#{pane_top} #{pane_left} #{pane_height} #{pane_width}",
            )
            top, left, height, width = map(int, value.split())
            return top, left, height, width

        async def capture(pane: str) -> tuple[str, ...]:
            bundle = build_tmux_capture_command(pane, tmux_version=version)
            return bundle.parse(await tm(*bundle.argv), profile=profile).snapshot.lines

        guest = [sys.executable, "-u", str(pathlib.Path(__file__).resolve()), "--guest"]
        try:
            archive = await tm(
                "new-session",
                "-d",
                "-s",
                "desk",
                "-x",
                str(START[1]),
                "-y",
                str(START[0]),
                "-P",
                "-F",
                "#{pane_id}",
                *guest,
                "archive",
                *(("--trigger", str(trigger)) if "M" in flags else ()),
            )
            await tm("set", "-g", "status", "on")
            await tm("set", "-g", "status-position", "top")
            await tm("set", "-g", "mouse", "on")
            await tm("set", "-g", "mode-style", "fg=yellow,bg=blue")
            if no_focus_on_click:
                await tm("bind", "-T", "root", "MouseDown1Pane", "send-keys", "-M")
            picker = await tm(
                "split-window",
                "-dh",
                "-t",
                archive,
                "-P",
                "-F",
                "#{pane_id}",
                *guest,
                "picker",
            )
            await tm("select-pane", "-t", archive)
            async with open_pty(
                [*server, "attach-session", "-t", "=desk"],
                rows=START[0],
                cols=START[1],
                profile=XTERM_PROFILE,
                env=env,
            ) as client:
                await client.wait_for("ARCHIVE LIVE", timeout=6)
                await client.wait_for("Picker READY", timeout=6)

                # Compare the application grid with the rendered client.
                await tm("copy-mode", "-t", archive)
                await tm("send-keys", "-X", "-t", archive, "history-top")
                await tm("send-keys", "-X", "-t", archive, "begin-selection")
                await tm("send-keys", "-X", "-t", archive, "cursor-right")
                pane_y, pane_x, height, width = await geometry(archive)
                # This example puts one status row above the window.
                client_y = 1 + pane_y
                rows = slice(client_y, client_y + height)
                cols = slice(pane_x, pane_x + width)
                ledger = tuple(f"Ledger entry {index:02}" for index in range(height))
                visible = await client.wait_for(
                    lambda snap: (
                        snap[client_y, pane_x].style.bg == AnsiColor.BLUE
                        and snap[client_y, pane_x].style.fg == AnsiColor.YELLOW
                        and all(
                            row.startswith(label)
                            for row, label in zip(
                                snap[rows, cols].lines, ledger, strict=True
                            )
                        )
                    ),
                    timeout=6,
                )
                _check(visible[client_y, pane_x].text == "L", "Missing selected L")
                _check(
                    visible[client_y, pane_x + 2].style.bg != AnsiColor.BLUE,
                    "Selection extends past the marked cells",
                )
                app = await capture(archive)
                _check(
                    "ARCHIVE LIVE" in app and "Ledger entry 00" not in app,
                    "Pane capture did not show the live archive",
                )
                sys.stdout.write(
                    "app pane: ARCHIVE LIVE\nattached copy mode: Ledger entry 00\n"
                )

                # Read the mode grid at the current scroll offset.
                if "M" in flags:
                    # Advance the live pane while copy mode stays frozen on history.
                    trigger.write_text("go", encoding="ascii")
                    deadline = asyncio.get_running_loop().time() + 5
                    while "ARCHIVE UPDATED" not in await capture(archive):
                        if asyncio.get_running_loop().time() >= deadline:
                            msg = "Live archive did not update behind copy mode"
                            raise AssertionError(msg)
                        await asyncio.sleep(0.02)
                    scroll = int(
                        await tm(
                            "display-message", "-p", "-t", archive, "#{scroll_position}"
                        )
                    )
                    mode_rows = await tm(
                        "capture-pane",
                        "-p",
                        "-M",
                        "-t",
                        archive,
                        "-S",
                        str(-scroll),
                        "-E",
                        str(height - 1 - scroll),
                    )
                    live_rows = await tm(
                        "capture-pane",
                        "-p",
                        "-t",
                        archive,
                        "-S",
                        str(-scroll),
                        "-E",
                        str(height - 1 - scroll),
                    )
                    attached_rows = visible[rows, cols].lines
                    # Compare ledger labels before any copy-mode decorations.
                    label_width = len(ledger[0])
                    _check(
                        tuple(row[:label_width] for row in mode_rows.splitlines())
                        == tuple(row[:label_width] for row in attached_rows),
                        "Copy-mode rows differ from the attached viewport",
                    )
                    _check(
                        "Ledger entry 00" not in live_rows,
                        "Plain capture-pane matched frozen copy-mode history",
                    )
                    sys.stdout.write("mode capture at scroll offset: Ledger entry 00\n")

                # Leave copy mode before sending application input.
                await tm("send-keys", "-X", "-t", archive, "cancel")
                live_label = "ARCHIVE UPDATED" if "M" in flags else "ARCHIVE LIVE"
                await client.wait_for(live_label, timeout=6)
                old_left = (await geometry(picker))[1]
                client.resize(rows=RESIZED[0], cols=RESIZED[1])
                deadline = asyncio.get_running_loop().time() + 6
                while True:
                    native = await tm(
                        "list-clients",
                        "-F",
                        "#{client_height} #{client_width} "
                        "#{window_height} #{window_width}",
                    )
                    top, left, pane_rows, pane_cols = await geometry(picker)
                    snap = client.terminal.committed
                    outer_row = 1 + top + PIN[0]
                    outer_col = left + PIN[1]
                    if (
                        native
                        == f"{RESIZED[0]} {RESIZED[1]} {RESIZED[0] - 1} {RESIZED[1]}"
                        and left != old_left
                        and (snap.rows, snap.cols) == RESIZED
                        and 0 <= PIN[0] < pane_rows
                        and 0 <= PIN[1] < pane_cols
                        and snap[outer_row, outer_col].text == "["
                    ):
                        break
                    if asyncio.get_running_loop().time() >= deadline:
                        msg = (
                            f"Client and picker did not settle after resize: {native!r}"
                        )
                        raise AssertionError(msg)
                    await asyncio.sleep(0.025)

                active = await tm("display-message", "-p", "-t", "desk:", "#{pane_id}")
                _check(
                    active == archive,
                    f"Expected the archive to own focus, got {active}",
                )
                if stale_origin:
                    outer_col = old_left + PIN[1]

                # MouseEvent accepts zero-based outer coordinates and encodes them.
                for edge in (MouseAction.PRESS, MouseAction.RELEASE):
                    client.send_event(
                        MouseEvent(MouseButton.LEFT, edge, outer_row, outer_col)
                    )
                press_row = 1 + top + 4
                release_row = 1 + top + 5
                receipt = await client.wait_for(
                    lambda s: (
                        (
                            line := s[release_row, left : left + pane_cols].lines[0]
                        ).startswith("Picker release ")
                        and line.endswith(";")
                    ),
                    timeout=6,
                )
                want = f"Picker release row={PIN[0]} col={PIN[1]}"
                actual = receipt[release_row, left : left + pane_cols].lines[0]
                actual = actual.removesuffix(";")
                _check(
                    actual == want,
                    f"Picker reported {actual.removeprefix('Picker ')}, wanted {want}",
                )
                press_line = receipt[press_row, left : left + pane_cols].lines[0]
                _check(
                    press_line == f"Picker press row={PIN[0]} col={PIN[1]};",
                    f"Picker missed the button press: {press_line!r}",
                )
                active = await tm("display-message", "-p", "-t", "desk:", "#{pane_id}")
                if no_focus_on_click:
                    _check(
                        active == archive,
                        f"Expected focus to stay on archive, got {active}",
                    )
                    await tm("select-pane", "-t", picker)
                    active = await tm(
                        "display-message", "-p", "-t", "desk:", "#{pane_id}"
                    )
                _check(
                    active == picker, f"Expected the picker to own focus, got {active}"
                )
                if no_focus_on_click:
                    sys.stdout.write(
                        "focus after click: stayed on archive; "
                        "transferred via select-pane\n"
                    )
                client.send_key("v")
                await client.wait_for("Picker key v", timeout=6)
                # The child has received both button edges and the key.
                sys.stdout.write(f"Picker received press, release and key at {PIN}\n")
        finally:
            await tm("kill-server", check=False)


def _main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--tmux", default="tmux", help="tmux executable")
    parser.add_argument(
        "--stale-origin", action="store_true", help="Reuse the old pane origin"
    )
    parser.add_argument(
        "--no-focus-on-click",
        action="store_true",
        help="Send mouse events without moving focus, then focus explicitly",
    )
    parser.add_argument(
        "--guest", choices=("archive", "picker"), help=argparse.SUPPRESS
    )
    parser.add_argument("--trigger", help=argparse.SUPPRESS)
    args = parser.parse_args()
    if args.guest:
        _guest(args.guest, args.trigger)
    else:
        binary = shutil.which(args.tmux)
        if binary is None:
            parser.error(f"Cannot find tmux executable {args.tmux!r}")
        version = subprocess.check_output([binary, "-V"], text=True, timeout=5).strip()
        if parse_tmux_version(version) < (3, 1):
            parser.error("The example requires tmux 3.1 or newer with capture-pane -N")
        asyncio.run(
            _demo(
                binary,
                version,
                stale_origin=args.stale_origin,
                no_focus_on_click=args.no_focus_on_click,
            )
        )


if __name__ == "__main__":
    _main()
