# -*- coding: utf-8 -*-
import os, re, sys, requests, io
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36",
      "Accept": "text/html,application/xhtml+xml", "Accept-Language": "en-US,en;q=0.9"}
OUT = "_r375_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)[:80]
    return s.strip('-')

def text(html):
    h = re.sub(r'(?is)<script.*?</script>', ' ', html)
    h = re.sub(r'(?is)<style.*?</style>', ' ', h)
    h = re.sub(r'(?is)<!--.*?-->', ' ', h)
    h = re.sub(r'(?s)<[^>]+>', '\n', h)
    h = re.sub(r'&nbsp;', ' ', h)
    h = re.sub(r'\n{2,}', '\n', h)
    return h.strip()

urls = sys.argv[1:]
for u in urls:
    try:
        r = requests.get(u, headers=UA, timeout=35)
        t = text(r.text)
        fn = os.path.join(OUT, slug(u) + ".txt")
        io.open(fn, "w", encoding="utf-8").write(t)
        print(r.status_code, len(r.text), len(t), u)
    except Exception as e:
        print("ERR", type(e).__name__, u)
