#!/usr/bin/env python3
"""Joins the logs of the final runs of IIS-Q-0003 in one text file for the upload.

usage: python3 -I make_q3_logs_file.py OUT_FILE LOGDIR
The script stops if one file of the list does not exist.  The logs of my first tests that the
report does not use (q3_pairs_L0.log, q3_pairs_full_L0.log, q3_budgets_more.log, q3_z3_*.log) are
not in the list.  The path of the root of the workspace is replaced by <W> in the text of the logs
(it occurs in two tracebacks).  clean(text) makes this replacement; build_report_capset_q3.py
uses the same function.
"""
import os
import sys

KINDS = ("dual", "intact", "p1s", "p1w", "p2", "p3")
# This script is in work/capset.  The root of the workspace is two levels above.
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))


def clean(text):
    """Replaces the path of the root of the workspace by <W>."""
    return text.replace(ROOT, "<W>")


SECTIONS = [
    ("The C program q3_check, final revision", [
        ("q3_all_run.log", "Console output of run_all.sh: the hashes of the source, the binary and the dump"),
        ("q3_facts.log", "Output of q3_check facts on the two caps"),
        ("q3_tables_run.log", "Console output of run_tables.sh: the tables of masks"),
        ("q3_tables_collected.log", "Output of collect_tables.py: Table 2 of the report, with the raw numbers"),
    ]),
    ("The raw logs of the tables of masks (the input of collect_tables.py)", [
        *(("q3_intact_L%d.log" % l, "Intact cap, cap %d" % l) for l in (0, 1)),
        *(("q3_dual_L%d.log" % l, "Dual mask, cap %d" % l) for l in (0, 1)),
        *(("q3_p1w_full_L%d.log" % l, "One puncture, weak rule, all budgets, cap %d" % l) for l in (0, 1)),
        *(("q3_p1s_L%d.log" % l, "One puncture, strict rule, cap %d" % l) for l in (0, 1)),
        *(("q3_p2_low_L%d.txt" % l, "Two punctures, budgets 30 to 33, cap %d" % l) for l in (0, 1)),
        *(("q3_p2_L%d_%d.log" % (l, i), "Two punctures, part %d, cap %d" % (i, l)) for l in (0, 1) for i in range(12)),
        *(("q3_p3_L%d_%d.log" % (l, i), "Three punctures, part %d, cap %d" % (i, l)) for l in (0, 1) for i in range(12)),
        ("q3_p2_low_run.log", "Console output of run_p2_low.sh and of q3_p2_low_summary.py"),
        ("q3_p2_low_run_first.log", "Console output of the first run of the same commands, before I wrote the script"),
    ]),
    ("The code replay of check16.py", [
        ("replay_check16.log", "Console output of run_replay_check16.sh"),
    ]),
    ("The direct tests of the C program", [
        *(("q3_climb_L%d.log" % l, "Random climbs, cap %d" % l) for l in (0, 1)),
        *(("q3_pairs_L%d_S%d.log" % (l, s), "Random matrices with an overlap of 26 or more, seed %d, cap %d" % (s, l))
          for l in (0, 1) for s in (5, 6, 7)),
        *(("q3_hunt_L%d.log" % l, "Hunt for large overlaps, cap %d" % l) for l in (0, 1)),
        *(("q3_mono_L%d.log" % l, "Signed permutation matrices, cap %d" % l) for l in (0, 1)),
        *(("q3_cross_L%d.log" % l, "The two caps of the 236-cap, cap %d" % l) for l in (0, 1)),
        *(("q3_one_identity_L%d.log" % l, "The identity map, cap %d" % l) for l in (0, 1)),
        *(("q3_one_overlap0_L%d.log" % l, "The overlap 0, cap %d" % l) for l in (0, 1)),
        ("q3_search_collected.log", "Output of run_search_collect.sh: the collection of the ten logs of the climbs, the random matrices and the hunts"),
        ("q3_target_run.log", "Console output of run_target.sh"),
        ("q3_target_L0.log", "Selected matrices, cap 0"),
        ("q3_target_L1.log", "Selected matrices, cap 1"),
        ("q3_target_collected.log", "Output of q3_target_collect.py on the two logs above"),
        ("q3_tight_run.log", "Console output of run_tight.sh"),
        ("q3_tight_collected.log", "Output of q3_target_collect.py on the two logs of the run (the raw logs have 9 MB each; they are not in this file)"),
        *(("q3_crosscheck_L%d.log" % l, "Output of q3_crosscheck.py, cap %d" % l) for l in (0, 1)),
        *(("q3_target_crosscheck_L%d.log" % l, "Output of q3_crosscheck.py on the selected matrices, cap %d" % l) for l in (0, 1)),
    ]),
    ("Two solvers that are not mine (z3 and HiGHS)", [
        ("q3_third_run.log", "Console output of run_third.sh"),
        ("q3_third_collected.log", "Output of q3_third_collect.py"),
        *(("q3_third_%s_L%d_%s.log" % (solver, l, kind), "%s, %s, cap %d" % ("z3" if solver == "z3" else "HiGHS", kind, l))
          for solver in ("z3", "highs") for l in (0, 1) for kind in KINDS),
    ]),
    ("The Python program q3_tables_py.py", [
        ("q3_tables_py_run.log", "Console output of the first run (revision 1 of the program)"),
        ("q3_tables_py_run1_P2_failed.log", "Console output of part 2 in the first run (it stopped at once)"),
        ("q3_tables_py_run1_P3_failed.log", "Console output of part 3 in the first run (it stopped at once)"),
        ("q3_tables_py_run2.log", "Console output of the second run (revision 2, parts 2 and 3)"),
        ("q3_tables_py_collected.log", "Output of the collection of the 12 parts: Table 3 of the report"),
        *(("q3_tables_py_P%d.log" % i, "Part %d of 12" % i) for i in range(12)),
    ]),
    ("The model of the cases", [
        ("q3_cases.log", "Output of run_cases.sh: the tables of the model, the types of the positions and the 792 cases"),
    ]),
    ("The sign test", [
        ("q3_signtest_run.log", "Console output of run_signtest.sh 400"),
        ("q3_signtest_L0.log", "Output of q3_signtest.py, cap 0"),
        ("q3_signtest_L1.log", "Output of q3_signtest.py, cap 1"),
    ]),
    ("The test of the masks", [
        ("q3_masks_test.log", "Console output of run_masks_test.sh and of q3_masks_summary.py"),
        ("q3_masks_intact.txt", "The intact mask of 308 directions, cap 0"),
        ("q3_masks_dual.txt", "The dual mask of 308 directions, cap 0"),
        ("q3_masks_p1s0.txt", "The strict mask for one puncture (class 0), cap 0"),
        ("q3_masks_p1s1.txt", "The strict mask for one puncture (class 1), cap 0"),
        ("q3_masks_p1w0.txt", "The weak mask for one puncture (class 0), cap 0"),
        ("q3_masks_p2.txt", "The strict mask for two punctures (classes 0 and 1), cap 0"),
    ]),
    ("The second run of four scripts in a copy of the tree, after the change of the variable W", [
        ("q3_cases_second.log", "Second run of run_cases.sh"),
        ("q3_masks_test_second.log", "Second run of run_masks_test.sh"),
        ("replay_check16_second.log", "Second run of run_replay_check16.sh"),
        ("q3_signtest_run_second.log", "Second run of run_signtest.sh 400: console output"),
        ("q3_signtest_L0_second.log", "Second run of run_signtest.sh 400, cap 0"),
        ("q3_signtest_L1_second.log", "Second run of run_signtest.sh 400, cap 1"),
    ]),
    ("The dump of the 236-cap", [
        ("q3_dump236.txt", "Output of q3_check dump236"),
    ]),
]


def names():
    return [name for _title, items in SECTIONS for name, _what in items]


def main():
    out, logdir = sys.argv[1:3]
    texts, replaced = {}, 0
    for name in names():
        path = os.path.join(logdir, name)
        if not os.path.isfile(path):
            print("ERROR: the log %s is not found" % name)
            return 1
        with open(path, encoding="utf-8", errors="replace") as f:
            raw = f.read().rstrip("\n")
        texts[name] = clean(raw)
        replaced += raw.count(ROOT)
    parts = []
    readme = ["Logs of my report on IIS-Q-0003 (Cap Set).  Each log starts with a line ===== and its file name.",
              "All times are UTC.  The scripts that made these logs are uploaded with this file.",
              "The path of the root of my workspace is replaced by <W> in %d lines." % sum(t.count("<W>") for t in texts.values())]
    for title, items in SECTIONS:
        readme += ["", title]
        readme += ["- %s: %s" % (name, what) for name, what in items]
    parts.append("\n".join(["===== README"] + readme))
    for title, items in SECTIONS:
        lines = ["", "##### " + title]
        for name, _what in items:
            lines += ["===== " + name, texts[name]]
        parts.append("\n".join(lines))
    body = "\n".join(parts) + "\n"
    with open(out, "w", encoding="utf-8") as f:
        f.write(body)
    print("log file bytes %d; lines %d; logs %d; path replaced %d times" % (len(body.encode("utf-8")), body.count("\n"), len(names()), replaced))
    return 0


if __name__ == "__main__":
    sys.exit(main())
