"""GTKWave backend.

Two jobs: write a `.gtkw` save file, then launch GTKWave against it.

The save file is the useful half and is produced unconditionally, including on
a headless machine. A run over SSH or in CI still ends with a file the person
can open locally, so `launch=False` is a first-class outcome rather than a
failure.
"""

from __future__ import annotations

import os
import shutil
import subprocess
from pathlib import Path

from ...registry import backend
from ..debug.engine import Wave
from . import ShowWaveIn, ShowWaveOut

SAVEFILE = "view.gtkw"


def _display_available() -> tuple[bool, str | None]:
    if os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY"):
        return True, None
    return False, "no DISPLAY or WAYLAND_DISPLAY; the .gtkw save file was still written"


def write_savefile(path: Path, wave_path: Path, signals: list[tuple[str, int]],
                   center_time: int | None, span: int | None) -> None:
    """Write a `.gtkw` GTKWave reads.

    A bare list of signal names is silently ignored: GTKWave only adds a trace
    once it has seen a flag line saying how to draw it. `@28` is a single bit,
    `@22` a vector in hex, and a vector's name must carry its bit range or the
    name will not resolve. Getting this wrong opens an empty window, which
    looks like the tool worked and wastes the person's time.
    """
    lines = [
        "[*] Generated by ic show_wave",
        f'[dumpfile] "{wave_path}"',
        f'[savefile] "{path}"',
        "[sst_width] 260",
        "[signals_width] 200",
        "[sst_expanded] 1",
    ]

    scopes = {name.rsplit(".", 1)[0] for name, _ in signals if "." in name}
    for scope in sorted(scopes):
        lines.append(f"[treeopen] {scope}.")

    if center_time is not None:
        window = span or 0
        lines.append(f"[timestart] {max(0, center_time - window // 2)}")
        # `*<zoom> <marker> <cursor...>`: field two places the marker, so the
        # person lands on the cycle the agent was talking about.
        lines.append(f"*-16.0 {center_time} -1 -1 -1 -1 -1 -1")
    else:
        lines.append("[timestart] 0")

    for name, width in signals:
        if width > 1:
            lines.append("@22")  # vector, hex
            lines.append(f"{name}[{width - 1}:0]")
        else:
            lines.append("@28")  # single bit
            lines.append(name)

    path.write_text("\n".join(lines) + "\n")


@backend("view", "gtkwave", requires="gtkwave", version_cmd=["gtkwave", "--version"])
class GtkWaveViewer:
    def show_wave(self, params: ShowWaveIn, ctx) -> ShowWaveOut:
        wave_path = Path(ctx.resolve(params.wave)).resolve()
        # The header parse is cheap and gives real signal paths, so a caller
        # can pass `accumulator` and still get a save file GTKWave accepts.
        wave = Wave(_readable(wave_path))
        clock = wave.clock_signal(params.clock)

        # Widths travel with the names: the save file needs them to pick a
        # trace flag and to spell a vector's bit range.
        if params.signals:
            resolved = []
            for name in params.signals:
                match = wave.header.find(name)
                resolved.append((match.path, match.width) if match else (name, 1))
        else:
            top = min((s.path.count(".") for s in wave.header.signals), default=0)
            resolved = [
                (s.path, s.width) for s in wave.header.signals if s.path.count(".") == top
            ][:32]

        center_time = params.center_time
        if center_time is None and params.center_cycle is not None:
            center_time = wave.cycle_time(clock, params.center_cycle)

        span = None
        edges = wave.edges(clock, upto=params.zoom_cycles + 1)
        if len(edges) > 1:
            span = (edges[1] - edges[0]) * params.zoom_cycles

        savefile = ctx.run.artifacts / SAVEFILE
        write_savefile(savefile, wave_path, resolved, center_time, span)
        # Report where the file ends up, not where it is being written.
        final = ctx.run.final_artifact(SAVEFILE)

        command = f"gtkwave {wave_path} {final}"
        launched, reason = False, None
        if params.launch:
            ok, reason = _display_available()
            if ok and shutil.which("gtkwave"):
                subprocess.Popen(
                    ["gtkwave", str(wave_path), str(savefile)],  # pre-rename copy
                    stdout=subprocess.DEVNULL,
                    stderr=subprocess.DEVNULL,
                    start_new_session=True,
                )
                launched = True
        else:
            reason = "launch=false; save file only"

        return ShowWaveOut(
            savefile=str(final),
            wave_path=str(wave_path),
            command=command,
            launched=launched,
            reason=reason,
            signals=[name for name, _ in resolved],
            center_time=center_time,
        )


def _readable(path: Path) -> Path:
    """GTKWave reads FST directly; the header parser needs VCD."""
    if path.suffix.lower() == ".vcd":
        return path
    from ..debug.fst import to_vcd

    return to_vcd(path)
