"""Recomputes the numbers quoted in the article from the public CSV files in this folder.
Run: python3 recount.py   (Python 3.9+, standard library only)"""
import csv, pathlib
from collections import Counter

D = pathlib.Path(__file__).resolve().parent
sites = list(csv.DictReader(open(D / 'sites.csv')))
dups = list(csv.DictReader(open(D / 'duplicates.csv')))
pages = list(csv.DictReader(open(D / 'pages.csv')))
sm = list(csv.DictReader(open(D / 'sitemap_sample.csv')))

SKIP = {'different_page', 'challenge', 'unreachable_on_recheck', 'now_redirects_to_main'}
by_site = {}
for d in dups:
    if d['verdict'] not in SKIP:
        by_site.setdefault(d['site_id'], []).append(d['verdict'])
print(f"homepages analysed: {len(sites)}")
print(f"sites where the same homepage answers on a second address: {len(by_site)}")
c = Counter()
for v in by_site.values():
    if all(x == 'canonical_to_main' for x in v):
        c['every copy has a canonical to the main version'] += 1
    elif 'canonical_to_itself' in v:
        c['a copy has a canonical to itself'] += 1
    elif 'no_canonical' in v:
        c['a copy has no canonical'] += 1
    else:
        c['other'] += 1
for k, n in c.most_common():
    print(f"  {k}: {n}")
print('copies differ from the main address by:', dict(Counter(d['differs_from_main_by'] for d in dups if d['verdict'] not in SKIP)))

withc = [p for p in pages if p['canonical_relation'] != 'none']
print(f"pages: {len(pages)}, with a canonical: {len(withc)}")
red = [p for p in withc if p['canonical_target_status'] in ('301', '302', '303', '307', '308')]
err = [p for p in withc if p['canonical_target_status'] and p['canonical_target_status'].isdigit() and int(p['canonical_target_status']) >= 400]
print(f"  canonical target redirects: {len(red)} (back to the same page: {sum(p['target_redirects_back_to_this_page'] == 'True' for p in red)})")
print('    by how the canonical differs from the page:', dict(Counter(p['canonical_relation'] for p in red)))
print(f"  canonical target answers 4xx/5xx: {len(err)}")
print(f"  sites with either problem: {len({p['site_id'] for p in red + err})}")
mix = [p for p in withc if p['canonical_relation'] in ('scheme_only', 'www_only', 'scheme_and_www')]
print(f"  canonical differs from the page only by http/https or www: {len(mix)}")
print(f"sitemaps sampled: {len(sm)}")
a = sum(1 for s in sm if int(s['redirecting']))
b = sum(1 for s in sm if int(s['canonical_points_elsewhere']))
u = sum(1 for s in sm if int(s['redirecting']) or int(s['canonical_points_elsewhere']))
print(f"  listing a redirecting URL: {a}, listing a URL canonicalised elsewhere: {b}, either: {u}")
