#!/usr/bin/env python3
"""Compile a STITCH++ harness inside the project image.

Reads <project>/stitch.toml, compiles harness/**/*.{cpp,cc,cxx,c} with instrumentation, links
  .stitch/build/fuzzer   harness + runtime + LibAFL engine
  .stitch/build/repro    harness + runtime + reproducer driver (no engine)
and writes .stitch/build/manifest.json.
"""
import argparse
import hashlib
import json
import os
import re
import subprocess
import sys
import tomllib
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

STITCH = Path(os.environ.get("STITCH_HOME", "/stitch"))
RT = STITCH / "runtime"


def sh(cmd, **kw):
    return subprocess.run(cmd, text=True, capture_output=True, **kw)


def flags(no_cov=False):
    r = sh(["/stitch/bin/stitch-flags"] + (["--no-cov"] if no_cov else []))
    return r.stdout.split()


# ------------------------------------------------------------------ parameter names
def split_top(s, sep=","):
    """Split on top-level separators; `<<` / `>>` between operands are shifts, not brackets."""
    out, depth, cur, i = [], 0, "", 0
    while i < len(s):
        ch = s[i]
        two = s[i:i + 2]
        prev = cur.rstrip()[-1:] if cur.rstrip() else ""
        nxt = s[i + 2:].lstrip()[:1]
        if two == "<<" and (prev.isalnum() or prev == ")"):
            cur += two; i += 2; continue
        if two == ">>" and (nxt.isdigit() or nxt == "("):
            cur += two; i += 2; continue
        if ch in "<([{":
            depth += 1
        elif ch in ">)]}":
            depth -= 1
        if ch == sep and depth == 0:
            out.append(cur)
            cur = ""
        else:
            cur += ch
        i += 1
    if cur.strip():
        out.append(cur)
    return out


def strip_comments(src):
    src = re.sub(r"//[^\n]*", "", src)
    return re.sub(r"/\*.*?\*/", "", src, flags=re.S)


def endpoint_arg_names(src):
    """{endpoint: [arg names]} for STITCH_ENDPOINT(fn) in this source."""
    code = strip_comments(src)
    out = {}
    for full in re.findall(r"STITCH_ENDPOINT\(\s*([\w:]+)\s*\)", code):
        fn = full.split("::")[-1]
        for m in re.finditer(r"\b%s\s*\(" % re.escape(fn), code):
            i, depth = m.end() - 1, 0
            for j in range(i, len(code)):
                if code[j] == "(":
                    depth += 1
                elif code[j] == ")":
                    depth -= 1
                    if depth == 0:
                        break
            rest = code[j + 1 : j + 200].lstrip()
            if not rest.startswith("{"):
                continue  # a call or declaration, not the definition
            names = []
            for p in split_top(code[i + 1 : j]):
                p = p.split("=")[0].strip()
                ids = re.findall(r"[A-Za-z_]\w*", p)
                names.append(ids[-1] if len(ids) >= 2 else "")
            out[full] = names
            break
    return out


# ------------------------------------------------------------------ incremental compile
def needs_build(obj: Path, src: Path, key: str):
    stamp = obj.with_suffix(".key")
    dep = obj.with_suffix(".d")
    if not obj.exists() or not stamp.exists() or stamp.read_text() != key:
        return True
    t = obj.stat().st_mtime
    deps = [src]
    if dep.exists():
        txt = dep.read_text().replace("\\\n", " ")
        deps += [Path(d) for d in txt.split(":", 1)[-1].split()]
    for d in deps:
        try:
            if d.stat().st_mtime > t:
                return True
        except FileNotFoundError:
            return True
    return False


def compile_one(src: Path, obj: Path, cmd, key):
    if not needs_build(obj, src, key):
        return src, None
    obj.parent.mkdir(parents=True, exist_ok=True)
    r = sh(cmd + ["-MMD", "-MF", str(obj.with_suffix(".d")), "-c", str(src), "-o", str(obj)])
    if r.returncode != 0:
        return src, (r.stderr or r.stdout)
    obj.with_suffix(".key").write_text(key)
    if r.stderr.strip():
        sys.stderr.write(r.stderr)
    return src, None


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--project", default="/project")
    ap.add_argument("--out", default=None, help="output dir (default .stitch/build)")
    ap.add_argument("--target", default="all", choices=["all", "fuzzer", "repro"])
    ap.add_argument("--json", action="store_true")
    a = ap.parse_args()
    proj = Path(a.project)
    os.chdir(proj)
    cfg = tomllib.loads((proj / "stitch.toml").read_text()) if (proj / "stitch.toml").exists() else {}
    b = cfg.get("build", {})
    san = b.get("sanitizers")
    if san:
        os.environ["STITCH_SANITIZERS"] = ",".join(san) if isinstance(san, list) else str(san)
    out = Path(a.out) if a.out else proj / ".stitch" / "build"
    objdir = out / "obj"
    objdir.mkdir(parents=True, exist_ok=True)
    std = b.get("std", "c++17")
    user_cflags = list(b.get("cflags", []))
    ldflags = list(b.get("ldflags", []))
    patterns = b.get("sources", ["harness/**/*.cpp", "harness/**/*.cc", "harness/**/*.cxx", "harness/**/*.c"])
    srcs = sorted({p for pat in patterns for p in Path(".").glob(pat) if p.is_file()})
    if not srcs:
        print("error: no harness sources (harness/**/*.cpp)", file=sys.stderr)
        sys.exit(1)

    # parameter names -> generated TU
    names = {}
    for s in srcs:
        names.update(endpoint_arg_names(s.read_text(errors="replace")))
    gen = out / "stitch_names.cpp"
    lines = ['#include <stitch.h>']
    for i, (fn, ns) in enumerate(sorted(names.items())):
        lst = ", ".join(json.dumps(n) for n in ns)
        lines.append(f'static const int stitch_names_{i} = (::stitch::detail::set_param_names("{fn}", {{{lst}}}), 0);')
    txt = "\n".join(lines) + "\n"
    if not gen.exists() or gen.read_text() != txt:
        gen.write_text(txt)

    instr = flags()
    nocov = flags(no_cov=True)
    inc = ["-I", str(RT / "include"), "-I", "harness"]
    jobs = []
    for s in srcs:
        is_c = s.suffix == ".c"
        cmd = (["clang"] if is_c else ["clang++", f"-std={std}"]) + instr + inc + user_cflags
        obj = objdir / (str(s).replace("/", "__") + ".o")
        jobs.append((s, obj, cmd, hashlib.sha1(" ".join(cmd).encode()).hexdigest()))
    rt_cmd = ["clang++", "-std=c++17"] + nocov + inc
    for name in ["runtime.cpp", "main_fuzzer.cpp", "main_repro.cpp"]:
        jobs.append((RT / "src" / name, objdir / ("_" + name + ".o"), rt_cmd, hashlib.sha1((" ".join(rt_cmd) + str((RT / "src" / name).stat().st_mtime)).encode()).hexdigest()))
    gen_cmd = ["clang++", f"-std={std}"] + nocov + inc
    jobs.append((gen, objdir / "_names.o", gen_cmd, hashlib.sha1(" ".join(gen_cmd).encode()).hexdigest()))

    errors = []
    with ThreadPoolExecutor(max_workers=os.cpu_count() or 4) as ex:
        for src, err in ex.map(lambda j: compile_one(*j), jobs):
            if err:
                errors.append({"file": str(src), "output": err[-8000:]})
                sys.stderr.write(err)
    result = {"ok": not errors, "sources": [str(s) for s in srcs], "errors": errors}
    if not errors:
        harness_objs = [str(j[1]) for j in jobs if not j[1].name.startswith("_")] + [str(objdir / "_names.o"), str(objdir / "_runtime.cpp.o")]
        sys_libs = ["-lstdc++", "-lpthread", "-ldl", "-lm", "-lrt"]
        targets = ["fuzzer", "repro"] if a.target == "all" else [a.target]
        for t in targets:
            main_o = str(objdir / ("_main_fuzzer.cpp.o" if t == "fuzzer" else "_main_repro.cpp.o"))
            engine = [str(STITCH / "lib" / "libstitch_engine.a")] if t == "fuzzer" else []
            prof = ["-fprofile-instr-generate"] if os.environ.get("STITCH_COVERAGE") else []
            cmd = ["clang++"] + nocov + prof + ["-o", str(out / t), main_o] + harness_objs + ldflags + engine + sys_libs
            r = sh(cmd)
            if r.returncode != 0:
                errors.append({"file": f"link {t}", "output": r.stderr[-8000:]})
                sys.stderr.write(r.stderr)
                result["ok"] = False
            else:
                result[t] = str(out / t)
        if result["ok"]:
            exe = out / ("fuzzer" if "fuzzer" in targets else "repro")
            r = sh([str(exe), "manifest"] if exe.name == "fuzzer" else [str(exe), "--manifest"], env={**os.environ, "ASAN_OPTIONS": "detect_leaks=0", "LLVM_PROFILE_FILE": "/dev/null"})
            if r.returncode == 0:
                (out / "manifest.json").write_text(r.stdout)
                m = json.loads(r.stdout)
                result["endpoints"] = len(m["endpoints"])
                result["objects"] = len(m["objects"])
                result["datatypes"] = len(m["datatypes"])
            else:
                result["ok"] = False
                errors.append({"file": "manifest", "output": (r.stderr or r.stdout)[-4000:]})
                sys.stderr.write(r.stderr)
    result["errors"] = errors
    if a.json:
        print(json.dumps(result))
    elif result["ok"]:
        print(f"built {', '.join(t for t in ('fuzzer', 'repro') if t in result)}: "
              f"{result.get('endpoints', '?')} endpoints, {result.get('objects', '?')} object types, {result.get('datatypes', '?')} datatypes")
    sys.exit(0 if result["ok"] else 1)


if __name__ == "__main__":
    main()
