"""Finite, offline site-table arithmetic exercise. No network or source authentication."""
import json
import sys

DIMENSIONS = ('data_date', 'site_url', 'query', 'is_anonymized_query', 'country', 'search_type', 'device')
METRICS = ('impressions', 'clicks', 'sum_top_position')

def aggregate(packet):
    if not isinstance(packet, dict) or packet.get('table') != 'searchdata_site_impression':
        raise ValueError('SITE_TABLE_REQUIRED')
    if not isinstance(packet.get('partitionReference'), str) or not packet['partitionReference'].strip():
        raise ValueError('PARTITION_REFERENCE_REQUIRED_NOT_AUTHENTICATED')
    grain = packet.get('grain')
    if not isinstance(grain, dict) or set(grain) != set(DIMENSIONS):
        raise ValueError('EXACT_DECLARED_DIMENSIONS_REQUIRED')
    if type(grain['is_anonymized_query']) is not bool:
        raise ValueError('INVALID_ANONYMIZED_FLAG')
    for key in DIMENSIONS:
        if key == 'is_anonymized_query':
            continue
        if key == 'query' and grain['is_anonymized_query'] and grain[key] in (None, ''):
            continue
        if not isinstance(grain[key], str) or not grain[key]:
            raise ValueError('INVALID_DIMENSION:' + key)
    if grain['is_anonymized_query'] and grain['query'] not in (None, ''):
        raise ValueError('ANONYMIZED_QUERY_TEXT_NOT_ALLOWED')
    rows = packet.get('rows')
    if not isinstance(rows, list) or not rows:
        raise ValueError('INPUT_ROWS_REQUIRED')
    totals = dict.fromkeys(METRICS, 0)
    for row in rows:
        if not isinstance(row, dict) or set(row) != set(DIMENSIONS + METRICS):
            raise ValueError('EXACT_SITE_ROW_FIELDS_REQUIRED')
        if any(type(row[k]) is not type(grain[k]) or row[k] != grain[k] for k in DIMENSIONS):
            raise ValueError('MIXED_GRAIN')
        for key in METRICS:
            if type(row[key]) is not int or row[key] < 0:
                raise ValueError('NONNEGATIVE_INTEGER_METRICS_REQUIRED')
        if row['impressions'] == 0 and (row['clicks'] != 0 or row['sum_top_position'] != 0):
            raise ValueError('ZERO_IMPRESSION_METRIC_CONFLICT')
        for key in METRICS:
            totals[key] += row[key]
    impressions = totals['impressions']
    return {'status': 'SUPPLIED_SITE_ROWS_AGGREGATED', 'inputRows': len(rows), 'grain': grain,
            'totals': totals, 'ctr': totals['clicks']/impressions if impressions else None,
            'averagePosition': totals['sum_top_position']/impressions+1 if impressions else None,
            'partitionAuthenticated': False, 'completeExportProven': False,
            'fixedKeywordRanking': False}

if __name__ == '__main__':
    try:
        with open(sys.argv[1], encoding='utf-8') as f:
            result = aggregate(json.load(f))
        print(json.dumps(result, ensure_ascii=False, indent=2, allow_nan=False))
    except (ValueError, OSError, IndexError) as e:
        print(json.dumps({'status': 'REJECTED', 'reason': str(e)}))
        sys.exit(1)
