#!/usr/bin/env python3
"""numcheck.py - check that every number in a draft also appears in its source.

Usage:
    python numcheck.py DRAFT SOURCE [SOURCE ...]

Prints each number found in DRAFT that does not appear in any SOURCE file.
Exit code 0 = all numbers found in sources, 1 = some numbers unsupported, 2 = usage error.
Numbers are compared after removing thousands separators (1,200 == 1200).
Only Python 3 standard library is used. Files are read as UTF-8.

License: MIT
Copyright (c) 2026 Ye Xiaoguo AI Team
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software, to deal in the software without restriction, including the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell copies, subject to
including this notice. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
"""
import re
import sys

NUMBER = re.compile(r'(?<![A-Za-z0-9_.])[+-]?\d[\d,]*(?:\.\d+)?%?(?![A-Za-z0-9_])')


def numbers(text):
    found = []
    for m in NUMBER.finditer(text):
        n = m.group().replace(',', '').lstrip('+')
        if n not in found:
            found.append(n)
    return found


def read(path):
    with open(path, encoding='utf-8-sig') as f:
        return f.read()


def main(argv):
    if len(argv) < 3:
        print(__doc__.strip().split('\n\n')[1])
        return 2
    try:
        draft = read(argv[1])
        source = '\n'.join(read(p) for p in argv[2:])
    except OSError as exc:
        print('cannot read file:', exc)
        return 2
    have = set(numbers(source))
    missing = [n for n in numbers(draft) if n not in have]
    for n in missing:
        print('NOT IN SOURCE:', n)
    print('checked %d numbers, %d not in source' % (len(numbers(draft)), len(missing)))
    return 1 if missing else 0


if __name__ == '__main__':
    sys.exit(main(sys.argv))
