#!/usr/bin/env python3
"""`repro --coverage DIR ...` for Java: run the programs under JaCoCo, write lcov.info + html/.

usage: stitch-java-cov APP_DIR [repro args...] --coverage DIR
Environment (set by the repro script): STITCH_JAVA_CP, STITCH_JVM, STITCH_JAVA_INCLUDE,
STITCH_JAVA_HARNESS, STITCH_JAVA_SOURCES.
"""
import glob
import os
import shlex
import subprocess
import sys
import xml.etree.ElementTree as ET
import zipfile
from pathlib import Path

app = sys.argv[1]
args = sys.argv[2:]
i = args.index("--coverage")
out = Path(args[i + 1])
args = args[:i] + args[i + 2:]
out.mkdir(parents=True, exist_ok=True)
cp = os.environ["STITCH_JAVA_CP"]
inc = [p for p in os.environ.get("STITCH_JAVA_INCLUDE", "").split(",") if p]
harness = [p for p in os.environ.get("STITCH_JAVA_HARNESS", "").split(",") if p]
includes = ":".join([p + ".*" for p in inc] + [c + "*" for c in harness]) or "*"
exec_file = out / "jacoco.exec"
agent = f"-javaagent:/stitch/java/jacocoagent.jar=destfile={exec_file},includes={includes}"
cmd = ["java", *shlex.split(os.environ.get("STITCH_JVM", "")), agent, "-cp", cp, "stitch.rt.Main", "--app", app, *args]
r = subprocess.run(cmd)

# class files: every classpath entry (wildcards expanded)
classfiles = []
for e in cp.split(":"):
    classfiles += glob.glob(e[:-1] + "*.jar") if e.endswith("/*") else [e]
roots = [s for s in os.environ.get("STITCH_JAVA_SOURCES", "").split(",") if s]
if not roots:
    roots = [str(p) for p in Path("/src").glob("**/src/main/java")] if Path("/src").is_dir() else []
roots.append("/project/harness")
cli = ["java", "-jar", "/stitch/java/jacococli.jar", "report", str(exec_file), "--xml", str(out / "jacoco.xml"),
       "--html", str(out / "html"), "--quiet"]


def measured(name):
    """A class file the report should analyze: in an included package (or the harness), and not a
    multi-release variant (META-INF/versions/N/...: JaCoCo rejects two classes with one name)."""
    if not name.endswith(".class") or name.startswith("META-INF/"):
        return False
    if not inc:
        return True
    dotted = name[:-len(".class")].replace("/", ".")
    return any(dotted.startswith(p + ".") for p in inc) or any(dotted == c or dotted.startswith(c + "$") for c in harness)


# Only the classes of the measured packages go to the report: dependency jars can hold classes
# JaCoCo cannot analyze side by side (multi-release jars), and they are not reported anyway.
cdir = out / "classes"
for c in classfiles:
    if not os.path.exists(c) or c.endswith("stitch.jar"):
        continue
    if os.path.isdir(c):
        for f in Path(c).rglob("*.class"):
            rel = str(f.relative_to(c))
            if measured(rel):
                (cdir / rel).parent.mkdir(parents=True, exist_ok=True)
                (cdir / rel).write_bytes(f.read_bytes())
        continue
    try:
        with zipfile.ZipFile(c) as z:
            for n in z.namelist():
                if measured(n) and not (cdir / n).exists():
                    (cdir / n).parent.mkdir(parents=True, exist_ok=True)
                    (cdir / n).write_bytes(z.read(n))
    except (zipfile.BadZipFile, OSError):
        cli += ["--classfiles", c]
cli += ["--classfiles", str(cdir)]
for s in roots:
    if os.path.isdir(s):
        cli += ["--sourcefiles", s]
rep = subprocess.run(cli, capture_output=True, text=True)
(out / "report.txt").write_text(rep.stdout + rep.stderr)


def wanted(pkg):
    if not inc:
        return True
    dotted = pkg.replace("/", ".")
    return any(dotted == p or dotted.startswith(p + ".") for p in inc) or any(
        (c.rsplit(".", 1)[0] if "." in c else "") == dotted for c in harness)


# jacoco.xml -> lcov
lines = []
if (out / "jacoco.xml").exists():
    tree = ET.parse(out / "jacoco.xml")
    for pkg in tree.getroot().iter("package"):
        pname = pkg.get("name")
        if not wanted(pname):
            continue
        methods = {}
        for cls in pkg.findall("class"):
            src = cls.get("sourcefilename")
            for m in cls.findall("method"):
                c = {x.get("type"): (int(x.get("missed")), int(x.get("covered"))) for x in m.findall("counter")}
                name = cls.get("name").rsplit("/", 1)[-1] + "." + m.get("name")
                methods.setdefault(src, []).append((int(m.get("line") or 0), name, c.get("METHOD", (1, 0))[1]))
        for sf in pkg.findall("sourcefile"):
            fname = sf.get("name")
            rel = f"{pname}/{fname}" if pname else fname
            path = next((f"{r}/{rel}" for r in roots if os.path.exists(f"{r}/{rel}")), "/" + rel)
            lines.append(f"SF:{path}")
            for ln, name, hit in methods.get(fname, []):
                lines.append(f"FN:{ln},{name}")
                lines.append(f"FNDA:{hit},{name}")
            fns = methods.get(fname, [])
            lines.append(f"FNF:{len(fns)}")
            lines.append(f"FNH:{sum(1 for f in fns if f[2])}")
            lf = lh = brf = brh = 0
            for l in sf.findall("line"):
                nr, ci, mb, cb = int(l.get("nr")), int(l.get("ci")), int(l.get("mb")), int(l.get("cb"))
                lines.append(f"DA:{nr},{1 if ci else 0}")
                lf += 1
                lh += 1 if ci else 0
                brf += mb + cb
                brh += cb
            lines += [f"BRF:{brf}", f"BRH:{brh}", f"LF:{lf}", f"LH:{lh}", "end_of_record"]
(out / "lcov.info").write_text("\n".join(lines) + "\n")
sys.exit(r.returncode)
