#!/usr/bin/env python3
"""Compare the main (superfish) menu tree of D7 vs D10 for / and /my."""
import re, sys, urllib.request, urllib.parse
from html.parser import HTMLParser

class P(HTMLParser):
    def __init__(s):
        super().__init__(); s.inmenu=0; s.depth=0; s.items=[]; s.cur=None
    def handle_starttag(s, t, a):
        a=dict(a)
        if t=='ul' and a.get('id')=='superfish-1': s.inmenu=1; s.depth=0
        if not s.inmenu: return
        if t=='ul': s.depth+=1
        if t=='a': s.cur=[s.depth, a.get('href',''), '']
    def handle_endtag(s, t):
        if not s.inmenu: return
        if t=='a' and s.cur: s.items.append(s.cur); s.cur=None
        if t=='ul':
            s.depth-=1
            if s.depth==0: s.inmenu=0
    def handle_data(s, d):
        if s.cur is not None: s.cur[2]+=d

def tree(url):
    h=urllib.request.urlopen(url).read().decode('utf8')
    p=P(); p.feed(h)
    out=[]
    for d,href,txt in p.items:
        txt=re.sub(r'\s+',' ',txt.replace('»','')).strip()
        href=urllib.parse.unquote(re.sub(r'^https?://[^/]+','',href))[:40]
        out.append('  '*(d-1)+txt+'  ['+href+']')
    return out

import difflib
for path in ['/', '/my']:
    a=tree('http://localhost:8080'+path); b=tree('http://localhost:8081'+path)
    print(f'===== {path}: D7 {len(a)} items, D10 {len(b)} items')
    for l in difflib.unified_diff(a,b,'d7','d10',lineterm='',n=0): print(l)
