#!/usr/bin/env python3
"""Compare two candump -L captures by CAN ID and payload sets.

Usage:
    python3 diffids.py idle1.log idle2.log

Reports:
  - IDs seen only in the first log, only in the second, or in both;
  - for shared IDs, whether their payload sets are identical, and
    which payloads are new in the second log.

Comparing two captures taken under identical conditions (e.g. two idle
captures) tells you which IDs are inherently noisy: those IDs are poor
candidates for stimulus analysis and should be discounted when you
later diff an idle capture against a stimulus capture.
"""

import re
import sys

LINE_RE = re.compile(
    r"^\((\d+(?:\.\d+)?)\)\s+(\S+)\s+([0-9A-Fa-f]+)#(\S*)\s*$"
)


def parse(path):
    """Return {can_id: set of payload strings}."""
    by_id = {}
    with open(path, "r", errors="replace") as fh:
        for line in fh:
            m = LINE_RE.match(line.strip())
            if not m:
                continue
            _ts, _iface, cid, data = m.groups()
            by_id.setdefault(cid.upper(), set()).add(data.upper())
    return by_id


def main():
    if len(sys.argv) != 3:
        sys.exit("usage: python3 diffids.py <log_a> <log_b>")

    a = parse(sys.argv[1])
    b = parse(sys.argv[2])

    ids_a, ids_b = set(a), set(b)
    only_a = sorted(ids_a - ids_b, key=lambda x: int(x, 16))
    only_b = sorted(ids_b - ids_a, key=lambda x: int(x, 16))
    shared = sorted(ids_a & ids_b, key=lambda x: int(x, 16))

    print("A = {}   B = {}".format(sys.argv[1], sys.argv[2]))
    print()
    print("IDs only in A ({}): {}".format(len(only_a), " ".join(only_a) or "-"))
    print("IDs only in B ({}): {}".format(len(only_b), " ".join(only_b) or "-"))
    print("IDs in both     ({}): {}".format(len(shared), " ".join(shared)))
    print()

    noisy = []
    for cid in shared:
        new = b[cid] - a[cid]
        if new:
            noisy.append(cid)
            shown = ", ".join(sorted(new)[:5])
            more = " ..." if len(new) > 5 else ""
            print(
                "{}  payload sets differ: {} new payload(s) in B: {}{}".format(
                    cid, len(new), shown, more
                )
            )
    if not noisy:
        print("All shared IDs have identical payload sets in both logs.")
    else:
        print()
        print(
            "IDs above behave differently across the two captures "
            "(noise candidates): {}".format(" ".join(noisy))
        )


if __name__ == "__main__":
    main()
