"""Boundary table (CS2 / L4): for p in a range and n in a range, decide whether
some X in P(n,5) with |X| = p has |dX| <= 11, and if so record the exact
minimum beta_p(n) and a witness (an obstruction to the boundary method).

usage: python3 code/run_boundary_table.py PMIN PMAX NMIN NMAX [workers]
       python3 code/run_boundary_table.py --job N P      (single instance, prints JSON)
appends to results/boundary_table.jsonl
Parallelism uses subprocesses (ProcessPoolExecutor is unavailable in the sandbox).
"""
import json
import os
import subprocess
import sys
import time
from concurrent.futures import ThreadPoolExecutor

import common
from graph_constructor import label
from sat_or_ilp_solver import beta


def job(n, p):
    t0 = time.time()
    r = beta(n, 5, p, start=11)
    r["wall_seconds"] = round(time.time() - t0, 3)
    r["utc"] = common.utcnow()
    if r["X"] is not None:
        r["X_labels"] = [label(w, n) for w in r["X"]]
        r["boundary_labels"] = [label(w, n) for w in r["boundary"]]
    return r


def run_sub(args):
    n, p = args
    out = subprocess.run([sys.executable, os.path.abspath(__file__), "--job", str(n), str(p)], capture_output=True, text=True)
    if out.returncode != 0:
        return {"n": n, "p": p, "error": out.stderr[-500:]}
    return json.loads(out.stdout.strip().splitlines()[-1])


if __name__ == "__main__":
    if sys.argv[1] == "--job":
        print(json.dumps(job(int(sys.argv[2]), int(sys.argv[3]))))
        sys.exit(0)
    pmin, pmax, nmin, nmax = (int(a) for a in sys.argv[1:5])
    workers = int(sys.argv[5]) if len(sys.argv) > 5 else 8
    out = os.path.join(common.RESULTS, "boundary_table.jsonl")
    tasks = [(n, p) for p in range(pmin, pmax + 1) for n in range(nmin, nmax + 1)]
    common.log_event("D", "boundary_table_start", pmin=pmin, pmax=pmax, nmin=nmin, nmax=nmax, workers=workers)
    with ThreadPoolExecutor(max_workers=workers) as ex:
        for r in ex.map(run_sub, tasks):
            common.append_jsonl(out, r)
            if "error" in r:
                print("n=%d p=%d ERROR %s" % (r["n"], r["p"], r["error"]), flush=True)
            else:
                print("n=%d p=%d beta=%s%s %.1fs" % (r["n"], r["p"], r["beta"], "" if r["exact"] else "+", r["wall_seconds"]), flush=True)
    common.log_event("D", "boundary_table_end", pmin=pmin, pmax=pmax, nmin=nmin, nmax=nmax)
