# -*- coding: utf-8 -*-
"""Fetch raw HTML with Chrome UA, cache to _r379_raw/, print key matches."""
import io, os, re, sys, hashlib, urllib.request, gzip, zlib

UA = ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
      '(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36')
DIR = '_r379_raw'


def slug(u):
    s = re.sub(r'^https?://', '', u)
    s = re.sub(r'[^A-Za-z0-9]+', '-', s).strip('-')
    return s[:110]


def fetch(u):
    req = urllib.request.Request(u, headers={
        'User-Agent': UA,
        'Accept': 'text/html,application/xhtml+xml',
        'Accept-Language': 'en-US,en;q=0.9',
        'Accept-Encoding': 'gzip',
    })
    r = urllib.request.urlopen(req, timeout=25)
    data = r.read()
    if r.headers.get('Content-Encoding') == 'gzip':
        data = gzip.decompress(data)
    return r.status, data.decode('utf-8', 'ignore')


def main():
    os.makedirs(DIR, exist_ok=True)
    pat = None
    args = sys.argv[1:]
    if args and args[0].startswith('--pat='):
        pat = args[0][6:]
        args = args[1:]
    rx = re.compile(pat, re.I) if pat else None
    for u in args:
        try:
            st, html = fetch(u)
        except Exception as e:
            print('ERR', type(e).__name__, u)
            continue
        p = os.path.join(DIR, slug(u) + '.html')
        io.open(p, 'w', encoding='utf-8').write(html)
        print(st, len(html), u, '->', p)
        if rx:
            for m in rx.finditer(html):
                s = max(0, m.start() - 100)
                print('   ', html[s:m.end() + 120].replace('\n', ' ')[:260])


main()
