#!/usr/bin/env python3
"""Compare two team-normalized CSV files locally; not a Wezy export parser.
Usage: python jsm-demand-reconcile.py observed.csv exported.csv
Required exact headers: request_key,votes. Blank votes remain unknown, not zero.
No network requests, file modifications, Jira writes or automatic deduplication.
"""
import argparse
import csv
import json
import re
import sys
from pathlib import Path


def read_normalized(path):
    result = {}
    with Path(path).open(encoding='utf-8-sig', newline='') as source:
        reader = csv.DictReader(source)
        if reader.fieldnames != ['request_key', 'votes']:
            raise ValueError('Expected exactly request_key,votes; explicitly map a COPY of your actual source first')
        for line, row in enumerate(reader, 2):
            if None in row or row.get('votes') is None:
                raise ValueError(f'Malformed CSV row {line}')
            key = row['request_key'].strip()
            if not re.fullmatch(r'[A-Z][A-Z0-9_]*-[0-9]+', key):
                raise ValueError(f'Invalid or unnormalized request key at row {line}')
            if key in result:
                raise ValueError(f'Duplicate request key at row {line}; resolve the record grain, do not sum silently')
            value = row['votes'].strip()
            if value and not re.fullmatch(r'[0-9]+', value):
                raise ValueError(f'Votes must be a non-negative integer or blank at row {line}')
            result[key] = int(value) if value else None
    return result


def compare(left, right):
    shared = sorted(left.keys() & right.keys())
    return {
        'left_rows': len(left), 'right_rows': len(right),
        'only_left': sorted(left.keys() - right.keys()),
        'only_right': sorted(right.keys() - left.keys()),
        'different_votes': [{'request_key': key, 'left': left[key], 'right': right[key]} for key in shared if left[key] != right[key]],
        'unknown_on_either_side': [key for key in shared if left[key] is None or right[key] is None],
        'limits': 'Compares supplied normalized copies only. Does not prove export scope, permissions, timing, source completeness, native schema or Jira indexing.'
    }


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('left', type=Path)
    parser.add_argument('right', type=Path)
    args = parser.parse_args()
    try:
        report = compare(read_normalized(args.left), read_normalized(args.right))
    except (OSError, UnicodeError, csv.Error, ValueError) as exc:
        print(f'Cannot compare: {exc}', file=sys.stderr)
        return 2
    print(json.dumps(report, indent=2))
    return 0

if __name__ == '__main__':
    raise SystemExit(main())
