#!/usr/bin/env python3
"""Collects the test results behind a slice gate's test scenarios into a PRS 17.3 record (ADR-HIS-089).

  collect_tests.py --slice RC-1 --results <dir> --out <dir> [--defects defects.json] [--tester "..."]

<dir> given to --results holds one folder per build folder that was tested, named as the build folder
with "/" replaced by "__" (services__adm-identity), each with what that folder's tests wrote:
  - Gradle JUnit XML (TEST-*.xml, any depth), for Java units;
  - test/out/results.json of a script unit (platform/gateways, network-protection, supply-chain);
  - junit.xml of Vitest, for web packages;
  - status.txt: the exit status of the folder's build and tests, and log.txt, its output.

A test is linked to a test scenario (TEST-XXX-NNN) and a requirement when the identifier is in its name,
its covers, its description, or a class-level @Tag of its source file (session rule 5). The scenarios
are those of the slice gate in docs/implementation_plan/delivery/gates/<GROUP>.md. The record is
tests.json, tests.md and SHA256SUMS. Python standard library only; synthetic data only."""

import argparse
import datetime
import glob
import hashlib
import json
import os
import platform
import re
import subprocess
import sys
import xml.etree.ElementTree as ET

REPO = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", ".."))
ID = re.compile(r"\b(TEST-[A-Z]{3}-\d{3}|WF-[A-Z]{3}-\d{3}|FR-[A-Z]{3}-[A-Z]{3}-\d{3})\b")


def gate_scenarios(slice_id):
    group = slice_id.split("-")[0]
    text = open(os.path.join(REPO, "docs/implementation_plan/delivery/gates", f"{group}.md"), encoding="utf-8").read()
    start = text.index(f'<a id="{slice_id.lower()}"></a>')
    end = text.find('<a id="', start + 10)
    rows = []
    for line in text[start:end if end > 0 else None].splitlines():
        if not line.startswith("| [TEST-"):
            continue
        cells = [c.strip() for c in line.strip().strip("|").split("|")]
        rows.append({
            "testCaseId": re.search(r"TEST-[A-Z]{3}-\d{3}", cells[0]).group(0),
            "requirementIds": re.findall(r"\[(FR-[A-Z]{3}-[A-Z]{3}-\d{3})\]", cells[1]),
            "scenario": cells[2], "type": cells[3], "expectedResult": cells[4],
        })
    # The specification workflows of the gate's criterion 2, as test cases of their own.
    for line in text[start:end if end > 0 else None].splitlines():
        if "specification workflows pass end to end" in line:
            for wf, title in re.findall(r"\[(WF-[A-Z]{3}-\d{3})\]\([^)]*\) ([^;|]+)", line):
                rows.append({"testCaseId": wf, "requirementIds": [], "scenario": title.strip(),
                             "type": "Workflow", "expectedResult": "The workflow passes end to end"})
            break
    return rows


def class_tags(folder):
    """Identifiers named at class level (before the first method) of each Java test source, by class name."""
    tags = {}
    for path in glob.glob(os.path.join(REPO, folder, "**/src/test/**/*.java"), recursive=True):
        src = open(path, encoding="utf-8", errors="replace").read()
        m = re.search(r"^\s*(?:public\s+|final\s+|abstract\s+)*(?:class|interface)\s+(\w+)", src, re.M)
        if not m:
            continue
        head = src[:m.end()]
        pkg = re.search(r"^package\s+([\w.]+);", src, re.M)
        name = (pkg.group(1) + "." if pkg else "") + m.group(1)
        tags[name] = set(ID.findall(head))
    return tags


def junit_cases(path):
    out = []
    try:
        root = ET.parse(path).getroot()
    except ET.ParseError:
        return out
    for tc in root.iter("testcase"):
        outcome = "passed"
        detail = ""
        for kind, val in (("failure", "failed"), ("error", "error"), ("skipped", "skipped")):
            el = tc.find(kind)
            if el is not None:
                outcome = val
                detail = (el.get("message") or el.text or "")[:500]
                break
        out.append({"suite": tc.get("classname", ""), "name": tc.get("name", ""), "outcome": outcome,
                    "detail": detail})
    return out


def collect(results_dir):
    tests = []
    folders = {}
    for d in sorted(os.listdir(results_dir)):
        path = os.path.join(results_dir, d)
        if not os.path.isdir(path):
            continue
        folder = d.replace("__", "/")
        status_file = os.path.join(path, "status.txt")
        status = open(status_file).read().strip() if os.path.exists(status_file) else "unknown"
        folders[folder] = {"exitStatus": status}
        tags = class_tags(folder) if os.path.isdir(os.path.join(REPO, folder)) else {}
        n = 0
        for x in glob.glob(os.path.join(path, "**/*.xml"), recursive=True):
            for c in junit_cases(x):
                ids = set(ID.findall(c["name"] + " " + c["suite"])) | tags.get(c["suite"], set())
                tests.append({"folder": folder, **c, "ids": sorted(ids)})
                n += 1
        for r in glob.glob(os.path.join(path, "**/results.json"), recursive=True):
            data = json.load(open(r, encoding="utf-8"))
            for c in data if isinstance(data, list) else data.get("results", data.get("tests", [])):
                text = " ".join([c.get("test", ""), c.get("description", ""), " ".join(c.get("covers", []))])
                tests.append({"folder": folder, "suite": c.get("test", "").rsplit(".", 1)[0],
                              "name": c.get("test", "").rsplit(".", 1)[-1] + (" " + c["description"] if c.get("description") else ""),
                              "outcome": {"error": "error"}.get(c.get("outcome"), c.get("outcome", "unknown")),
                              "detail": (c.get("detail") or "")[:500], "ids": sorted(set(ID.findall(text)))})
                n += 1
        folders[folder]["tests"] = n
        failing = [t for t in tests if t["folder"] == folder and t["outcome"] in ("failed", "error")]
        folders[folder]["failed"] = len(failing)
        # A failed build is explained when each failing test names what it covers; otherwise (no failing
        # test, or a class that did not start) tests may not have run, and no pass in the folder is sure.
        folders[folder]["unexplained"] = status != "0" and (not failing or any(not t["ids"] for t in failing))
    return tests, folders


def git(*args):
    return subprocess.run(["git", "-C", REPO, *args], capture_output=True, text=True).stdout.strip()


def tool_version(cmd):
    try:
        return subprocess.run(cmd, capture_output=True, text=True, timeout=30).stdout.strip().splitlines()[0]
    except Exception:  # noqa: BLE001 - a missing tool is recorded as such
        return "not available"


def main():
    p = argparse.ArgumentParser()
    p.add_argument("--slice", required=True)
    p.add_argument("--results", required=True)
    p.add_argument("--out", required=True)
    p.add_argument("--defects", help="JSON: {TEST id: [issue references]}")
    p.add_argument("--notes", help="JSON: {TEST id: note on the outcome}")
    p.add_argument("--tester", default="gate evidence session (agent)")
    p.add_argument("--session", default=os.environ.get("HIS_SESSION", ""))
    p.add_argument("--checkout", default="this checkout",
                   help='where the tests ran, for example "a git archive export of the commit"')
    a = p.parse_args()

    tests, folders = collect(a.results)
    defects = json.load(open(a.defects)) if a.defects else {}
    notes = json.load(open(a.notes)) if a.notes else {}
    commit = git("rev-parse", "HEAD")
    build = {"commit": commit, "dirty": bool(git("status", "--porcelain", "--", *folders.keys())),
             "components": [{"folder": f, "tree": git("rev-parse", f"HEAD:{f}")} for f in folders]}
    environment = {
        "host": platform.platform(), "session": a.session, "profile": "light (Java units), Docker for script units",
        "jdk": subprocess.run(["java", "-version"], capture_output=True, text=True).stderr.splitlines()[0],
        "node": tool_version(["node", "--version"]), "python": platform.python_version(),
        "docker": tool_version(["docker", "--version"]), "checkout": a.checkout,
    }
    now = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds")
    record = {"slice": a.slice, "kind": "test scenarios of the slice gate (PRS 17.3)", "generatedAt": now,
              "build": build, "environment": environment, "testDataClassification": "synthetic",
              "tester": a.tester, "approver": "pending", "folders": folders, "testCases": []}
    for s in gate_scenarios(a.slice):
        linked = [t for t in tests if s["testCaseId"] in t["ids"]]
        if not linked:
            outcome = "no test"
        elif any(t["outcome"] in ("failed", "error") for t in linked):
            outcome = "failed"
        elif all(t["outcome"] == "skipped" for t in linked):
            outcome = "skipped"
        else:
            outcome = "passed"
        # A folder whose build failed may have tests that never ran (a class that did not start names
        # no scenario), so a pass that rests on such a folder is not a pass, unless every failure in it is a
        # test that names what it covers.
        broken = sorted({t["folder"] for t in linked if folders[t["folder"]]["unexplained"]})
        if outcome == "passed" and broken:
            outcome = "inconclusive"
        record["testCases"].append({
            **s, "build": commit, "environment": a.session, "testDataClassification": "synthetic",
            "tester": a.tester, "date": now[:10], "outcome": outcome,
            "defectReferences": defects.get(s["testCaseId"], []), "approver": "pending", "waiver": None,
            "note": " ".join(x for x in [notes.get(s["testCaseId"], ""),
                             ("The build of " + ", ".join(broken) + " failed.") if broken else ""] if x),
            "tests": [{k: t[k] for k in ("folder", "suite", "name", "outcome", "detail") if t.get(k) or k != "detail"} for t in linked],
        })
    os.makedirs(a.out, exist_ok=True)
    with open(os.path.join(a.out, "tests.json"), "w", encoding="utf-8") as f:
        json.dump(record, f, indent=2, ensure_ascii=False)
        f.write("\n")
    write_md(record, os.path.join(a.out, "tests.md"))
    with open(os.path.join(a.out, "SHA256SUMS"), "w") as f:
        for name in ("tests.json", "tests.md"):
            f.write(hashlib.sha256(open(os.path.join(a.out, name), "rb").read()).hexdigest() + "  " + name + "\n")
    counts = {}
    for c in record["testCases"]:
        counts[c["outcome"]] = counts.get(c["outcome"], 0) + 1
    print(json.dumps(counts))


def write_md(r, path):
    L = [f"# Test scenarios of slice gate {r['slice']}: test results (PRS 17.3)", "",
         "Generated by `collect_tests.py` (ADR-HIS-089). Do not edit by hand; `tests.json` is the record.", "",
         "| Field | Value |", "|---|---|",
         f"| Build | commit `{r['build']['commit']}`{' (uncommitted changes)' if r['build']['dirty'] else ''}; component trees in `tests.json` |",
         f"| Environment | {r['environment']['host']}; session `{r['environment']['session']}`; {r['environment']['jdk']}; Node.js {r['environment']['node']}; Python {r['environment']['python']}; {r['environment']['docker']}; tests ran in {r['environment']['checkout']} |",
         f"| Test data classification | {r['testDataClassification']} |", f"| Tester | {r['tester']} |",
         f"| Date | {r['generatedAt']} |", f"| Approver | {r['approver']} |", "",
         "## Build folders", "", "| Folder | Build and tests exit status | Tests | Failed |", "|---|---|---|---|"]
    for f, v in r["folders"].items():
        L.append(f"| `{f}` | {v['exitStatus']} | {v['tests']} | {v['failed']} |")
    L += ["", "## Test scenarios", "",
          "| Test case | Requirements | Outcome | Tests (passed/total) | Defects | Waiver | Note |", "|---|---|---|---|---|---|---|"]
    for c in r["testCases"]:
        ok = sum(1 for t in c["tests"] if t["outcome"] == "passed")
        L.append(f"| {c['testCaseId']} | {', '.join(c['requirementIds'])} | **{c['outcome']}** | {ok}/{len(c['tests'])} | "
                 f"{', '.join(c['defectReferences']) or '—'} | {c['waiver'] or '—'} | {c['note'] or ''} |")
    L += ["", "## Tests behind each scenario", ""]
    for c in r["testCases"]:
        L += [f"### {c['testCaseId']}", "", f"{c['scenario']}. Expected: {c['expectedResult']}", ""]
        if not c["tests"]:
            L += ["No test names this scenario.", ""]
            continue
        L += ["| Folder | Test | Outcome |", "|---|---|---|"]
        for t in c["tests"]:
            name = (t["suite"].rsplit(".", 1)[-1] + " › " + t["name"]).replace("|", "\\|")
            L.append(f"| `{t['folder']}` | {name} | {t['outcome']} |")
        L.append("")
    open(path, "w", encoding="utf-8").write("\n".join(L) + "\n")


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