"""Reproduce navigation cohorts from exact frozen public evidence, not new observations.

Standard library only. No network access or file writes. Output counts describe
selected records, not populations, audience sizes, transactions or independent studies.
"""
import argparse
import hashlib
import json
from pathlib import Path
import re

SOURCES = {
    'minnesota': '668b4bfbe392047a59621c573dda9bb75f1b5025a003fd5c94986840fad49e88',
    'earnings': 'd4d7771bf47ac2166a6ae6998e9b0c4a636080e026fb2da0409acc5973a3dd73',
}
TOPICS = ['Food', 'Education', 'Travel']
PLATFORMS = ['Instagram', 'YouTube', 'Facebook', 'TikTok']
EVIDENCE_GROUPS = [
    ('annual-income', 'What do creator-income surveys report?', ['creator_survey']),
    ('listed-prices', 'What prices do creators list?', ['marketplace_listed_rate']),
    ('reported-payments', 'What do reported payments show?', ['marketplace_actual_payout', 'negotiated_payment']),
    ('platform-rules', 'How do platform rules and definitions work?', ['official_platform_formula', 'official_platform_program']),
]

def load(kind, path):
    raw = Path(path).read_bytes()
    if hashlib.sha256(raw).hexdigest() != SOURCES[kind]:
        raise ValueError('Input is not the documented frozen edition; no silent substitution.')
    rows = json.loads(raw)['records']
    if len(rows) != (47 if kind == 'minnesota' else 32):
        raise ValueError('Unexpected source cohort.')
    return rows

def cohorts(kind, rows):
    if kind == 'minnesota':
        result = []
        for topic in TOPICS:
            group = [r for r in rows if topic.lower() in re.split(r'[^a-z]+', r['category'].lower())]
            for platform in PLATFORMS:
                members = sorted((r for r in group if platform in r['primary_platforms']), key=lambda r: r['display_name'].casefold())
                result.append(dict(cohort=topic.lower()+'-'+platform.lower(), topic=topic, platform=platform,
                                   topic_records=len(group), matched_records=len(members), selected_records=47,
                                   record_ids=[r['entity_id'] for r in members]))
        return result
    return [dict(cohort=key, question=question, evidence_classes=classes,
                 matched_records=len([r for r in rows if r['evidence_class'] in classes]), selected_records=32,
                 record_ids=[r['record_id'] for r in rows if r['evidence_class'] in classes])
            for key, question, classes in EVIDENCE_GROUPS]

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('kind', choices=sorted(SOURCES))
    parser.add_argument('source', type=Path)
    args = parser.parse_args()
    print(json.dumps(dict(view_version='1.0.0', source_sha256=SOURCES[args.kind],
                         unit='Selected source records; not a representative population',
                         cohorts=cohorts(args.kind, load(args.kind, args.source))), ensure_ascii=False, indent=2))
