"""Explain the dependency path and slack that govern CI duration."""
from collections import defaultdict
from heapq import heapify, heappop, heappush


def analyze(jobs):
    """Jobs map names to (duration in seconds, prerequisite job names)."""
    if not jobs:
        return {"seconds": 0, "critical_path": [], "slack": {}}
    followers = defaultdict(list)
    pending = {}
    for name, (duration, dependencies) in jobs.items():
        if duration <= 0 or len(set(dependencies)) != len(dependencies):
            raise ValueError(f"Invalid duration or duplicate dependency for {name}")
        pending[name] = len(dependencies)
        for dep in dependencies:
            if dep not in jobs:
                raise ValueError(f"Missing prerequisite {dep} for {name}")
            followers[dep].append(name)

    ready = [name for name, count in pending.items() if count == 0]
    heapify(ready)
    order, finish, parent = [], {}, {}
    while ready:
        name = heappop(ready)
        order.append(name)
        duration, dependencies = jobs[name]
        predecessor = max(dependencies, key=lambda dep: (finish[dep], dep), default=None)
        parent[name] = predecessor
        finish[name] = duration + finish.get(predecessor, 0)
        for child in followers[name]:
            pending[child] -= 1
            if pending[child] == 0:
                heappush(ready, child)
    if len(order) != len(jobs):
        raise ValueError("The pipeline has a dependency cycle")

    end = max(order, key=lambda name: (finish[name], name))
    total = finish[end]
    latest_finish, slack = {}, {}
    for name in reversed(order):
        latest_finish[name] = min((latest_finish[child] - jobs[child][0]
                                   for child in followers[name]), default=total)
        slack[name] = latest_finish[name] - finish[name]
    path = []
    while end is not None:
        path.append(end)
        end = parent[end]
    return {"seconds": total, "critical_path": path[::-1], "slack": dict(sorted(slack.items()))}


if __name__ == "__main__":
    print(analyze({"compile": (45, []), "cook-assets": (85, []),
                   "unit-tests": (25, ["compile"]), "package": (20, ["compile", "cook-assets"]),
                   "smoke": (30, ["unit-tests", "package"])}))

