#!/usr/bin/env python3
"""Compare two compact two-column count files on a common index range."""
from __future__ import annotations

import argparse
from pathlib import Path


def load(path: Path) -> list[int]:
    values: list[int] = []
    for raw in path.read_text().splitlines():
        line = raw.strip()
        if not line or line.startswith('#'):
            continue
        k_s, value_s = line.split()
        k = int(k_s)
        if k != len(values):
            raise ValueError(f'unexpected index {k} in {path}')
        values.append(int(value_s))
    return values


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument('--candidate', type=Path, required=True)
    parser.add_argument('--reference', type=Path, required=True)
    parser.add_argument('--max-index', type=int)
    args = parser.parse_args()

    candidate = load(args.candidate)
    reference = load(args.reference)
    upper = min(len(candidate), len(reference)) - 1
    if args.max_index is not None:
        upper = min(upper, args.max_index)
    if upper < 0:
        raise ValueError('no common data rows')
    for k in range(upper + 1):
        if candidate[k] != reference[k]:
            raise AssertionError(
                f'mismatch at k={k}: candidate={candidate[k]}, reference={reference[k]}'
            )
    print(f'Counts agree for k=0,...,{upper} ({upper + 1} values).')


if __name__ == '__main__':
    main()
