"""Offline fixed-cohort comparison. No network, account access or rank retrieval."""
import json
import sys
from datetime import date

CONDITIONS = ('engine', 'location', 'device', 'interfaceLanguage', 'domain', 'resultType', 'cohortVersion')


def validate(snapshot):
    source_date = snapshot['sourceDate']
    if not isinstance(source_date, str) or date.fromisoformat(source_date).isoformat() != source_date:
        raise ValueError('sourceDate must use canonical YYYY-MM-DD format')
    for key in CONDITIONS:
        if not isinstance(snapshot['conditions'].get(key), str) or not snapshot['conditions'][key].strip():
            raise ValueError('Missing condition: ' + key)
    items = snapshot['rows']
    if not items:
        raise ValueError('Empty fixed cohort')
    index = {}
    for row in items:
        ident = row['id']
        if not isinstance(ident, str) or not ident.strip() or ident in index:
            raise ValueError('Invalid or duplicate keyword ID')
        if type(row['brand']) is not bool or not isinstance(row['keyword'], str) or not row['keyword'].strip():
            raise ValueError('Invalid fixed keyword identity')
        status = row['status']
        rank = row['position']
        if status == 'ranked':
            if type(rank) is not int or not 1 <= rank <= 100:
                raise ValueError('Rank must be integer 1 through 100')
        elif status in ('not_in_top100', 'unknown'):
            if rank is not None:
                raise ValueError('Unranked or unknown must not have an invented position')
        else:
            raise ValueError('Unknown observation status')
        url = row.get('url')
        if url is not None and (not isinstance(url, str) or not url.startswith(('https://', 'http://'))):
            raise ValueError('Invalid observed landing URL')
        index[ident] = row
    if len({r['keyword'] for r in items}) != len(items):
        raise ValueError('Duplicate keyword text')
    return index


def coverage(rows):
    unknown = sum(r['status'] == 'unknown' for r in rows)
    total = len(rows)
    thresholds = {}
    for n in (3, 5, 10, 100):
        observed = sum(r['status'] == 'ranked' and r['position'] <= n for r in rows)
        thresholds[str(n)] = {'count': observed if not unknown else None,
                              'observedAtLeast': observed,
                              'possibleAtMost': observed + unknown,
                              'rate': observed / total if total and not unknown else None}
    return {'denominator': total, 'unknown': unknown, 'topN': thresholds}


def compare(before, after):
    a, b = validate(before), validate(after)
    mismatches = [k for k in CONDITIONS if before['conditions'][k] != after['conditions'][k]]
    if mismatches:
        return {'status': 'INCOMPARABLE', 'reasons': mismatches}
    if before['sourceDate'] >= after['sourceDate']:
        return {'status': 'INCOMPARABLE', 'reasons': ['sourceDate must advance']}
    if set(a) != set(b):
        return {'status': 'INCOMPARABLE', 'reasons': ['fixed cohort changed'],
                'missingAfter': sorted(set(a) - set(b)), 'newAfter': sorted(set(b) - set(a))}
    for ident in a:
        if any(a[ident][k] != b[ident][k] for k in ('keyword', 'brand')):
            return {'status': 'INCOMPARABLE', 'reasons': ['keyword or brand identity changed: ' + ident]}
    result = {'status': 'COMPARABLE', 'beforeDate': before['sourceDate'], 'afterDate': after['sourceDate'],
              'coverage': {}, 'thresholdTransitions': {}, 'movements': [],
              'limits': ['Nested TopN counts must not be added.',
                         'Supplied observations are not authenticated by this program.',
                         'No ranking cause, penalty or Google-wide result is established.']}
    for group, selected in [('all', list(a)), ('brand', [k for k in a if a[k]['brand']]),
                            ('nonBrand', [k for k in a if not a[k]['brand']])]:
        result['coverage'][group] = {'before': coverage([a[k] for k in selected]),
                                     'after': coverage([b[k] for k in selected])}
    for n in (3, 5, 10, 100):
        enters, exits, unresolved = [], [], []
        for ident in a:
            x, y = a[ident], b[ident]
            if 'unknown' in (x['status'], y['status']):
                unresolved.append(ident)
                continue
            was = x['status'] == 'ranked' and x['position'] <= n
            now = y['status'] == 'ranked' and y['position'] <= n
            if now and not was:
                enters.append(ident)
            if was and not now:
                exits.append(ident)
        result['thresholdTransitions'][str(n)] = {'entries': sorted(enters), 'exits': sorted(exits),
                                                'unknownComparisons': sorted(unresolved)}
    for ident in a:
        x, y = a[ident], b[ident]
        both_ranked = x['status'] == y['status'] == 'ranked'
        result['movements'].append({'id': ident, 'keyword': x['keyword'], 'brand': x['brand'],
                                    'before': x['position'], 'after': y['position'],
                                    'beforeStatus': x['status'], 'afterStatus': y['status'],
                                    'positionsImproved': x['position'] - y['position'] if both_ranked else None,
                                    'beforeUrl': x.get('url'), 'afterUrl': y.get('url'),
                                    'urlChanged': x['url'] != y['url'] if both_ranked and x.get('url') and y.get('url') else None})
    return result


if __name__ == '__main__':
    if len(sys.argv) != 2:
        raise SystemExit('Usage: python3 compare.py input.json')
    with open(sys.argv[1], encoding='utf-8') as stream:
        data = json.load(stream)
    try:
        output = compare(data['before'], data['after'])
    except (ValueError, KeyError, TypeError) as exc:
        output = {'status': 'INVALID_INPUT', 'reason': str(exc)}
    print(json.dumps(output, ensure_ascii=False, indent=2))
