import io, os, re, sys, requests
UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36'
OUT = '_r380_txt'
os.makedirs(OUT, exist_ok=True)

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

def html2txt(h):
    h = re.sub(r'<script[\s\S]*?</script>', ' ', h, flags=re.I)
    h = re.sub(r'<style[\s\S]*?</style>', ' ', h, flags=re.I)
    h = re.sub(r'<br\s*/?>', '\n', h, flags=re.I)
    h = re.sub(r'</(p|div|li|tr|h\d|td)>', '\n', h, flags=re.I)
    h = re.sub(r'<[^>]+>', ' ', h)
    import html as H
    h = H.unescape(h)
    h = re.sub(r'[ \t\xa0]+', ' ', h)
    h = re.sub(r'\n\s*\n+', '\n', h)
    return h.strip()

if __name__ == '__main__':
    args = sys.argv[1:]
    keep_raw = False
    if args and args[0] == '--raw':
        keep_raw = True
        args = args[1:]
    for u in args:
        try:
            r = requests.get(u, headers={'User-Agent': UA}, timeout=15)
            t = html2txt(r.text)
            base = slug(u)
            io.open(os.path.join(OUT, base + '.txt'), 'w', encoding='utf-8').write(t)
            if keep_raw:
                io.open(os.path.join(OUT, base + '.html'), 'w', encoding='utf-8').write(r.text)
            print(r.status_code, len(t), base)
        except Exception as e:
            print('ERR', type(e).__name__, u)
