#!/usr/bin/env python3
"""m4.sh — chat with the Qwen model on mini-m4 (mlx_lm.server :8080), no OpenCode.

  m4.sh                   interactive chat (keeps history; /new resets, /quit or Ctrl-D exits)
  m4.sh "question"        one-shot answer
  cat file | m4.sh "summarize this"   piped text is added to the prompt

Replies are plain text (no Markdown); M4_SYSTEM="" turns that off, or sets your own system prompt.
After each answer a stats line goes to stderr (M4_STATS=0 hides it).
"""
import json, os, re, shutil, sys, time, unicodedata, urllib.parse, urllib.request

URL = os.environ.get("M4_URL", "http://mini-m4:8080/v1/chat/completions")
MODEL = os.environ.get("M4_MODEL", "mlx-community/Qwen3.5-9B-4bit")
MAX_TOKENS = int(os.environ.get("M4_MAX_TOKENS", "4096"))
SYSTEM = os.environ.get("M4_SYSTEM",
    "Reply in plain text for a terminal. Do not use Markdown: no **bold**, no # headings, "
    "no tables. Use simple dashes for lists.")


class Unbold:
    """Removes ** from streamed text, even when a ** is split across two chunks."""
    def __init__(self):
        self.held = ""

    def feed(self, text):
        text = (self.held + text).replace("**", "")
        self.held = "*" if text.endswith("*") else ""
        return text[:-1] if self.held else text

    def flush(self):
        held, self.held = self.held, ""
        return held


def cells(s):
    """Terminal width of s (Korean/CJK characters take two cells)."""
    return sum(2 if unicodedata.east_asian_width(c) in "WF" else 1 for c in s)


class Wrap:
    """Word-wraps streamed text to the terminal width, so words are never split.
    List items ("- ", "1. ") wrap with a hanging indent."""
    def __init__(self, width):
        self.width, self.col, self.word, self.spaces = width, 0, "", ""
        self.hang, self.first = "", True

    def _word(self):
        out, w = "", self.word
        if not w:
            return out
        if self.first:                      # first word on this line: set hanging indent
            lead = self.spaces
            bullet = w in ("-", "*", "•") or re.fullmatch(r"\d+[.)]", w)
            self.hang = " " * (cells(lead) + (cells(w) + 1 if bullet else 0))
            out, self.col, self.first = lead, cells(lead), False
        elif self.col + cells(self.spaces) + cells(w) > self.width() and self.col > len(self.hang):
            out, self.col = "\n" + self.hang, len(self.hang)
        else:
            out, self.col = self.spaces, self.col + cells(self.spaces)
        self.word, self.spaces = "", ""
        self.col += cells(w)
        return out + w

    def feed(self, text):
        out = ""
        for ch in text:
            if ch == "\n":
                out += self._word() + "\n"
                self.col, self.spaces, self.first = 0, "", True
            elif ch in " \t":
                out += self._word()
                self.spaces += ch
            else:
                self.word += ch
        return out

    def flush(self):
        return self._word()


class NoWrap:
    def feed(self, text):
        return text

    def flush(self):
        return ""


def ask(messages):
    if SYSTEM:
        messages = [{"role": "system", "content": SYSTEM}] + messages
    unbold = Unbold()
    wrap = (Wrap(lambda: shutil.get_terminal_size().columns - 1)  # re-read per word: follows resizes
            if sys.stdout.isatty() else NoWrap())
    body = json.dumps({"model": MODEL, "messages": messages,
                       "max_tokens": MAX_TOKENS, "stream": True,
                       "stream_options": {"include_usage": True}}).encode()
    req = urllib.request.Request(URL, body, {"Content-Type": "application/json"})
    out, usage, first, meta = [], {}, None, {}
    start = time.monotonic()
    try:
        with urllib.request.urlopen(req, timeout=600) as r:
            for line in r:
                line = line.decode().strip()
                if not line.startswith("data:"):
                    continue
                data = line[5:].strip()
                if data == "[DONE]":
                    break
                chunk = json.loads(data)
                usage = chunk.get("usage") or usage
                meta.setdefault("model", chunk.get("model"))
                meta.setdefault("fp", chunk.get("system_fingerprint"))
                if not chunk.get("choices"):
                    continue
                delta = chunk["choices"][0].get("delta", {}).get("content") or ""
                if delta and first is None:
                    first = time.monotonic()
                delta = unbold.feed(delta)
                out.append(delta)
                print(wrap.feed(delta), end="", flush=True)
    except OSError as e:
        sys.exit(f"m4: can't reach {URL}: {e}")
    end = time.monotonic()
    tail = unbold.flush()
    out.append(tail)
    print(wrap.feed(tail) + wrap.flush(), flush=True)
    stats(usage, start, first, end, meta)
    return "".join(out)


def stats(u, start, first, end, meta):
    if os.environ.get("M4_STATS", "1") == "0":
        return
    first = first or end
    out, gen = u.get("completion_tokens", 0), end - first
    ver = (meta.get("fp") or "").split("-")[0]          # e.g. "0.32.2-..." -> mlx-lm 0.32.2
    model = (meta.get("model") or MODEL).split("/")[-1]  # drop "mlx-community/"
    host = urllib.parse.urlparse(URL).hostname
    parts = [host, f"mlx-lm {ver}".strip(), model]
    if out > 1 and gen > 0:
        parts.append(f"{(out - 1) / gen:.1f} tok/s")
    parts.append(f"{end - start:.1f}s total")
    dim = sys.stderr.isatty()
    print(("\033[2m" if dim else "") + "[" + " · ".join(parts) + "]" + ("\033[0m" if dim else ""),
          file=sys.stderr)


def main():
    prompt = " ".join(sys.argv[1:])
    if not sys.stdin.isatty():
        piped = sys.stdin.read()
        prompt = f"{prompt}\n\n{piped}" if prompt else piped
    if prompt.strip():
        ask([{"role": "user", "content": prompt}])
        return

    import readline  # noqa: F401  (line editing + up-arrow history)
    history = []
    print(f"m4.sh chat — {MODEL}  (/new to reset, /quit to exit)")
    while True:
        try:
            q = input("\n> ").strip()
        except (EOFError, KeyboardInterrupt):
            print()
            return
        if not q:
            continue
        if q in ("/quit", "/exit"):
            return
        if q == "/new":
            history = []
            print("(new conversation)")
            continue
        history.append({"role": "user", "content": q})
        try:
            history.append({"role": "assistant", "content": ask(history)})
        except KeyboardInterrupt:
            print("\n(interrupted)")
            history.pop()


if __name__ == "__main__":
    main()
