#!/usr/bin/env python3
"""Compare the main view listing of D7 (:8080) and D10 (:8081) pages.

For each path and language prints: number of rows in the main .view-content
and the first 3 node link titles. Usage: compare_views.py path1 path2 ...
"""
import re
import sys
import urllib.parse
import urllib.request
import html


def main_view(url):
    try:
        body = urllib.request.urlopen(url, timeout=60).read().decode('utf-8', 'replace')
    except Exception as e:  # noqa
        return None, str(e)
    # Main page view: the first view whose wrapper has "view-display-id-page".
    m = re.search(r'<div[^>]+class="[^"]*view-display-id-page[^"]*"(.*?)(<nav|<h2[^>]*pager|class="item-list|class="pager|$)', body, re.S)
    chunk = m.group(1) if m else body
    rows = len(re.findall(r'class="[^"]*views-row[^"]*"|<tr[ >]', chunk))
    titles = [html.unescape(re.sub('<[^>]+>', '', t)).strip()[:28] for t in re.findall(r'<a [^>]*href="[^"]+"[^>]*>(.*?)</a>', chunk, re.S)]
    titles = [t for t in titles if t][:3]
    return rows, ' | '.join(titles)


for path in sys.argv[1:]:
    for lang in ('', 'my/'):
        a = main_view(f'http://localhost:8080/{lang}{path}')
        b = main_view(f'http://localhost:8081/{lang}{path}')
        flag = '' if a[0] == b[0] else '  <<< rows'
        print(f'/{lang}{path}{flag}\n   D7 : {a[0]} {a[1]}\n   D10: {b[0]} {b[1]}')
