#!/usr/bin/env python3
# $Id: make-figures 238 2026-10-17 15:14:07Z peter $
#
# Copyright (C) 2026 Péter Felecan
# Assisted by Claude Sonnet 5.5 (Anthropic)
#
# This program is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

"""make-figures -- draw the figures of the documents from their sources.

A figure is a SOURCE at the top level of the project (the project is flat; the files of a figure share the prefix fig-):
  fig-NAME.dot   a Graphviz source: a drawing made for the document;
  fig-NAME.cmd   a RECIPE: a shell script that runs this project's own tools on a design of TestSchemes/ and leaves an SVG in $OUT (the working directory is a scratch
                 one with TestSchemes/ linked in, the tools of the project are on the PATH, $WORK is a scratch directory of its own): the picture is then the tool's
                 real output. A line "# crop: yes" crops the SVG to its drawing.
and two DERIVED files, built and never kept, like the PDF and HTML documents (.tar-exclude leaves them out, make clean removes them):
  fig-NAME.svg   the drawing, for the HTML documents;
  fig-NAME.pdf   the same drawing as a PDF, for the PDF documents (LaTeX's svg package needs Inkscape, which is not assumed).
`make pdf` and `make html` build them (Makefile.am: FIGURES, and the rules that call this script); `make figures` builds only them. The date that kicad-cli writes in the title of an SVG is
replaced by a fixed text.

  make-figures [--svg | --pdf] [NAME ...]   build the SVG (from the source), or the PDF (from the SVG), or both, of the figures fig-NAME; all the figures when no NAME is given
  make-figures --dir DIR ...                another directory of sources (the tests do); TestSchemes/ and the tools are always the project's own

Needs: dot (Graphviz) for a .dot; kicad-cli for a .cmd (the project's tools run it); python3 with cairosvg for the PDF and with PIL for the cropping.
"""

import argparse
import glob
import io
import os
import re
import shutil
import subprocess
import sys
import tempfile

HERE = os.path.dirname(os.path.abspath(__file__))


def dot_version():
    try:
        r = subprocess.run(["dot", "-V"], capture_output=True, text=True)
    except FileNotFoundError:
        return None
    m = re.search(r"version ([0-9.]+)", r.stderr + r.stdout)
    return m.group(1) if m else None


def draw_svg(dot_file):
    r = subprocess.run(["dot", "-Tsvg", dot_file], capture_output=True)
    if r.returncode != 0:
        raise RuntimeError(f"dot failed on {dot_file}: {r.stderr.decode('utf-8', 'replace').strip()}")
    return r.stdout


def kicad_available():
    return bool(shutil.which("kicad-cli") or os.environ.get("KICAD_CLI"))


def run_recipe(recipe):
    """The SVG that a recipe leaves in $OUT, as bytes."""
    work = tempfile.mkdtemp(prefix="make-figures-")
    try:
        os.symlink(os.path.join(HERE, "TestSchemes"), os.path.join(work, "TestSchemes"))
        dirs = [HERE]
        if not shutil.which("kicad-cli") and os.environ.get("KICAD_CLI"):
            os.makedirs(os.path.join(work, "bin"))
            wrapper = os.path.join(work, "bin", "kicad-cli")
            with open(wrapper, "w", encoding="utf-8") as f:
                f.write('#!/bin/bash\nexec ' + os.environ["KICAD_CLI"] + ' "$@"\n')
            os.chmod(wrapper, 0o755)
            dirs.append(os.path.join(work, "bin"))
        env = dict(os.environ, PATH=os.pathsep.join(dirs + [os.environ.get("PATH", "")]), WORK=work, OUT=os.path.join(work, "out.svg"))
        if os.environ.get("PACKPAY_COMPONENT_LIBS"):      # the recipe runs in a scratch directory: a relative library directory would not be found from there
            env["PACKPAY_COMPONENT_LIBS"] = os.pathsep.join(os.path.abspath(os.path.expanduser(d)) for d in os.environ["PACKPAY_COMPONENT_LIBS"].split(os.pathsep) if d)
        r = subprocess.run(["bash", "-ex", os.path.abspath(recipe)], cwd=work, env=env, capture_output=True, text=True, timeout=600)
        if r.returncode != 0 or not os.path.exists(env["OUT"]):
            trace = [ln for ln in r.stderr.splitlines() if ln.startswith("+ ")]
            output = [ln for ln in (r.stdout.splitlines() + [x for x in r.stderr.splitlines() if not x.startswith("+ ")]) if ln.strip()]
            at = trace[-1][2:] if trace else "(none: the recipe stopped before its first command)"
            why = "its last command left no SVG in $OUT" if r.returncode == 0 else f"exit status {r.returncode}"
            raise RuntimeError(f"the recipe {os.path.basename(recipe)} failed ({why}) at the command:\n    {at}\n  the output of the recipe ended with:\n    " + ("\n    ".join(output[-8:]) if output else "(nothing: the command printed no message)"))
        return open(env["OUT"], "rb").read()
    finally:
        shutil.rmtree(work, ignore_errors=True)


def crop_svg(svg):
    """The SVG with its viewBox cut down to the drawing (plus 3 user units of margin): find the box of the painted pixels of a rendering and map it back."""
    try:
        import cairosvg
        from PIL import Image
    except ImportError as e:
        raise RuntimeError(f"python3 cairosvg and PIL are needed to crop a picture ({e}); on Debian: apt install python3-cairosvg python3-pil")
    png = cairosvg.svg2png(bytestring=svg, scale=2.0)
    im = Image.open(io.BytesIO(png)).convert("RGBA")
    box = im.getchannel("A").getbbox()
    tag = re.search(rb"<svg\b[^>]*>", svg).group(0)
    vb = re.search(rb'viewBox="([^"]+)"', tag).group(1).decode().split()
    x0, y0, w, h = (float(v) for v in vb)
    sx, sy = w / im.size[0], h / im.size[1]
    m = 3.0
    nx, ny = x0 + box[0] * sx - m, y0 + box[1] * sy - m
    nw, nh = (box[2] - box[0]) * sx + 2 * m, (box[3] - box[1]) * sy + 2 * m
    new = re.sub(rb'viewBox="[^"]+"', b'viewBox="%.4f %.4f %.4f %.4f"' % (nx, ny, nw, nh), tag, count=1)
    unit = re.search(rb'\swidth="[0-9.]+([a-z]*)"', tag)
    if unit:      # a root that has a size (KiCad's: in mm) keeps it, now the size of the cropped drawing; one that has only a viewBox (pprender's) is sized by its container
        new = re.sub(rb'\swidth="[^"]+"', b' width="%.4f%s"' % (nw, unit.group(1)), new, count=1)
        new = re.sub(rb'\sheight="[^"]+"', b' height="%.4f%s"' % (nh, unit.group(1)), new, count=1)
    return svg.replace(tag, new, 1)


def finish_recipe_svg(svg, recipe_text):
    svg = re.sub(rb"(SVG Image created as \S+ date )\S+", rb"\1(date left out)", svg)
    if re.search(r"(?m)^# crop: yes\s*$", recipe_text):
        svg = crop_svg(svg)
    return svg


def sources(directory, names):
    found = sorted(glob.glob(os.path.join(directory, "fig-*.dot")) + glob.glob(os.path.join(directory, "fig-*.cmd")))
    if names:
        wanted = {n if n.startswith("fig-") else "fig-" + n for n in names}
        missing = wanted - {os.path.splitext(os.path.basename(s))[0] for s in found}
        if missing:
            raise RuntimeError("no source (fig-NAME.dot or fig-NAME.cmd) for: " + ", ".join(sorted(missing)))
        found = [s for s in found if os.path.splitext(os.path.basename(s))[0] in wanted]
    return found


def build_svg(src):
    base, kind = os.path.splitext(src)
    if kind == ".dot":
        if dot_version() is None:
            raise RuntimeError("dot (Graphviz) is not installed: the figure " + os.path.basename(base) + " cannot be drawn; on Debian: apt install graphviz")
        svg = draw_svg(src)
    else:
        if not kicad_available():
            raise RuntimeError("kicad-cli cannot be run (KiCad's command line tool: put it on the PATH or set KICAD_CLI): the figure " + os.path.basename(base) + " is made by running the project's tools")
        svg = finish_recipe_svg(run_recipe(src), open(src, encoding="utf-8").read())
    with open(base + ".svg", "wb") as f:
        f.write(svg)
    return base + ".svg"


def build_pdf(src):
    base = os.path.splitext(src)[0]
    if not os.path.exists(base + ".svg"):
        raise RuntimeError(os.path.basename(base) + ".svg does not exist: build it first (make-figures --svg)")
    try:
        import cairosvg
    except ImportError:
        raise RuntimeError("python3 cairosvg is not installed: the PDF of " + os.path.basename(base) + " cannot be drawn; on Debian: apt install python3-cairosvg")
    cairosvg.svg2pdf(bytestring=open(base + ".svg", "rb").read(), write_to=base + ".pdf")
    return base + ".pdf"


def main():
    ap = argparse.ArgumentParser(prog="make-figures", description="Draw the figures of the documents from their sources (Graphviz drawings and recipes).")
    ap.add_argument("names", nargs="*", help="figures, by name (fig-NAME or NAME); all when none")
    ap.add_argument("--dir", default=HERE)
    ap.add_argument("--svg", action="store_true", help="only the SVG, from the source")
    ap.add_argument("--pdf", action="store_true", help="only the PDF, from the SVG")
    args = ap.parse_args()
    both = not (args.svg or args.pdf)
    try:
        found = sources(args.dir, args.names)
        if not found:
            raise RuntimeError(f"no fig-*.dot or fig-*.cmd file in {args.dir}")
        for src in found:
            if args.svg or both:
                print("make-figures: drew " + os.path.basename(build_svg(src)))
            if args.pdf or both:
                print("make-figures: drew " + os.path.basename(build_pdf(src)))
    except RuntimeError as e:
        print(f"make-figures: {e}", file=sys.stderr)
        return 1
    return 0


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

# Local Variables:
# mode: python
# End:
