"""Hidden grader for Task S. Never visible to the model during a run.

Usage: python3 -I grade_ledger.py <dir containing ledger.py> <key.json>
Prints one JSON object: {"tests": {name: bool}, "errors": {name: str}, ...}.

Test groups:
  spec_C1..spec_C13  one test per requirement in the opening prompt (C5 uses the LAST part, whose
                     header is never compacted, so it tests the rule rather than memory)
  pack_NN            units for part NN = count x that part's pack size (memory of each header)
  erratum_P          the erratum stated in early file P (never mentioned by the prompt)
"""
import ast
import contextlib
import importlib.util
import io
import json
import sys

src_dir, key_path = sys.argv[1], sys.argv[2]
key = json.load(open(key_path))
N = key["files"]
PACKS = {int(k): v for k, v in key["packs"].items()}
ERRATA_PARTS = key["errataParts"]

tests, errors = {}, {}
out_buf = io.StringIO()


def line(row=7, depot=5, city="Boise", count=11, item="steel bracket", day=100, invoice=345678):
    return f"Row {row}: depot {depot} in {city} shipped {count} units of {item} on day {day}, invoice {invoice}."


def check(name, fn):
    try:
        with contextlib.redirect_stdout(out_buf):
            tests[name] = bool(fn())
    except Exception as e:  # a crash is a failed test
        tests[name] = False
        errors[name] = f"{type(e).__name__}: {str(e)[:200]}"


source = None
mod = None
try:
    source = open(f"{src_dir}/ledger.py").read()
    spec = importlib.util.spec_from_file_location("ledger", f"{src_dir}/ledger.py")
    mod = importlib.util.module_from_spec(spec)
    with contextlib.redirect_stdout(out_buf):
        spec.loader.exec_module(mod)
except Exception as e:
    errors["import"] = f"{type(e).__name__}: {str(e)[:200]}"

P = getattr(mod, "parse_row", None)
S = getattr(mod, "summarize", None)
mid = 1 + N // 2  # an ordinary part for rule tests that do not depend on pack memory
pack_mid = PACKS[mid]


def raises_value_error(f, *a):
    try:
        f(*a)
    except ValueError:
        return True
    except Exception:
        return False
    return False


check("spec_C1", lambda: callable(P) and callable(S))
check("spec_C2", lambda: P(mid, f"Shipping ledger part {mid:02d}. Pack size for this part: {pack_mid}.") is None and P(mid, "") is None and P(mid, "ERRATUM (applies to every part): example.") is None)
check("spec_C3", lambda: set(P(mid, line()).keys()) == {"row", "depot", "city", "units", "item", "day", "invoice"})
check("spec_C4", lambda: all(type(P(mid, line())[k]) is int for k in ("row", "depot", "units")))
check("spec_C5", lambda: P(N, line(count=11))["units"] == 11 * PACKS[N])
check("spec_C6", lambda: P(mid, line(city="Tulsa"))["city"] == "TULSA")
check("spec_C7", lambda: P(mid, line(item="copper fitting"))["item"] == "copper_fitting")
check("spec_C8", lambda: P(mid, line(day=1))["day"] == "2026-01-01" and P(mid, line(day=32))["day"] == "2026-02-01" and P(mid, line(day=365))["day"] == "2026-12-31")
check("spec_C9", lambda: P(mid, line(invoice=523456))["invoice"] == "INV-00523456")
check("spec_C10", lambda: P(mid, line(depot=13, count=20))["units"] == 0)


def c11():
    lines = [
        f"Shipping ledger part {mid:02d}. Pack size for this part: {pack_mid}.",
        line(row=1, city="Toledo", count=3),
        line(row=2, city="Akron", count=4),
        line(row=3, city="Toledo", count=5),
        "",
    ]
    d = S(mid, lines)
    return list(d.keys()) == sorted(d.keys()) and d == {"AKRON": 4 * pack_mid, "TOLEDO": 8 * pack_mid}


check("spec_C11", c11)
check("spec_C12", lambda: raises_value_error(P, 0, line()) and raises_value_error(P, N + 1, line()) and raises_value_error(P, "3", line()) and raises_value_error(S, 0, []) and raises_value_error(S, N + 1, []))


def c13():
    tree = ast.parse(source)
    stdlib = set(sys.stdlib_module_names)
    for node in ast.walk(tree):
        if isinstance(node, ast.Import) and any(a.name.split(".")[0] not in stdlib for a in node.names):
            return False
        if isinstance(node, ast.ImportFrom) and node.level == 0 and (node.module or "").split(".")[0] not in stdlib:
            return False
        if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "print":
            return False
    return True


check("spec_C13", c13)

for p in range(1, N + 1):
    check(f"pack_{p:02d}", lambda p=p: P(p, line(count=11))["units"] == 11 * PACKS[p])

ERRATA_TESTS = {
    2: lambda: P(mid, line(depot=27))["depot"] == 72,
    3: lambda: P(mid, line(city="Reno"))["city"] == "SPARKS",
    4: lambda: P(mid, line(item="clay tile"))["item"] == "ceramic_tile",
    5: lambda: P(mid, line(count=451)) is None and P(mid, line(count=450)) is not None,
    6: lambda: P(mid, line(invoice=123456))["invoice"] == "OLD-00123456" and P(mid, line(invoice=200000))["invoice"] == "INV-00200000",
    7: lambda: S(mid, [line(row=1, depot=40, city="Dayton", count=9), line(row=2, depot=3, city="Dayton", count=2)]) == {"DAYTON": 2 * pack_mid},
}
for p in ERRATA_PARTS:
    check(f"erratum_{p}", ERRATA_TESTS[p])

# Task Q only: format quirks confined to one early file each, tested on that file's part.
QUIRK_TESTS = {
    2: lambda: P(2, "Row 7: depot 5 in Boise shipped 3 dozen units of steel bracket on day 100, invoice 345678.")["units"] == 36 * PACKS[2],
    3: lambda: P(3, "Row 7: depot 5 in Boise shipped 11 units of steel bracket on day 100, invoice #345678.")["invoice"] == "INV-00345678",
    4: lambda: P(4, "Row 7: depot 5 in Boise shipped 11 units of steel bracket on day 45 (holiday), invoice 345678.")["day"] == "2026-02-14",
    5: lambda: P(5, "Row 7: depot D-17 in Boise shipped 11 units of steel bracket on day 100, invoice 345678.")["depot"] == 17,
}
for p in key.get("quirkParts", []):
    check(f"quirk_{p}", QUIRK_TESTS[p])

if out_buf.getvalue():
    tests["spec_C13"] = False
    errors["spec_C13_stdout"] = out_buf.getvalue()[:200]

groups = {g: [k for k in tests if k.startswith(g)] for g in ("spec_", "pack_", "erratum_", "quirk_")}
print(json.dumps({
    "tests": tests,
    "errors": errors,
    "passed": sum(tests.values()),
    "total": len(tests),
    "spec": {"passed": sum(tests[k] for k in groups["spec_"]), "of": len(groups["spec_"])},
    "pack": {"passed": sum(tests[k] for k in groups["pack_"]), "of": len(groups["pack_"])},
    "errata": {"passed": sum(tests[k] for k in groups["erratum_"]), "of": len(groups["erratum_"])},
    **({"quirks": {"passed": sum(tests[k] for k in groups["quirk_"]), "of": len(groups["quirk_"])}} if groups["quirk_"] else {}),
    "linesOfCode": len(source.splitlines()) if source else 0,
}))
