#!/usr/bin/env python3
"""Does api's incremental cache survive an api-common edit? (real workload)"""
import json, os, shutil, subprocess, time, statistics

REC = "/Users/oscar/.worktree/hot-reload/labs/hot-reload/target/kan-hot/debug/rustc"
ROOT = "/Users/oscar/.worktree/hot-reload/labs/hot-reload"
SRC = {"api_common": os.path.join(ROOT, "api-common/src/lib.rs"),
       "api": os.path.join(ROOT, "api/src/lib.rs")}
orig = {k: open(v).read() for k, v in SRC.items()}
INV = {k: json.load(open(os.path.join(REC, k + ".json"))) for k in SRC}
INC = os.path.join(ROOT, "target/bench-inc-api")


def compile_(name, extra=()):
    inv = INV[name]
    t0 = time.monotonic()
    p = subprocess.run(list(inv["argv"]) + list(extra), cwd=inv["cwd"], env=dict(inv["env"]),
                       stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
    el = (time.monotonic() - t0) * 1000
    assert p.returncode == 0, p.stderr.decode()[:3000]
    return el


def seq(label, common_extra=(), api_extra=(), n=7, reset=None):
    if reset:
        shutil.rmtree(reset, ignore_errors=True)
    cs, as_ = [], []
    for _ in range(n):
        open(SRC["api_common"], "w").write(orig["api_common"].replace("nested-v1", f"x-{time.time_ns()}"))
        cs.append(compile_("api_common", common_extra))
        as_.append(compile_("api", api_extra))
    c, a = statistics.median(cs), statistics.median(as_)
    print(f"{label:34s} common={c:6.1f} api={a:6.1f} total={c + a:6.1f} (api min {min(as_):.1f})")


try:
    seq("baseline")
    seq("api incremental", api_extra=("-C", f"incremental={INC}"), reset=INC)
    seq("api incremental 2nd", api_extra=("-C", f"incremental={INC}"))
    seq("api incremental cgu1", api_extra=("-C", f"incremental={INC}", "-C", "codegen-units=1"))
    seq("api incremental cgu16", api_extra=("-C", f"incremental={INC}", "-C", "codegen-units=16"))
finally:
    shutil.rmtree(INC, ignore_errors=True)
    for k, v in SRC.items():
        open(v, "w").write(orig[k])
