#!/usr/bin/env python3
"""lab: stage, verify and recover the Stockroom project for every part of the lab.

The project at the start of part N is built by layering overlays:
    parts/01/start + parts/01/solution + ... + parts/N-1/solution + parts/N/start
and the reference end of part N adds parts/N/solution. Each part has PROMPTS.md (what to send to Codex) and
checks.txt (the acceptance checks: structure and behaviour, never the model's wording).
"""
from __future__ import annotations

import argparse
import ast
import os
import shutil
import subprocess
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
PARTS = ROOT / "parts"
STAGE = Path(os.environ.get("STOCKROOM_STAGE", Path.home() / "stockroom"))
TESTS = ["python3", "-m", "unittest", "discover", "-s", "tests"]


def parts() -> list[Path]:
    """Return the part folders in order."""
    return sorted(p for p in PARTS.iterdir() if p.is_dir() and p.name[:2].isdigit())


def part(number: str) -> Path:
    """Return the folder of part `number`, or stop with a message."""
    key = f"{int(number):02d}" if number.isdigit() else number
    for p in parts():
        if p.name.startswith(key + "-"):
            return p
    sys.exit(f"unknown part {number!r}; run `bin/lab list`")


def overlay(src: Path, dest: Path) -> list[str]:
    """Copy an overlay onto dest and return the relative paths it wrote."""
    written = []
    if src.is_dir():
        for item in sorted(src.rglob("*")):
            rel = item.relative_to(src)
            if "__pycache__" in rel.parts or item.is_dir():
                continue
            (dest / rel).parent.mkdir(parents=True, exist_ok=True)
            shutil.copy2(item, dest / rel)
            written.append(str(rel))
    return written


def build(number: str, dest: Path, solved: bool) -> None:
    """Layer the overlays up to the start (or the reference end) of part `number`."""
    target = part(number)
    for p in parts():
        overlay(p / "start", dest)
        if p == target and not solved:
            return
        overlay(p / "solution", dest)
        if p == target:
            return


def git(dest: Path, *args: str) -> None:
    """Run git in dest with a neutral identity when none is configured."""
    env = dict(os.environ)
    for key, value in (("GIT_AUTHOR_NAME", "Student"), ("GIT_AUTHOR_EMAIL", "student@example.com"),
                       ("GIT_COMMITTER_NAME", "Student"), ("GIT_COMMITTER_EMAIL", "student@example.com")):
        env.setdefault(key, value)
    subprocess.run(["git", *args], cwd=dest, check=True, stdout=subprocess.DEVNULL, env=env)


def fresh(dest: Path, force: bool) -> None:
    """Make dest an empty folder; refuse to replace an existing one without --force."""
    if dest.exists() and any(dest.iterdir()):
        if not force:
            sys.exit(f"{dest} is not empty; add --force to replace it")
        shutil.rmtree(dest)
    dest.mkdir(parents=True, exist_ok=True)


def commit(dest: Path, number: str, message: str) -> None:
    """Make dest a repository with one commit, and note which part it holds."""
    git(dest, "init", "-q", "-b", "main")
    git(dest, "add", "-A")
    git(dest, "commit", "-q", "-m", message)
    (dest / ".git" / "lab-part").write_text(part(number).name[:2] + "\n")


def cmd_list(_: argparse.Namespace) -> None:
    for p in parts():
        title = (p / "PROMPTS.md").read_text(encoding="utf-8").splitlines()[0].lstrip("# ").strip()
        print(f"{p.name[:2]}  {title.split(': ', 1)[-1]}")


def cmd_stage(args: argparse.Namespace) -> None:
    fresh(args.dir, args.force)
    build(args.part, args.dir, solved=False)
    commit(args.dir, args.part, f"start of part {part(args.part).name[:2]}")
    print(f"Staged part {part(args.part).name[:2]} at {args.dir}")
    print(f"Prompts: {part(args.part) / 'PROMPTS.md'}")


def cmd_checkpoint(args: argparse.Namespace) -> None:
    fresh(args.dir, args.force)
    build(args.part, args.dir, solved=True)
    commit(args.dir, args.part, f"reference end of part {part(args.part).name[:2]}")
    print(f"Reference end of part {part(args.part).name[:2]} at {args.dir}")


def cmd_fallback(args: argparse.Namespace) -> None:
    if not (args.dir / ".git").is_dir():
        sys.exit(f"{args.dir} is not a staged project; run `bin/lab stage {args.part}` first")
    for rel in overlay(part(args.part) / "solution", args.dir):
        print(f"  reference: {rel}")
    print("Loaded the reference result. Read `git diff` before you go on.")


def cmd_diff(args: argparse.Namespace) -> None:
    for item in sorted((part(args.part) / "solution").rglob("*")):
        if item.is_file():
            print(item.relative_to(part(args.part) / "solution"))


def checks(dest: Path) -> list[tuple[str, str, str]]:
    """Return (name, command, expected substring) for the part that dest holds."""
    marker = dest / ".git" / "lab-part"
    if not marker.exists():
        sys.exit(f"{dest} was not staged by this lab; run `bin/lab stage <part>` first")
    rows = []
    for line in (part(marker.read_text().strip()) / "checks.txt").read_text(encoding="utf-8").splitlines():
        if line.strip() and not line.startswith("#"):
            name, command, expected = ([x.strip() for x in line.split("::")] + [""])[:3]
            rows.append((name, command, expected))
    return rows


def cmd_verify(args: argparse.Namespace) -> None:
    env = {**os.environ, "LAB_TOOL": str(Path(__file__).resolve()), "PYTHONDONTWRITEBYTECODE": "1"}
    failed = 0
    for name, command, expected in checks(args.dir):
        r = subprocess.run(["bash", "-c", command], cwd=args.dir, env=env, capture_output=True, text=True)
        out = (r.stdout + r.stderr).strip()
        ok = r.returncode == 0 and (not expected or expected in out)
        failed += not ok
        print(f"{'PASS' if ok else 'FAIL'}  {name}")
        if not ok:
            print("      " + (out.splitlines()[-1][:150] if out else f"exit code {r.returncode}"))
    print(f"{'All checks passed' if not failed else str(failed) + ' check(s) failed'} for part "
          f"{(args.dir / '.git' / 'lab-part').read_text().strip()}")
    sys.exit(1 if failed else 0)


def cmd_docstrings(args: argparse.Namespace) -> None:
    missing = [f"{p.name}:{n.name}" for p in sorted(Path(args.folder).glob("*.py"))
               for n in ast.walk(ast.parse(p.read_text(encoding="utf-8")))
               if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and not ast.get_docstring(n)]
    print("missing a docstring: " + ", ".join(missing) if missing else "all documented")
    sys.exit(1 if missing else 0)


def cmd_preflight(_: argparse.Namespace) -> None:
    import tempfile
    failed = 0
    for tool, command in (("python3", ["python3", "--version"]), ("git", ["git", "--version"]),
                          ("codex", ["codex", "--version"])):
        try:
            text = subprocess.run(command, capture_output=True, text=True, check=True).stdout.strip()
        except (OSError, subprocess.CalledProcessError):
            text, failed = "MISSING", failed + 1
        print(f"{tool:8} {text}")
    for p in parts():
        with tempfile.TemporaryDirectory() as folder:
            build(p.name[:2], Path(folder), solved=True)
            r = subprocess.run(TESTS, cwd=folder, capture_output=True, text=True,
                               env={**os.environ, "PYTHONDONTWRITEBYTECODE": "1"})
            last = (r.stdout + r.stderr).strip().splitlines()[-1]
            failed += r.returncode != 0
            print(f"part {p.name[:2]}  reference builds, tests: {last}")
    print("preflight ok" if not failed else f"preflight: {failed} problem(s)")
    sys.exit(1 if failed else 0)


def main() -> None:
    parser = argparse.ArgumentParser(prog="lab", description=__doc__.splitlines()[0])
    sub = parser.add_subparsers(dest="command", required=True)
    sub.add_parser("list", help="list the parts").set_defaults(func=cmd_list)
    for name, func, text in (("stage", cmd_stage, "build the start of a part, with a baseline commit"),
                             ("checkpoint", cmd_checkpoint, "build the reference end of a part")):
        p = sub.add_parser(name, help=text)
        p.add_argument("part")
        p.add_argument("--dir", type=Path, default=STAGE)
        p.add_argument("--force", action="store_true")
        p.set_defaults(func=func)
    p = sub.add_parser("fallback", help="load the reference result of a part into the staged project")
    p.add_argument("part")
    p.add_argument("--dir", type=Path, default=STAGE)
    p.set_defaults(func=cmd_fallback)
    p = sub.add_parser("verify", help="run the acceptance checks of the staged part")
    p.add_argument("--dir", type=Path, default=STAGE)
    p.set_defaults(func=cmd_verify)
    p = sub.add_parser("diff", help="the files that a part's reference result writes")
    p.add_argument("part")
    p.set_defaults(func=cmd_diff)
    p = sub.add_parser("docstrings", help="check that every function in a folder has a docstring")
    p.add_argument("folder")
    p.set_defaults(func=cmd_docstrings)
    sub.add_parser("preflight", help="check the tools and every reference result").set_defaults(func=cmd_preflight)
    args = parser.parse_args()
    args.func(args)


if __name__ == "__main__":
    main()
