"""best-before: runs a checklist and issues a certificate of completion
that goes stale with the clock and with the files."""

import sys

if sys.version_info < (3, 11):
    sys.stderr.write("best-before: needs Python 3.11 or newer\n")
    sys.exit(2)

import argparse
import datetime
import hashlib
import json
import os
import re
import signal
import subprocess
import time
import tomllib

TASK_FILE = "best-before.toml"
STATE_DIR = ".best-before"
LEDGER = "ledger.jsonl"
DEFAULT_MAX_AGE = 24 * 3600  # open question in the card: one constant
DEFAULT_TIMEOUT = 10 * 60
MAX_TIMEOUT = 3600
WINDOW = 10  # Laplace window, fixed in this build
TAIL = 20
NAME_RE = re.compile(r"[A-Za-z0-9._-]{1,40}")
CHECK_KEYS = {"name", "run", "watch", "max_age", "timeout"}
UNITS = {"s": 1, "m": 60, "h": 3600, "d": 86400}
DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
          "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

HELP = """\
usage: best_before.py [-f FILE] [--at WHEN] [status]
       best_before.py [-f FILE] run [CHECK ...]
       best_before.py [-f FILE] lot
       best_before.py --help

Runs the checks listed in a task file and issues a certificate of
completion only while every check has fresh green evidence. Evidence
goes stale when the files it was checked against change, or when it
outlives the age its own run history has earned.

commands:
  status      certificate or refusal; runs nothing (the default)
  run         run all checks, or those named, record them, then status
  lot         print the lot of the current files (12 hex)

options:
  -f FILE     task file (default: best-before.toml in this folder)
  --at WHEN   judge as of an ISO 8601 time (status only)
  -h, --help  show this text

exit: 0 certificate issued, 1 not issued, 2 usage or file error.

This does not make the work good. It makes the evidence recent.
"""


class Fail(Exception):
    """A usage, task-file or read error: exit 2, nothing written."""


# task file

def parse_duration(value, units, what):
    m = re.fullmatch(r"([0-9]+)([a-z])", value) if isinstance(value, str) else None
    if not m or m.group(2) not in units:
        raise Fail(f'{what} "{value}" is not a duration ({", ".join(units)})')
    return int(m.group(1)) * UNITS[m.group(2)]


def check_watch_path(base, path):
    if not isinstance(path, str) or not path:
        raise Fail("watch entries must be non-empty strings")
    if os.path.isabs(path) or path.startswith("~"):
        raise Fail(f'watch path "{path}" is absolute')
    if ".." in re.split(r"[\\/]", path):
        raise Fail(f'watch path "{path}" contains ..')
    if not os.path.exists(os.path.join(base, path)):
        raise Fail(f'watch path "{path}" does not exist')


def load_task(path):
    path = os.path.abspath(path)
    try:
        with open(path, "rb") as f:
            data = tomllib.load(f)
    except FileNotFoundError:
        raise Fail(f"no task file at {path}")
    except (OSError, tomllib.TOMLDecodeError) as e:
        raise Fail(f"cannot read the task file: {e}")
    base = os.path.dirname(path)
    unknown = set(data) - {"goal", "check"}
    if unknown:
        raise Fail(f'unknown key "{sorted(unknown)[0]}" in the task file')
    goal = data.get("goal", "")
    if not isinstance(goal, str) or len(goal) > 50 or not goal.isprintable():
        raise Fail("goal must be one line of at most 50 characters")
    raw = data.get("check", [])
    if not isinstance(raw, list) or not all(isinstance(c, dict) for c in raw):
        raise Fail("check must be written as [[check]] tables")
    if not raw:
        raise Fail("Nothing to certify. A certificate for nothing is not issued.")
    checks, seen = [], set()
    for c in raw:
        unknown = set(c) - CHECK_KEYS
        if unknown:
            raise Fail(f'unknown key "{sorted(unknown)[0]}" in a check')
        name = c.get("name")
        if not isinstance(name, str) or not NAME_RE.fullmatch(name):
            raise Fail(f"check name {name!r} must be 1 to 40 of A-Z a-z 0-9 . _ -")
        if name in seen:
            raise Fail(f'two checks are named "{name}"')
        seen.add(name)
        run = c.get("run")
        if not isinstance(run, str) or not run.strip():
            raise Fail(f'check "{name}" has an empty run')
        watch = c.get("watch")
        if watch is not None:
            if not isinstance(watch, list):
                raise Fail(f'check "{name}": watch must be a list')
            for w in watch:
                check_watch_path(base, w)
        max_age = parse_duration(c.get("max_age", "24h"), "mhd", f'check "{name}": max_age')
        if max_age < 60:
            raise Fail(f'check "{name}": max_age is at least 1m')
        timeout = parse_duration(c.get("timeout", "10m"), "smh", f'check "{name}": timeout')
        if not 0 < timeout <= MAX_TIMEOUT:
            raise Fail(f'check "{name}": timeout must be above 0 and at most 1h')
        checks.append({"name": name, "run": run, "watch": watch,
                       "max_age": max_age, "timeout": timeout})
    return {"path": path, "base": base, "goal": goal, "checks": checks}


# watch hash

def file_sha(full, rel):
    try:
        with open(full, "rb") as f:
            return hashlib.file_digest(f, "sha256").hexdigest()
    except FileNotFoundError:
        return "-"
    except OSError as e:
        raise Fail(f"cannot read {rel}: {e.strerror}")


def declared_files(base, watch):
    out = set()
    for w in watch:
        full = os.path.join(base, w)
        if not os.path.isdir(full):
            out.add(os.path.relpath(full, base))
            continue
        for root, dirs, files in os.walk(full):  # symlinked folders are not followed
            dirs[:] = [d for d in dirs if d not in (".git", STATE_DIR)]
            out.update(os.path.relpath(os.path.join(root, f), base) for f in files)
    return out


def in_git(base):
    try:
        r = subprocess.run(["git", "rev-parse", "--is-inside-work-tree"], cwd=base,
                           capture_output=True, text=True)
    except OSError:
        return False
    return r.returncode == 0 and r.stdout.strip() == "true"


def git_files(task):
    r = subprocess.run(["git", "ls-files", "-z", "--cached", "--others", "--exclude-standard"],
                       cwd=task["base"], capture_output=True)
    if r.returncode != 0:
        raise Fail("git ls-files failed: " + r.stderr.decode(errors="replace").strip())
    own = os.path.relpath(task["path"], task["base"])
    names = {os.fsdecode(p) for p in r.stdout.split(b"\0") if p}
    return {p for p in names if p != own and p.split("/")[0] != STATE_DIR}


def tree_hash(base, rels):
    lines = []
    for rel in rels:
        full = os.path.join(base, rel)
        if os.path.isdir(full):
            continue  # Known limit: a git submodule is listed as a folder and is not hashed.
        posix = rel.replace(os.sep, "/")
        lines.append((posix.encode("utf-8", "surrogateescape"), file_sha(full, posix)))
    lines.sort()
    body = b"".join(p + b"\0" + s.encode() + b"\n" for p, s in lines)
    return hashlib.sha256(body).hexdigest()[:12]


class Watcher:
    """Knows how each check watches, and hashes it now.
    Known limit: the whole watched tree is hashed on every status call (fine
    up to a few thousand files; cache by mtime if it ever matters)."""

    def __init__(self, task):
        self.task = task
        self.git = None if all(c["watch"] is not None for c in task["checks"]) else in_git(task["base"])

    def mode(self, check):
        if check["watch"]:
            return "declared"
        return "git" if check["watch"] is None and self.git else "none"

    def text(self, check):
        mode = self.mode(check)
        if mode == "declared":
            return "watches " + plural(len(check["watch"]), "declared path")
        return "watches the git tree" if mode == "git" else "watches nothing (clock only)"

    def hash(self, check):
        mode = self.mode(check)
        if mode == "none":
            return None
        base = self.task["base"]
        files = declared_files(base, check["watch"]) if mode == "declared" else git_files(self.task)
        return tree_hash(base, files)


def lot_of(pairs):
    body = "".join(f"{n}\0{h or '-'}\n" for n, h in sorted(pairs))
    return hashlib.sha256(body.encode()).hexdigest()[:12]


# ledger

def ledger_path(task):
    return os.path.join(task["base"], STATE_DIR, LEDGER)


def read_ledger(task):
    try:
        with open(ledger_path(task), "rb") as f:
            raw = f.read()
    except FileNotFoundError:
        return []
    except OSError as e:
        raise Fail(f"cannot read the ledger: {e.strerror}")
    entries = []
    for i, line in enumerate(raw.splitlines(), 1):
        try:
            e = json.loads(line)
            e["t"] = int(datetime.datetime.strptime(e["at"], "%Y-%m-%dT%H:%M:%SZ")
                         .replace(tzinfo=datetime.timezone.utc).timestamp())
            if not (isinstance(e["check"], str) and isinstance(e["command"], str)
                    and (e["watch"] is None or isinstance(e["watch"], str))):
                raise ValueError("bad field")
            e["green"] = e["exit"] == 0 and e["timeout"] is False
        except Exception:
            sys.stderr.write(f"best-before: ledger line {i} unreadable, ignored\n")
            continue
        entries.append(e)
    return entries


def append_ledger(task, entry):
    folder = os.path.join(task["base"], STATE_DIR)
    if not os.path.isdir(folder):
        os.makedirs(folder)
        with open(os.path.join(folder, ".gitignore"), "w") as f:
            f.write("*\n")
    # Known limit: appends are single writes with no lock; parallel run in one folder is unsupported.
    with open(os.path.join(folder, LEDGER), "a", encoding="utf-8") as f:
        f.write(json.dumps(entry, ensure_ascii=False, separators=(",", ":")) + "\n")


# judging

def earned(history, cap):
    """Laplace's rule: rate = (f + 1) / (t + 2); earned = cap x (1 - rate).
    Returns (numerator, denominator) in seconds, kept exact."""
    t = len(history) - 1
    f = sum(a["green"] != b["green"] for a, b in zip(history, history[1:]))
    return cap * (t + 1 - f), t + 2, f


def judge(check, entries, now, watcher):
    named = [e for e in entries if e["check"] == check["name"] and e["t"] <= now]
    same = [e for e in named if e["command"] == check["run"]]
    v = {"check": check, "fresh": False}
    if not same:
        v["state"] = "never"
        v["changed"] = bool(named)
        return v
    entry = same[-1]
    history = same[-WINDOW:]
    num, den, flips = earned(history, check["max_age"])
    v.update(entry=entry, runs=len(history), flips=flips, earned=num // den,
             expires=(entry["t"] * den + num) // (den * 60) * 60)
    reds = [e for e in history if not e["green"]]
    v["last_failed"] = reds[-1]["t"] if reds else None
    if not entry["green"]:
        v["state"] = "failed"
    elif entry.get("self_edit"):
        v["state"] = "self-edit"
    elif entry["watch"] is not None and watcher.hash(check) != entry["watch"]:
        v["state"] = "edited"
    elif now >= v["expires"]:
        v["state"] = "age"
    else:
        v["state"], v["fresh"] = "fresh", True
    return v


# text

def plural(n, word):
    return f"{n} {word}" if n == 1 else f"{n} {word}s"


def age_text(seconds):
    if seconds < 60:
        return "just now"
    if seconds < 3600:
        return f"{seconds // 60} min ago"
    if seconds < 48 * 3600:
        return f"{seconds // 3600} h ago"
    return f"{seconds // 86400} d ago"


def duration_text(seconds):
    seconds = int(seconds)
    if seconds < 60:
        return f"{seconds} s"
    if seconds < 3600:
        return f"{seconds // 60} min"
    h, m = divmod(seconds // 60, 60)
    return f"{h} h" if m == 0 else f"{h} h {m} min"


def local(epoch):
    return datetime.datetime.fromtimestamp(epoch)


def when_text(epoch, now):
    d, n = local(epoch), local(now)
    hm = d.strftime("%H:%M")
    words = {0: "today", 1: "tomorrow", -1: "yesterday"}
    delta = (d.date() - n.date()).days
    if delta in words:
        return f"{hm} {words[delta]}"
    year = f" {d.year}" if d.year != n.year else ""
    return f"{DAYS[d.weekday()]} {d.day} {MONTHS[d.month - 1]}{year} {hm}"


def issued_text(epoch):
    d = local(epoch)
    return f"{DAYS[d.weekday()]} {d.day} {MONTHS[d.month - 1]} {d.year} {d:%H:%M}"


def bold(word):
    if sys.stdout.isatty() and "NO_COLOR" not in os.environ and os.environ.get("TERM") != "dumb":
        return f"\x1b[1m{word}\x1b[0m"
    return word


REASONS = {
    "edited": ["Files changed since.", "This result describes a tree that no longer exists."],
    "self-edit": ["The command changed the files it was checked against.",
                  "Narrow the watch list or ignore its output."],
}


def check_block(v, now, watcher):
    c, state = v["check"], v["state"]
    lines = [c["name"]]
    if state == "never":
        lines.append("  never run")
        if v["changed"]:
            lines.append("      The command in the task file has changed since the last run.")
        return lines
    e = v["entry"]
    age = age_text(now - e["t"])
    if state == "fresh":
        lines.append(f"  passed {age}, best before {when_text(v['expires'], now)}")
    elif state == "failed":
        how = (f"timed out after {duration_text(c['timeout'])}" if e["timeout"]
               else f"exit {e['exit']}")
        lines.append(f"  {bold('FAILED')}, {how}, {age}")
    else:
        lines.append(f"  {bold('STALE')}, passed {age}, was best before {when_text(v['expires'], now)}")
    watches = watcher.text(c) if e["watch"] is not None else "watches nothing (clock only)"
    lines.append(f"  {plural(v['runs'], 'run')}, {plural(v['flips'], 'flip')}, "
                 f"earned {duration_text(v['earned'])}, {watches}")
    if state == "fresh" and v["last_failed"] is not None:
        lines.append(f"  last failed {when_text(v['last_failed'], now)}")
    if state == "age":
        lines.append(f"      Older than the {duration_text(v['earned'])} it earned.")
    lines += ["      " + r for r in REASONS.get(state, [])]
    return lines


def report(task, now, watcher):
    entries = read_ledger(task)
    verdicts = [judge(c, entries, now, watcher) for c in task["checks"]]
    blocks = [line for v in verdicts for line in check_block(v, now, watcher)]
    goal = [f"Goal    {task['goal']}"] if task["goal"] else []
    total = len(verdicts)
    bad = sum(not v["fresh"] for v in verdicts)
    if bad:
        out = ["NO CERTIFICATE", f"{bad} of {plural(total, 'check')} cannot be certified.", ""]
        out += goal + ([""] if goal else []) + blocks
        out += ["", "Run: best_before.py run", "normal is dead"]
        return "\n".join(out) + "\n", 1
    oldest = min(v["entry"]["t"] for v in verdicts)
    expires = min(v["expires"] for v in verdicts)
    lot = lot_of((v["check"]["name"], v["entry"]["watch"]) for v in verdicts)
    watched = any(v["entry"]["watch"] is not None for v in verdicts)
    out = ["CERTIFICATE OF COMPLETION",
           f"{'Checks' if total > 1 else 'Check'} passed {age_text(now - oldest)}. "
           f"Best before {when_text(expires, now)}.",
           "Or earlier if the files change." if watched
           else "Nothing here watches the files, so this goes by the clock alone.",
           ""]
    out += goal + [f"Lot     {lot}", f"Issued  {issued_text(now // 60 * 60)}", ""]
    out += blocks + ["", f"Valid for lot {lot} only.", "normal is dead"]
    return "\n".join(out) + "\n", 0


# run

def kill_group(proc):
    try:
        os.killpg(proc.pid, signal.SIGKILL)
    except ProcessLookupError:
        pass


def execute(check, base):
    start = time.monotonic()
    proc = subprocess.Popen(check["run"], shell=True, cwd=base, stdin=subprocess.DEVNULL,
                            stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                            start_new_session=True)  # its own process group
    timed_out = False
    try:
        out, _ = proc.communicate(timeout=check["timeout"])
    except subprocess.TimeoutExpired:
        timed_out = True
        kill_group(proc)
        out, _ = proc.communicate()
    except KeyboardInterrupt:
        kill_group(proc)
        proc.wait()
        raise
    ms = int((time.monotonic() - start) * 1000)
    return (None if timed_out else proc.returncode), timed_out, out, ms


def run_checks(task, names, watcher):
    known = {c["name"] for c in task["checks"]}
    for n in names:
        if n not in known:
            raise Fail(f'no check named "{n}" in the task file')
    chosen = [c for c in task["checks"] if not names or c["name"] in names]
    width = max(len(c["name"]) for c in chosen)
    print(f"Running {plural(len(chosen), 'check')}.", flush=True)
    for c in chosen:
        before = watcher.hash(c)
        code, timed_out, out, ms = execute(c, task["base"])
        after = watcher.hash(c)
        at = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
        append_ledger(task, {"check": c["name"], "command": c["run"], "at": at, "exit": code,
                             "timeout": timed_out, "watch": before,
                             "self_edit": before is not None and after != before, "ms": ms})
        head = c["name"].ljust(width) + "  "
        if code == 0:
            print(f"{head}passed  {ms / 1000:.1f} s", flush=True)
            continue
        how = (f"timed out after {duration_text(c['timeout'])}" if timed_out
               else f"exit {code}, {ms / 1000:.1f} s")
        print(f"{head}{bold('FAILED')}  {how}", flush=True)
        tail = out.split(b"\n")
        if tail and tail[-1] == b"":
            tail.pop()
        sys.stdout.buffer.write(b"".join(b"    " + line + b"\n" for line in tail[-TAIL:]))
        sys.stdout.buffer.flush()
    print()


# main

class Parser(argparse.ArgumentParser):
    def error(self, message):
        raise Fail(message)


def parse_at(text):
    try:
        d = datetime.datetime.fromisoformat(text)
    except ValueError:
        raise Fail(f'--at "{text}" is not an ISO 8601 time')
    return int(d.astimezone().timestamp() // 1)


def main(argv):
    p = Parser(prog="best_before.py", add_help=False)
    p.add_argument("-h", "--help", action="store_true")
    p.add_argument("-f", dest="file", default=TASK_FILE)
    p.add_argument("--at")
    p.add_argument("command", nargs="?", default="status")
    p.add_argument("names", nargs="*")
    a = p.parse_args(argv)
    if a.help:
        sys.stdout.write(HELP)
        return 0
    if a.command not in ("status", "run", "lot"):
        raise Fail(f'unknown command "{a.command}" (status, run, lot)')
    if a.names and a.command != "run":
        raise Fail(f"{a.command} takes no check names")
    if a.at is not None and a.command != "status":
        raise Fail("--at is for status only")
    now = parse_at(a.at) if a.at is not None else int(time.time())
    task = load_task(a.file)
    watcher = Watcher(task)
    if a.command == "lot":
        print(lot_of((c["name"], watcher.hash(c)) for c in task["checks"]))
        return 0
    if a.command == "run":
        run_checks(task, a.names, watcher)
        now = int(time.time())
    text, code = report(task, now, watcher)
    sys.stdout.write(text)
    return code


if __name__ == "__main__":
    try:
        sys.exit(main(sys.argv[1:]))
    except Fail as e:
        sys.stderr.write(f"best-before: {e}\n")
        sys.exit(2)
    except KeyboardInterrupt:
        sys.exit(130)
