#!/usr/bin/env python3
# tenkana, a spider that jumps from the checkpoints of your TeX document.
# Copyright © 2026 निरंजन (Niranjan)
#
# tenkana 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.
#
# tenkana 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 tenkana.  If not, see <https://www.gnu.org/licenses/>.
#
# tenkana was written by Claude, a large language model (LLM) made by
# Anthropic.  Courts are divided on whether material generated by an LLM can be
# protected by copyright.  Should it be found that the copyright claimant
# cannot hold copyright in any part of tenkana, that part is in the public
# domain.  Wherever copyright does hold, tenkana is distributed under the terms
# of the GNU General Public License, version 3 or (at your option) any later
# version, as stated above.

"""Write MESSAGES: every text tenkana can show, as plain text, for review.

    python3 tools/catalogue.py [examples.txt] > MESSAGES

Reads src/tenkana/messages.py (all messages), the help page (tenkana --help),
tenkana.1 (rendered with groff if available) and install.sh (installer
lines).  An optional examples file (captured real runs, sections starting
with "@@@ title") is included as is.
"""

import io
import textwrap
import os
import re
import shutil
import subprocess
import sys
import contextlib

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(ROOT, "src"))
from tenkana import messages as M  # noqa: E402
from tenkana import cli, __version__  # noqa: E402
from tenkana.common import banner  # noqa: E402


def groups():
    """(title, [(NAME, text), ...]) in source order, split at the
    '# ---- title ----' lines of messages.py."""
    src = open(
        os.path.join(ROOT, "src", "tenkana", "messages.py"), encoding="utf-8"
    ).read()
    out, title = [], None
    for line in src.splitlines():
        m = re.match(r"# -+ (.*?) -+$", line)
        if m:
            title = m.group(1)
            out.append((title, []))
            continue
        m = re.match(r"([A-Z_]+) = ", line)
        if m and out and m.group(1) != "NAME":
            out[-1][1].append((m.group(1), getattr(M, m.group(1))))
    return out


def shown(name, text):
    """How the message appears on screen (prefix on the first line)."""
    text = text.replace("{{", "\x00").replace("}}", "\x01")
    text = text.replace("\x00", "{").replace("\x01", "}")
    if name.startswith("D_"):
        return f"{M.NAME}[debug]: {text}"
    if name in ("VERSION", "USAGE", "HELP", "TAGLINE", "SPIDER", "LLM_NOTE"):
        return text
    if (
        name.startswith(("REASON_", "HOW_", "WHY_", "RUNS_", "SLOWER_RUNS"))
        or name == "V_CHANGED_FILE"
    ):
        return text  # a fragment, used inside other messages
    return "\n".join(f"{M.NAME}: {line}" for line in text.split("\n"))


def folded(text):
    """A message wider than this file, folded with a hanging indent (on
    screen it stays one line)."""
    out = []
    for line in text.split("\n"):
        if len(line) <= WIDTH:
            out.append(line)
            continue
        indent = " " * (line.index(" ") + 1)  # under the message's text
        out.extend(
            textwrap.wrap(
                line,
                WIDTH,
                subsequent_indent=indent,
                break_long_words=False,
                break_on_hyphens=False,
            )
        )
    return "\n".join(out)


def help_text():
    buf = io.StringIO()
    os.environ["COLUMNS"] = "80"
    with contextlib.redirect_stdout(buf):
        try:
            cli.main(["--help"])
        except SystemExit:
            pass
    return buf.getvalue()


def man_text():
    page = os.path.join(ROOT, "tenkana.1")
    if shutil.which("groff"):
        env = dict(os.environ, GROFF_NO_SGR="1")
        r = subprocess.run(
            [
                "groff",
                "-man",
                "-k",
                "-dAD=l",  # ragged right, like the other plain text
                "-rHY=0",  # and no hyphenation
                "-Tutf8",
                "-P-c",
                "-P-b",
                "-P-u",
                "-rLL=78n",
                page,
            ],
            capture_output=True,
            text=True,
            env=env,
        )
        if r.returncode == 0:
            return r.stdout
    return open(page).read()


def installer_lines():
    lines = []
    for line in open(os.path.join(ROOT, "install.sh")):
        for m in re.finditer(r'echo "((?:[^"\\]|\\.)*)"', line):
            lines.append(m.group(1).replace('\\"', '"').replace("\\$", "$"))
    return lines


WIDTH = 79


def para(text):
    return textwrap.fill(" ".join(text.split()), WIDTH) + "\n"


def heading(text, ch="="):
    return f"{text}\n{ch * len(text)}\n"


def notice():
    path = os.path.join(ROOT, "src", "tenkana", "__init__.py")
    lines = []
    for line in open(path, encoding="utf-8"):
        if not line.startswith("#"):
            break
        lines.append(line[2:].rstrip() if line.startswith("# ") else "")
    return "\n".join(lines[1:]) + "\n"  # without the first line


def main():
    o = []
    w = o.append
    w(
        heading(
            f"tenkana {__version__}: every message, the help page and the "
            "man page"
        )
    )
    w(
        para(
            "This file lists every text tenkana can print, so that the "
            "wording can be reviewed in one place.  It is generated by "
            "tools/catalogue.py from the source; all texts live in "
            "src/tenkana/messages.py."
        )
    )
    n = iter(range(1, 10))  # section numbers (the examples are optional)
    w(heading(f"{next(n)}. How tenkana's messages look", "-"))
    for t in (
        "TeX's own terminal output comes first, unchanged.",
        "tenkana's messages follow at the end.",
        'Each message is one line, starting with "tenkana: ", as Unix '
        "commands do; errors go to stderr.  With --silent only errors are "
        "printed.  Below, long messages are folded to fit this file.",
        "{t} and similar placeholders are filled in at run time.  Times "
        "are in seconds with one decimal (xx.xs).",
    ):
        w(
            textwrap.fill(
                " ".join(t.split()),
                WIDTH,
                initial_indent="  * ",
                subsequent_indent="    ",
            )
        )
    w("\nExample:\n")
    w(
        "Output written on talk.pdf (14 pages, 74150 bytes).\n"
        "Transcript written on talk.log.\n"
        "tenkana: jumped from ~xx.xs for a plain run to xx.xs "
        "(xx% less time).\n"
    )

    if len(sys.argv) > 1:
        w(heading(f"{next(n)}. Real examples (from actual runs)", "-"))
        text = open(sys.argv[1], encoding="utf-8").read()
        for block in text.split("@@@ ")[1:]:
            title, _, body = block.partition("\n")
            w(f"[{title.strip()}]\n")
            w(body.rstrip() + "\n")

    w(heading(f"{next(n)}. Every message", "-"))
    w(
        para(
            "Fragments (reasons, how a file changed, why snapshots are "
            "unavailable) are inserted into the messages that use them, "
            "as {reason}, {how}, {why} and {runs}."
        )
    )
    for title, items in groups():
        w(heading(title[0].upper() + title[1:], "."))
        for name, text in items:
            w(f"[{name}]")
            w(folded(shown(name, text)) + "\n")

    w(heading(f"{next(n)}. Installer (./install.sh)", "-"))
    w(banner(__version__) + "\n\n")
    w("\n".join(installer_lines()) + "\n")
    w(heading(f"{next(n)}. Help page (tenkana --help)", "-"))
    w(help_text().rstrip() + "\n")
    w(heading(f"{next(n)}. Man page (man tenkana)", "-"))
    w(man_text().rstrip() + "\n")
    w(heading("Copyright and license", "-"))
    w(notice())
    print("\n".join(o), end="")


if __name__ == "__main__":
    main()
