"""Offline authored incident inputs and a public mechanical grader.

No provider, service, production or generic student solution is included.
Only import a student file you control: module import executes Python code.
"""
import argparse
import copy
import hashlib
import importlib.util
import json
from pathlib import Path
import sys

LAB_VERSION = "incident-lab-v3"
CASES_PATH = Path(__file__).with_name("incident-cases.json")
COUNT_KEYS = {"task_count", "acceptance_known", "accepted_tasks", "pending_tasks",
              "rounds_total", "tool_call_count", "tool_403_count", "tool_retry_count"}
RATE_KEYS = {"acceptance_rate", "rounds_per_task", "tool_403_rate"}
sys.dont_write_bytecode = True


def digest(value):
    return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":")).encode()).hexdigest()


def manifest():
    data = json.loads(CASES_PATH.read_text())
    if data.get("schema_version") != 1 or data.get("lab_version") != LAB_VERSION:
        raise ValueError("case_manifest_version")
    return data


def materialize(data, key):
    indexes = data["datasets"][key]
    return {kind: [copy.deepcopy(data["records"][i]) for i in indexes[kind]] for kind in ["tasks", "events"]}


def fixture(case):
    data = manifest()
    if case not in data["fixtures"]:
        raise ValueError("unknown_case")
    return {"schema_version": 1, "source": "authored_redacted_fixture", "case": case,
            "clock": "logical milliseconds; not measured latency", **materialize(data, data["fixtures"][case])}


def output_shape(actual, function):
    if function == "summarize":
        return (type(actual) is dict and set(actual) == COUNT_KEYS | RATE_KEYS
                and all(type(actual[k]) is int for k in COUNT_KEYS)
                and all(actual[k] is None or type(actual[k]) is float for k in RATE_KEYS))
    return (type(actual) is dict and set(actual) == {"stage", "event_id", "reason"}
            and type(actual["stage"]) is str and type(actual["reason"]) is str
            and (actual["event_id"] is None or type(actual["event_id"]) is str))


def grade(student_path):
    student_path = Path(student_path).resolve()
    data = manifest()
    spec = importlib.util.spec_from_file_location("incident_student", student_path)
    if spec is None or spec.loader is None:
        raise ValueError("student_import")
    module = importlib.util.module_from_spec(spec)
    sys.modules["incident_student"] = module
    spec.loader.exec_module(module)
    own = all(callable(getattr(module, name, None)) and getattr(getattr(module, name), "__module__", None) == "incident_student"
              for name in ["summarize", "first_failure"])
    checks = []
    def record(name, passed, details):
        try:
            json.dumps(details)
        except (TypeError, ValueError):
            details = {"non_json_details": repr(details)}
        checks.append({"name": name, "passed": bool(passed), "details": details})
    record("student_functions", own, {"required": ["summarize", "first_failure"], "direct_import_alias_allowed": False})
    if own:
        for case in data["checks"]:
            inputs = materialize(data, case["dataset"])
            args = (inputs["tasks"], inputs["events"]) if case["function"] == "summarize" else (inputs["tasks"][0], inputs["events"])
            before = digest(args)
            kwargs = copy.deepcopy(case.get("kwargs", {}))
            try:
                actual = getattr(module, case["function"])(*args, **kwargs)
            except Exception as exc:
                passed = ("expected_error" in case and type(exc) is ValueError
                          and str(exc) == case["expected_error"] and digest(args) == before)
                record(case["name"], passed, {"expected_error": case.get("expected_error"),
                       "actual_error": type(exc).__name__ + ":" + str(exc), "input_unchanged": digest(args) == before})
            else:
                passed = ("expected" in case and output_shape(actual, case["function"])
                          and actual == case["expected"] and digest(args) == before)
                record(case["name"], passed, {"expected": case.get("expected"), "actual": actual,
                       "expected_error": case.get("expected_error"), "input_unchanged": digest(args) == before})
    return {"source": "public_mechanical_grader", "lab_version": LAB_VERSION,
            "cases_sha256": hashlib.sha256(CASES_PATH.read_bytes()).hexdigest(),
            "student_sha256": hashlib.sha256(student_path.read_bytes()).hexdigest(),
            "passed": all(c["passed"] for c in checks), "passed_checks": sum(c["passed"] for c in checks),
            "total_checks": len(checks), "checks": checks,
            "limits": "public fixed inputs and expected outputs; no authorship, semantic, production or unseen-interview certification"}


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("command", choices=["scaffold", "sample", "guided", "grade"])
    parser.add_argument("--case", choices=["amber", "violet"], default="amber")
    parser.add_argument("--module")
    parser.add_argument("--out", required=True)
    args = parser.parse_args(argv)
    if args.command == "scaffold":
        out = Path(args.out)
        if out.exists():
            parser.error("scaffold refuses to overwrite an existing student file")
        out.parent.mkdir(parents=True, exist_ok=True)
        out.write_text('''"""Implement both contracts yourself; disclose any guided/reference assistance."""

def summarize(tasks, events, *, version=None, tenant=None, start_ms=None, end_ms=None):
    raise NotImplementedError("implement the complete metrics contract")

def first_failure(task, trace):
    raise NotImplementedError("implement the evidence-stage contract")
''')
        print(json.dumps({"out": str(out), "lab_version": LAB_VERSION, "source": "unimplemented_student_scaffold",
              "sha256": hashlib.sha256(out.read_bytes()).hexdigest()}, sort_keys=True))
        return 0
    try:
        if args.command == "grade":
            if not args.module:
                parser.error("grade requires --module")
            result = grade(args.module)
            exit_code = 0 if result["passed"] else 1
        elif args.command == "sample":
            result, exit_code = fixture(args.case), 0
        else:
            data = manifest()
            result = {"source": "authored_redacted_fixture", "lab_version": LAB_VERSION, "case": args.case,
                      "input_sha256": digest(fixture(args.case)), "metrics": copy.deepcopy(data["guided"][args.case]),
                      "meaning": "stored fixed fixture metrics; not measured provider tokens, cost, latency or an enterprise incident"}
            exit_code = 0
    except Exception as exc:
        result = {"source": "public_mechanical_grader", "lab_version": LAB_VERSION,
                  "passed": False, "setup_error": type(exc).__name__ + ":" + str(exc)}
        exit_code = 2
    out = Path(args.out)
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n")
    print(json.dumps({"out": str(out), "lab_version": LAB_VERSION, "source": result["source"],
          "passed": result.get("passed"), "passed_checks": result.get("passed_checks"),
          "total_checks": result.get("total_checks"), "sha256": hashlib.sha256(out.read_bytes()).hexdigest()}, sort_keys=True))
    return exit_code


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