#!/usr/bin/env python3
"""mkchrbios — character bios live in markdown; this puts them into the C.

  mkchrbios build     [--doc DOC] [--src SRC]   markdown -> C
  mkchrbios check     [--doc DOC] [--src SRC]   exit 1 if the C is stale
  mkchrbios extract   [--doc DOC] [--src SRC]   C -> markdown
  mkchrbios selftest  [--doc DOC] [--src SRC]   run the failure matrix on a copy

The C side is the region between the sentinel comments in SRC. `build` never
parses C — it finds the two markers and splices — so nothing outside them can
move. `extract` does parse C, with line-anchored regexes, and refuses rather
than guessing.

Two kinds of bio:
  literal  the string is authored here and emitted as a C string literal
  lang     the string lives in the ROM's language bank; only the four
           L_* symbol names are emitted, and no text is duplicated here

stdlib only.
"""

import argparse, os, re, shutil, subprocess, sys, tempfile

DOC = "src/game/chrbios.md"
SRC = "src/game/training.c"
OPEN = "// >>> chrbios: generated from src/game/chrbios.md by tools/mkchrbios"
CLOSE = "// <<< chrbios"
INDENT = "\t\t"

def die(msg):
    sys.exit("mkchrbios: " + msg)

def write_atomic(path, text):
    """Write via a temp file in the same directory, then rename over.

    An interrupted write must not truncate the target. rename() is permitted
    on the session mount even where unlink() is not, and the rename consumes
    the temp file, so nothing is left behind. If rename is refused anyway,
    fall back to a direct write rather than failing the build.
    """
    d = os.path.dirname(os.path.abspath(path))
    fd, tmp = tempfile.mkstemp(dir=d, prefix=".mkchrbios.", suffix=".tmp")
    try:
        with os.fdopen(fd, "w") as f:
            f.write(text)
        os.replace(tmp, path)
    except OSError:
        with open(path, "w") as f:
            f.write(text)
        try:
            os.unlink(tmp)
        except OSError:
            pass

# ── C string escaping ────────────────────────────────────────────────

def c_unescape(s):
    out, i = [], 0
    while i < len(s):
        c = s[i]
        if c == "\\" and i + 1 < len(s):
            nxt = s[i + 1]
            out.append({"n": "\n", "t": "\t", '"': '"', "\\": "\\"}.get(nxt, "\\" + nxt))
            i += 2
        else:
            out.append(c)
            i += 1
    return "".join(out)

def c_escape(s):
    return s.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n").replace("\t", "\\t")

# ── description <-> markdown body ────────────────────────────────────

def desc_to_md(desc):
    out = []
    for b in desc.rstrip("\n").split("\n\n"):
        out.append("### " + b[1:-2].strip() if b.startswith("|") and b.endswith(" -") else b)
    return "\n\n".join(out)

def md_to_desc(md):
    out = []
    for b in md.strip("\n").split("\n\n"):
        out.append("|" + b[4:].strip() + " -" if b.startswith("### ") else b)
    return "\n\n".join(out) + "\n"

# ── the C region ─────────────────────────────────────────────────────

LITERAL_RE = re.compile(
    r'/\*(\d+)\*/\s*\{\s*\(uintptr_t\)"((?:[^"\\]|\\.)*)",'
    r'\s*\(uintptr_t\)"((?:[^"\\]|\\.)*)",'
    r'\s*\(uintptr_t\)"((?:[^"\\]|\\.)*)",'
    r'\s*\(uintptr_t\)"((?:[^"\\]|\\.)*)",\s*([A-Za-z0-9_]+)\s*\},')
LANG_RE = re.compile(
    r'/\*(\d+)\*/\s*\{\s*([A-Za-z0-9_]+),\s*([A-Za-z0-9_]+),\s*([A-Za-z0-9_]+),'
    r'\s*([A-Za-z0-9_]+),\s*([A-Za-z0-9_]+)\s*\},\s*(?://\s*(.*))?')

def read_region(src_text, src_path):
    try:
        a = src_text.index(OPEN)
        b = src_text.index(CLOSE, a)
    except ValueError:
        die("%s: sentinels not found. Add these around the bios[] entries:\n  %s\n  %s"
            % (src_path, OPEN, CLOSE))
    return src_text.index("\n", a) + 1, src_text.rindex("\n", 0, b) + 1

def parse_c(region):
    bios = []
    for line in region.splitlines():
        line = line.strip()
        if not line.startswith("/*"):
            continue
        m = LITERAL_RE.match(line)
        if m:
            bios.append(dict(index=int(m.group(1)), kind="literal",
                             name=c_unescape(m.group(2)), race=c_unescape(m.group(3)),
                             age=c_unescape(m.group(4)), desc=c_unescape(m.group(5)),
                             flags=m.group(6), note=""))
            continue
        m = LANG_RE.match(line)
        if m:
            bios.append(dict(index=int(m.group(1)), kind="lang",
                             name=(m.group(7) or "").strip() or "(unnamed)",
                             strings=[m.group(i) for i in range(2, 6)],
                             flags=m.group(6), note=(m.group(7) or "").strip()))
            continue
        die("cannot parse line in the generated region:\n  " + line)
    return bios

# ── emit ─────────────────────────────────────────────────────────────

def emit_c(bios):
    width = max(len("/*%d*/" % b["index"]) for b in bios)
    lines = []
    for b in bios:
        marker = ("/*%d*/" % b["index"]).ljust(width)
        if b["kind"] == "literal":
            lines.append('%s%s { (uintptr_t)"%s", (uintptr_t)"%s", (uintptr_t)"%s", (uintptr_t)"%s", %s },'
                         % (INDENT, marker, c_escape(b["name"]), c_escape(b["race"]),
                            c_escape(b["age"]), c_escape(b["desc"]), b["flags"]))
        else:
            note = (" // " + b["note"]) if b["note"] else ""
            lines.append("%s%s { %s, %s, %s, %s, %s },%s"
                         % (INDENT, marker, b["strings"][0], b["strings"][1],
                            b["strings"][2], b["strings"][3], b["flags"], note))
    return "\n".join(lines) + "\n"

def emit_md(bios, src_path):
    out = ["# Character bios", "",
           "Source of truth for every `struct chrbio` entry the port compiles.",
           "Edit here, then run `tools/mkchrbios build` to write it into",
           "`%s`. Never edit the generated region in the C by hand." % src_path, "",
           "Two kinds of entry:", "",
           "- **literal** — the text is authored in this document and compiled in as a",
           "  C string literal.",
           "- **lang** — the text lives in the ROM's own language bank and is *not*",
           "  copied here; only the four `L_*` symbol names are recorded, so the game",
           "  keeps showing it in the player's language.", "",
           "The field list is the run of `- **key** `value`` lines directly under a",
           "`##` heading. It ends at the first line that is not one, and everything",
           "after that is body — so a line in prose that looks like a field stays",
           "prose.", "",
           "Inside a bio, `###` becomes a `|Heading -` section and everything else is",
           "emitted verbatim — **a line break in this document is a line break in the",
           "game**, so keep a paragraph on one line unless you mean to wrap it.", ""]
    for b in bios:
        out += ["---", "", "## " + b["name"], "",
                "- **index** `%d`" % b["index"],
                "- **kind** `%s`" % b["kind"],
                "- **file** `%s`" % src_path,
                "- **symbol** `bios[%d]`" % b["index"],
                "- **flags** `%s`" % b["flags"]]
        if b["kind"] == "lang":
            out += ["- **strings** `%s`" % ", ".join(b["strings"]), "",
                    "_Text lives in the language bank; not duplicated here._", ""]
        else:
            out += ["- **race** `%s`" % b["race"], "- **age** `%s`" % b["age"], "",
                    desc_to_md(b["desc"]), ""]
    return "\n".join(out).rstrip("\n") + "\n"

# ── parse the markdown ───────────────────────────────────────────────

FIELD_RE = re.compile(r"^- \*\*([a-z]+)\*\* `(.*)`\s*$")
KNOWN = ("kind", "flags", "race", "age")

def parse_md(text):
    bios, cur, body, in_fields = [], None, [], False

    def flush():
        if cur is None:
            return
        if "index" not in cur:
            die("'%s' has no `- **index**` field" % cur["name"])
        if cur["kind"] == "literal":
            lines = body[:]
            while lines and not lines[-1].strip():
                lines.pop()
            if lines and lines[-1].strip() == "---":   # the separator, not prose
                lines.pop()
            cur["desc"] = md_to_desc("\n".join(lines).strip("\n"))
        bios.append(cur)

    for line in text.split("\n"):
        if line.startswith("## "):
            flush()
            cur = dict(name=line[3:].strip(), kind="literal", flags="0", note="")
            body, in_fields = [], True
            continue
        if cur is None:
            continue
        if in_fields:
            if not line.strip():
                continue                                # blanks do not end the block
            m = FIELD_RE.match(line)
            if m:
                k, v = m.group(1), m.group(2)
                if k == "strings":
                    cur["strings"] = [s.strip() for s in v.split(",")]
                elif k == "index":
                    if not v.strip().isdigit():
                        die("'%s' has a non-numeric index: %r" % (cur["name"], v))
                    cur["index"] = int(v)
                elif k in KNOWN:
                    cur[k] = v
                continue
            in_fields = False                           # first non-field line: body from here
        body.append(line)
    flush()

    if not bios:
        die("no bios found — the document has no `## Name` sections. Refusing to "
            "empty the generated region.")
    bios.sort(key=lambda b: b["index"])
    for i, b in enumerate(bios):
        if b["index"] != i:
            die("index %d is out of sequence (expected %d) for '%s'" % (b["index"], i, b["name"]))
        if b["kind"] == "lang":
            b["note"] = b["name"]
            if len(b.get("strings", [])) != 4:
                die("'%s' is kind lang but does not list four strings" % b["name"])
    return bios

# ── selftest ─────────────────────────────────────────────────────────

def selftest(doc_path, src_path):
    """Run the failure matrix against copies. Touches nothing real."""
    me = os.path.abspath(__file__)
    tmp = tempfile.mkdtemp(prefix="mkchrbios-selftest-")
    doc, src = os.path.join(tmp, "chrbios.md"), os.path.join(tmp, "training.c")
    shutil.copy(doc_path, doc)
    shutil.copy(src_path, src)
    good_doc, good_src = open(doc).read(), open(src).read()

    def run(cmd):
        p = subprocess.run([sys.executable, me, cmd, "--doc", doc, "--src", src],
                           capture_output=True, text=True)
        return p.returncode, (p.stdout + p.stderr)

    def reset(d=None, s=None):
        open(doc, "w").write(d if d is not None else good_doc)
        open(src, "w").write(s if s is not None else good_src)

    results = []
    def case(name, ok, detail=""):
        results.append((name, ok, detail))

    # 1. round trip is byte exact
    reset()
    run("extract"); run("build")
    rc, _ = run("check")
    case("round trip byte exact", rc == 0 and open(src).read() == good_src)

    # 2. nothing outside the sentinels moves
    reset(re.sub(r"- \*\*age\*\* `[^`]*`", "- **age** `MOVED`", good_doc, count=1))
    run("build")
    a, b = good_src, open(src).read()
    lo_a, hi_a = read_region(a, src); lo_b, hi_b = read_region(b, src)
    case("build touches only the region", a[:lo_a] == b[:lo_b] and a[hi_a:] == b[hi_b:])

    # 3. a prose line that looks like a field stays prose
    reset(good_doc.replace("### Profile", "### Profile\n\n- **age** `99`", 1))
    rc, _ = run("build")
    body_kept = "- **age** `99`" in open(src).read()
    ages = re.findall(r'\(uintptr_t\)"99"', open(src).read())
    case("field-shaped prose stays prose", rc == 0 and body_kept and not ages)

    # 4. a --- inside prose survives
    reset(good_doc.replace("### Profile\n", "### Profile\n\nabove\n---\nbelow\n", 1))
    run("build")
    case("--- inside prose survives", "above\\n---\\nbelow" in open(src).read())

    # 5. a ## block with no index refuses
    reset(re.sub(r"(## [^\n]+\n\n)- \*\*index\*\* `\d+`\n", r"\1", good_doc, count=1))
    rc, out = run("build")
    case("missing index refuses", rc == 1 and "no `- **index**` field" in out, out.strip()[:60])

    # 6. an empty document refuses
    reset("")
    rc, out = run("build")
    case("empty document refuses", rc == 1 and "Refusing to empty" in out, out.strip()[:60])

    # 7. an out-of-sequence index refuses
    reset(good_doc.replace("- **index** `2`", "- **index** `9`", 1))
    rc, out = run("build")
    case("out-of-sequence index refuses", rc == 1 and "out of sequence" in out)

    # 8. junk in the region refuses on extract
    lo, _ = read_region(good_src, src)
    reset(None, good_src[:lo] + "\t\t/*99*/ { some, hand, written, junk },\n" + good_src[lo:])
    rc, out = run("extract")
    case("junk in the region refuses on extract", rc == 1 and "cannot parse" in out)

    # 9. the target survives a refused build
    reset(None, good_src)
    open(doc, "w").write("")
    run("build")
    case("refused build leaves the C intact", open(src).read() == good_src)

    shutil.rmtree(tmp, ignore_errors=True)
    width = max(len(n) for n, _, _ in results)
    bad = 0
    for name, ok, detail in results:
        print("  %s  %s%s" % ("PASS" if ok else "FAIL", name.ljust(width),
                              ("   " + detail) if detail and not ok else ""))
        bad += 0 if ok else 1
    print("mkchrbios selftest: %d/%d passed" % (len(results) - bad, len(results)))
    return 1 if bad else 0

# ── commands ─────────────────────────────────────────────────────────

RAW = argparse.RawDescriptionHelpFormatter

TOP_EPILOG = """\
where the text lives
  %s   the source of truth, edited by hand
  %s   the generated region, between the sentinel comments

Two kinds of bio:
  literal   the string is authored in the markdown and emitted as a C literal
  lang      the string lives in the ROM's language bank; only the four L_*
            symbol names are emitted, and no ROM text is duplicated

`build` never parses C. It finds the two sentinels and splices between them,
so nothing outside that region can move, whatever the markdown says. `extract`
does parse C, with line-anchored regexes, and refuses rather than guessing.

  mkchrbios build          # after editing the markdown
  mkchrbios check          # exit 1 if the C is behind the markdown
""" % (DOC, SRC)

def add_paths(p):
    p.add_argument("--doc", default=DOC, metavar="MD",
                   help="the markdown bios (default: %(default)s)")
    p.add_argument("--src", default=SRC, metavar="C",
                   help="the C file holding the generated region (default: %(default)s)")
    return p

def main():
    ap = argparse.ArgumentParser(
        prog="mkchrbios", formatter_class=RAW,
        description="Character bios live in markdown; this compiles them into the C.",
        epilog=TOP_EPILOG)
    sub = ap.add_subparsers(dest="command", required=True, metavar="COMMAND")

    add_paths(sub.add_parser(
        "build", formatter_class=RAW,
        help="markdown -> C",
        description="Compile the markdown bios into the generated region of the C file.",
        epilog="""\
Writes through a temp file and renames over, so an interrupted run cannot leave
a half-written C file. A run that changes nothing writes nothing.

Refuses, leaving the C untouched, if the markdown has a bio with no index, an
index out of sequence, a field it does not recognise, or a `lang` bio missing
one of its four L_* symbols. Prose between bios is carried through as-is.
"""))

    add_paths(sub.add_parser(
        "check", formatter_class=RAW,
        help="exit 1 if the C is behind the markdown",
        description="Compare what the markdown would generate against what is in the "
                    "C file. Writes nothing.",
        epilog="""\
Exit 0 means they agree, exit 1 means `build` has not been run since the
markdown changed. For a pre-commit hook or a build step.
"""))

    add_paths(sub.add_parser(
        "extract", formatter_class=RAW,
        help="C -> markdown",
        description="Read the generated region back out of the C file and write it as "
                    "markdown.",
        epilog="""\
For bootstrapping the markdown from C that was hand-written, or for recovering
it if it is lost. It OVERWRITES --doc, so on an established tree this is the
wrong direction: `build` is.
"""))

    add_paths(sub.add_parser(
        "selftest", formatter_class=RAW,
        help="run the failure matrix against a copy",
        description="Run every way the compiler is meant to refuse, against copies in "
                    "a temp directory.",
        epilog="""\
Touches nothing in the tree: the real --doc and --src are copied out first and
every case runs against the copies. Nine cases; prints a line each and a total.
Run it after changing this tool.
"""))

    a = ap.parse_args()

    if a.command == "selftest":
        return selftest(a.doc, a.src)

    src = open(a.src).read()
    lo, hi = read_region(src, a.src)

    if a.command == "extract":
        bios = parse_c(src[lo:hi])
        write_atomic(a.doc, emit_md(bios, a.src))
        print("mkchrbios: wrote %s (%d bios)" % (a.doc, len(bios)))
        return 0

    if not os.path.exists(a.doc):
        die("%s does not exist; run 'mkchrbios extract' first" % a.doc)

    bios = parse_md(open(a.doc).read())
    new = src[:lo] + emit_c(bios) + src[hi:]

    if a.command == "check":
        if new == src:
            print("mkchrbios: %s is up to date (%d bios)" % (a.src, len(bios)))
            return 0
        print("mkchrbios: %s is STALE — run 'mkchrbios build'" % a.src, file=sys.stderr)
        return 1

    if new == src:
        print("mkchrbios: %s already up to date (%d bios)" % (a.src, len(bios)))
        return 0
    write_atomic(a.src, new)
    print("mkchrbios: wrote %d bios into %s" % (len(bios), a.src))
    return 0

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