#!/usr/bin/env python3
"""Inspect a narrow archive-shaped input as DATA. Python 3.10+, no dependencies.
Accepts UTF-8 JSON arrays in literal window.YTD.tweets.partN assignments only.
Does not execute JavaScript, fetch URLs, modify inputs or prove export completeness.
Prints IDs and field summaries, never post text. Review the report before sharing.
"""
import argparse
from collections import Counter
import hashlib
import json
from pathlib import Path
import re
import sys

MAX_FILE = 10 * 1024 * 1024
MAX_TOTAL = 20 * 1024 * 1024
MAX_ROWS = 20000
WRAPPER = re.compile(r'\s*window\.YTD\.tweets\.part(0|[1-9][0-9]*)\s*=\s*(\[.*\])\s*;?\s*', re.DOTALL)


def unique_keys(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError('Repeated JSON key: inspect original input')
        result[key] = value
    return result


def reject_constant(value):
    raise ValueError('Non-JSON number constant')


def state(obj, key):
    if key not in obj:
        return 'missing'
    if obj[key] is None:
        return 'null'
    if obj[key] == 0 and not isinstance(obj[key], bool):
        return 'numeric_zero'
    if obj[key] == '0':
        return 'string_zero'
    return 'other_present'


def inspect(paths):
    if not paths or len(paths) > 100:
        raise ValueError('Supply 1 to 100 explicit file paths')
    total = 0
    parts = {}
    ids = []
    missing_ids = 0
    keys = Counter()
    fields = {key: Counter() for key in ['favorite_count', 'created_at', 'full_text']}
    count = 0
    for path in paths:
        # Read at most limit+1 bytes even if file changes after a size check.
        with path.open('rb') as stream:
            raw = stream.read(MAX_FILE + 1)
        total += len(raw)
        if len(raw) > MAX_FILE or total > MAX_TOTAL:
            raise ValueError('Teaching checker size limit: 10 MiB/file, 20 MiB total')
        match = WRAPPER.fullmatch(raw.decode('utf-8-sig'))
        if not match:
            raise ValueError('Unsupported wrapper or extra syntax; inspect as text')
        part = int(match.group(1))
        if part in parts:
            raise ValueError('Repeated part number; do not combine these inputs blindly')
        records = json.loads(match.group(2), object_pairs_hook=unique_keys,
                             parse_constant=reject_constant)
        count += len(records)
        if count > MAX_ROWS:
            raise ValueError('Teaching checker limit: 20000 total records')
        parts[part] = {'file': path.name, 'part': part, 'records': len(records),
                       'sha256': hashlib.sha256(raw).hexdigest()}
        for record in records:
            if not isinstance(record, dict) or not isinstance(record.get('tweet'), dict):
                raise ValueError('Expected array entries with nested tweet objects')
            tweet = record['tweet']
            if 'id_str' not in tweet:
                missing_ids += 1
            elif not isinstance(tweet['id_str'], str) or not re.fullmatch(r'[0-9]{1,20}', tweet['id_str']):
                raise ValueError('id_str must be an exact 1–20 digit string; no numeric coercion')
            else:
                ids.append(tweet['id_str'])
            keys.update(tweet.keys())
            for key in fields:
                fields[key][state(tweet, key)] += 1
    numbers = sorted(parts)
    if numbers != list(range(len(numbers))):
        raise ValueError('Supplied parts must start at 0 and contain no gaps')
    return {'scope': 'Only the supplied files; contiguous parts do not prove complete export',
            'files': [parts[n] for n in numbers], 'records': count,
            'id_occurrences': ids, 'distinct_ids': len(set(ids)),
            'repeated_id_occurrences': len(ids) - len(set(ids)),
            'records_without_id_str': missing_ids,
            'tweet_key_occurrences': dict(sorted(keys.items())),
            'field_states': {k: dict(sorted(v.items())) for k, v in fields.items()},
            'limits': 'No media, author, timestamp validity, coverage or current metric validation; original files preserved'}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('files', nargs='+', type=Path)
    args = parser.parse_args()
    try:
        report = inspect(args.files)
    except (OSError, ValueError, RecursionError) as exc:
        print('Stopped: ' + str(exc), file=sys.stderr)
        return 2
    print(json.dumps(report, indent=2, ensure_ascii=True))
    return 0


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