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

Snapshots harness/ into <out>/app (campaigns run from their own copy), checks that it loads,
and writes
  <out>/fuzzer          the engine, with the Ruby worker (YJIT) as its runtime
  <out>/repro           runs .stp programs (`stitch-rb`)
  <out>/manifest.json   the stubs as the fuzzer sees them
stitch.toml [ruby]: include = ["gem", ...] (gems or path prefixes to measure; default: all but
                    the standard library), exclude = [...]
"""
import argparse
import json
import shlex
import shutil
import subprocess
import sys
import tomllib
from pathlib import Path


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--project", default="/project")
    ap.add_argument("--out", default=None)
    ap.add_argument("--target", default="all")
    ap.add_argument("--json", action="store_true")
    a = ap.parse_args()
    proj = Path(a.project).resolve()
    cfg = tomllib.loads((proj / "stitch.toml").read_text()) if (proj / "stitch.toml").exists() else {}
    rb = cfg.get("ruby", {})
    out = Path(a.out) if a.out else proj / ".stitch" / "build"
    if not out.is_absolute():
        out = proj / out
    out.mkdir(parents=True, exist_ok=True)
    app = out / "app"
    shutil.rmtree(app, ignore_errors=True)
    if not (proj / "harness").is_dir():
        return finish(a, {"ok": False, "errors": [{"file": "harness", "output": "no harness/ directory"}]})
    shutil.copytree(proj / "harness", app / "harness", ignore=shutil.ignore_patterns("data"))
    env_lines = [f"export STITCH_RB_INCLUDE={shlex.quote(','.join(rb.get('include', [])))}",
                 f"export STITCH_RB_EXCLUDE={shlex.quote(','.join(rb.get('exclude', [])))}",
                 'export STITCH_PROJECT="$HERE/app"']
    head = ["#!/bin/sh", 'HERE="$(cd "$(dirname "$0")" && pwd)"'] + env_lines
    (out / "fuzzer").write_text("\n".join(head + [
        'export STITCH_WORKER="ruby --yjit /stitch/ruby/bin/stitch-rb worker --project \'$HERE/app\'"',
        'exec /stitch/bin/stitch-engine "$@"', ""]))
    (out / "repro").write_text("\n".join(head + ['exec ruby /stitch/ruby/bin/stitch-rb --project "$HERE/app" "$@"', ""]))
    for f in ("fuzzer", "repro"):
        (out / f).chmod(0o755)
    r = subprocess.run([str(out / "repro"), "--manifest"], capture_output=True, text=True, cwd=proj)
    if r.returncode != 0:
        return finish(a, {"ok": False, "errors": [{"file": "harness", "output": (r.stderr or r.stdout)[-8000:]}]})
    m = json.loads(r.stdout.strip().splitlines()[-1])
    (out / "manifest.json").write_text(json.dumps(m))
    res = {"ok": True, "fuzzer": str(out / "fuzzer"), "repro": str(out / "repro"), "endpoints": len(m["endpoints"]),
           "objects": len(m["objects"]), "datatypes": len(m["datatypes"]), "errors": []}
    return finish(a, res)


def finish(a, res):
    if a.json:
        print(json.dumps(res))
    elif res["ok"]:
        print(f"built: {res['endpoints']} endpoints, {res['objects']} object types, {res['datatypes']} datatypes")
    else:
        for e in res["errors"]:
            sys.stderr.write(e["output"] + "\n")
    sys.exit(0 if res["ok"] else 1)


if __name__ == "__main__":
    main()
