#!/usr/bin/env python3
#------------------------------------------------------------------------------
# smoke-select.py - Choose the programs of the smoke test
#
#   smoke-select.py [--e2e-out DIR] [--oo-out DIR] [--tests DIR] [DROP]
#
# A greedy choice, out of the end-to-end tests (../tests/e2e/cases, without
# the cases that have .expected files) and the OO cases (../tests/oo/cases),
# of programs that together have every feature that any of them has. The
# features of a program: the R-code opcodes it uses, opcode + name operand
# (the built-in functions with their argument counts, the conditions, the
# environments...), its non-empty sections, the ::OPTIONS, and the error
# codes in the native standard error. They are read from the outputs of a
# full run of the suites:
#   --e2e-out: the work directory of "e2e.sh js" (NAME.rcode, NAME.o.err;
#              default $RVM_TESTS_TMP/e2e-js);
#   --oo-out:  the work directory of a full "oo-e2e.sh" (NAME.rcode,
#              NAME.nat.err; default $RVM_TESTS_TMP/oo).
# RVM_TESTS_TMP defaults to ${TMPDIR:-/tmp}/rvm-tests. DROP is a
# comma-separated list of programs (e2e:NAME, oo:NAME) not to choose.
# Prints the counts on standard error and the chosen programs, one per line,
# on standard output. See doc/16-testing.md for how the smoke test is
# rebuilt from them.
#
# This file is part of the RVM, the Rexx Virtual Machine
# [See https://rexx.epbcn.com/rexx-parser/]
#
# Copyright (c) 2026 Josep Maria Blasco <josep.maria.blasco@epbcn.com>
#
# License: Apache License 2.0 (https://www.apache.org/licenses/LICENSE-2.0)
#------------------------------------------------------------------------------
import argparse, os, re, sys, glob
HERE = os.path.dirname(os.path.abspath(__file__))
TMP = os.environ.get("RVM_TESTS_TMP") or os.path.join(os.environ.get("TMPDIR") or "/tmp", "rvm-tests")
ap = argparse.ArgumentParser(description="Choose the programs of the smoke test.")
ap.add_argument("--tests", default=os.path.join(HERE, "..", "tests"), help="the RVM's tests directory")
ap.add_argument("--e2e-out", default=os.path.join(TMP, "e2e-js"))
ap.add_argument("--oo-out", default=os.path.join(TMP, "oo"))
ap.add_argument("drop", nargs="?", default="")
args = ap.parse_args()
E2E = os.path.join(args.tests, "e2e", "cases")
OO = os.path.join(args.tests, "oo", "cases")
pool = {}
def feats(rcode, errfile):
    f = set()
    try: lines = open(rcode, encoding="latin-1").read().split("\n")
    except: return None
    if not lines or not lines[0].startswith("RCODE"): return None
    incode = False
    consts, inconst = [], False
    for l in lines:
        if l.startswith("CONSTANTS "): inconst = True; continue
        if l.startswith("NAMES "): inconst = False
        if inconst: consts.append(l.strip('"').upper())
    for l in lines:
        m = re.match(r"^(CONSTANTS|NAMES|LABELS|DESCRIPTORS|WITHS|REQUIRES|CLASSES|METHODS|ROUTINES|ANNOTATIONS|RESOURCES|CODE) (\d+)$", l)
        if m:
            if m.group(1) != "CODE" and int(m.group(2)) > 0: f.add("SEC:" + m.group(1))
            incode = m.group(1) == "CODE"; continue
        if l.startswith("OPTIONS "): f.add("OPT:" + " ".join(l.split()[3:]))
        if incode and l:
            t = l.split()
            if not re.match(r"^[A-Z]+$", t[0]): continue
            f.add("OP:" + t[0])
            if t[0] in ("FUNCB", "CALLB") and len(t) > 2:
                k = int(t[1]) - 1
                if 0 <= k < len(consts):
                    f.add("BIF:" + consts[k]); f.add("BIFN:" + consts[k] + "/" + t[2])
            if len(t) > 1 and re.match(r'^"?[A-Za-z][A-Za-z0-9.]*"?$', t[1]) and t[0] not in ("CLAUSE",):
                f.add("OPN:" + t[0] + " " + t[1].strip('"').upper())
    if errfile and os.path.exists(errfile):
        for m in re.finditer(r"Error (\d+\.\d+)", open(errfile, encoding="latin-1").read()):
            f.add("ERR:" + m.group(1))
    return f
for r in glob.glob(os.path.join(args.e2e_out, "*.rcode")):
    b = os.path.basename(r)[:-6]; src = os.path.join(E2E, b + ".rex")
    if not os.path.exists(src): continue
    if glob.glob(os.path.join(E2E, b + ".expected*")): continue
    x = feats(r, os.path.join(args.e2e_out, b + ".o.err"))
    if x: pool["e2e:" + b] = x
for r in glob.glob(os.path.join(args.oo_out, "*.rcode")):
    b = os.path.basename(r)[:-6]; src = os.path.join(OO, b + ".rex")
    if not os.path.exists(src): continue
    x = feats(r, os.path.join(args.oo_out, b + ".nat.err"))
    if x: pool["oo:" + b] = x
drop = set(args.drop.split(",")) if args.drop else set()
for d in drop: pool.pop(d, None)
if not pool: sys.exit("no programs: run e2e.sh js and oo-e2e.sh first (see --e2e-out, --oo-out)")
allf = set().union(*pool.values())
chosen, covered = [], set()
while True:
    best = max(pool, key=lambda k: (len(pool[k] - covered), -len(pool[k])))
    gain = pool[best] - covered
    if not gain: break
    chosen.append(best); covered |= gain
print(len(pool), "programs,", len(allf), "features;", len(chosen), "chosen", file=sys.stderr)
kinds = {}
for f in allf: kinds[f.split(":")[0]] = kinds.get(f.split(":")[0], 0) + 1
print(kinds, file=sys.stderr)
print("\n".join(chosen))
