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

Compiles harness/**/*.java into <out>/app/classes (campaigns run from their own copy) and writes
  <out>/fuzzer          the engine, with the JVM worker as its runtime
  <out>/repro           runs .stp programs
  <out>/manifest.json   the stubs as the fuzzer sees them
stitch.toml [java]: classpath = ["/deps/*"]       the library and its dependencies
                    include = ["org.example"]     packages to instrument (default: all non-JDK)
                    sources = ["/src/src/main/java"]  source roots (coverage reports)
                    jvm_options = [...]
"""
import argparse
import json
import re
import shlex
import shutil
import subprocess
import sys
import tomllib
from pathlib import Path

STITCH_JAR = "/stitch/java/stitch.jar"
EXPORT = "--add-exports java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED"


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 {}
    jv = cfg.get("java", {})
    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)
    (app / "classes").mkdir(parents=True)
    srcs = sorted(p for p in (proj / "harness").rglob("*.java") if "data" not in p.relative_to(proj / "harness").parts[:1])
    if not srcs:
        return finish(a, {"ok": False, "errors": [{"file": "harness", "output": "no harness/**/*.java files"}]})
    cp = ":".join(jv.get("classpath", ["/deps/*"]))
    r = subprocess.run(["javac", "-g", "-parameters", "-nowarn", "-encoding", "UTF-8", "-d", str(app / "classes"), "-cp",
                        f"{STITCH_JAR}:{cp}", *map(str, srcs)], capture_output=True, text=True)
    if r.returncode != 0:
        return finish(a, {"ok": False, "errors": [{"file": "javac", "output": (r.stderr or r.stdout)[-8000:]}]})
    lines, classes = [], []
    for s in srcs:
        m = re.search(r"^\s*package\s+([\w.]+)\s*;", s.read_text(errors="replace"), re.M)
        name = (m.group(1) + "." if m else "") + s.stem
        if (app / "classes" / (name.replace(".", "/") + ".class")).exists():
            lines.append(f"{name}\t{s.relative_to(proj)}")
            classes.append(name)
    (app / "harness-classes.txt").write_text("\n".join(lines) + "\n")
    full_cp = f'$HERE/app/classes:{STITCH_JAR}:{cp}'
    jvm = " ".join(shlex.quote(o) for o in jv.get("jvm_options", ["-Xmx2g", "-Xss8m", "-XX:+UseSerialGC"]))
    head = ["#!/bin/sh", 'HERE="$(cd "$(dirname "$0")" && pwd)"',
            f"export STITCH_JAVA_INCLUDE={shlex.quote(','.join(jv.get('include', [])))}",
            f"export STITCH_JAVA_HARNESS={shlex.quote(','.join(classes))}",
            f"export STITCH_JAVA_SOURCES={shlex.quote(','.join(jv.get('sources', [])))}",
            f'export STITCH_JAVA_CP="{full_cp}"',
            f"export STITCH_JVM={shlex.quote(jvm)}"]
    (out / "fuzzer").write_text("\n".join(head + [
        f'export STITCH_WORKER="java $STITCH_JVM {EXPORT} -javaagent:{STITCH_JAR} -cp \'$STITCH_JAVA_CP\' stitch.rt.Main --app \'$HERE/app\' worker"',
        'exec /stitch/bin/stitch-engine "$@"', ""]))
    (out / "repro").write_text("\n".join(head + [
        'case " $* " in *" --coverage "*) exec /stitch/bin/stitch-java-cov "$HERE/app" "$@";; esac',
        'exec java $STITCH_JVM -cp "$STITCH_JAVA_CP" stitch.rt.Main --app "$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 or not r.stdout.strip():
        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))
    return finish(a, {"ok": True, "endpoints": len(m["endpoints"]), "objects": len(m["objects"]),
                      "datatypes": len(m["datatypes"]), "errors": []})


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()
