"""
Снимок сайта на Tilda для импорта: страницы из sitemap.xml и карт сайта лент (sitemap-feeds.xml),
закрытые в robots.txt и все найденные внутренние ссылки, а также посты лент Tilda (Feeds) через их API.
Результат: storage/app/tilda-mirror/pages/*.html, crawl.json (статусы/редиректы), sitemap*.xml, robots.txt,
custom.css, feeds/<feeduid>.json (лента и полные тексты постов).

    pip install requests
    python tools/crawl.py            # докачать недостающее
    python tools/crawl.py --fresh    # полный свежий снимок

Сайт за DDoS-Guard: между запросами пауза 0.6 с; при ответах 403/429 скрипт ждёт и повторяет,
уже скачанные страницы повторно не запрашиваются.
"""
import requests, time, json, re, os, sys, html as htmllib
from urllib.parse import urljoin, urlparse

BASE = os.environ.get('TILDA_SITE', 'https://restoplace.cc')
HOSTS = {urlparse(BASE).netloc, 'www.' + urlparse(BASE).netloc}
FEEDS_API = 'https://feeds.tildaapi.com/api'
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'storage', 'app', 'tilda-mirror')
OUT = os.path.join(ROOT, 'pages')
FEEDS_OUT = os.path.join(ROOT, 'feeds')
UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0 Safari/537.36'
FRESH = '--fresh' in sys.argv
os.makedirs(OUT, exist_ok=True)
os.makedirs(FEEDS_OUT, exist_ok=True)
s = requests.Session()
s.headers.update({'User-Agent': UA, 'Accept-Language': 'ru-RU,ru;q=0.9'})


def get(url, **kw):
    """GET с повтором при ответах DDoS-Guard (403/429/5xx) и сетевых ошибках."""
    kw.setdefault('timeout', 60)
    for attempt in range(6):
        try:
            r = s.get(url, **kw)
        except requests.RequestException as e:
            if attempt == 5:
                raise
            print('  ! сеть:', e, '— повтор', flush=True)
            time.sleep(5 * (attempt + 1)); continue
        if r.status_code in (403, 429, 500, 502, 503, 504) and attempt < 5:
            print('  !', r.status_code, url, '— жду и повторяю', flush=True)
            time.sleep(10 * (attempt + 1)); continue
        return r


def norm(path):
    p = urlparse(path)
    path = p.path or '/'
    if path != '/' and path.endswith('/'):
        path = path.rstrip('/')
    return path


def fname(path):
    if path == '/': return 'index.html'
    return path.strip('/').replace('/', '__') + ('' if path.endswith('.html') else '.html')


def save(name, content):
    with open(os.path.join(ROOT, name), 'wb') as f:
        f.write(content)


queue = []
seen = set()
def add(path, src):
    path = norm(path)
    if path in seen: return
    seen.add(path); queue.append((path, src))


def locs(xml):
    return [re.sub(r'^https?://[^/]+', '', u.strip()) for u in re.findall(r'<loc>([^<]+)</loc>', xml)]


# Служебные файлы сайта рядом с зеркалом: карты сайта (в том числе лент), robots.txt, custom.css
sitemap = get(BASE + '/sitemap.xml')
save('sitemap.xml', sitemap.content)
for u in locs(sitemap.text):
    add(u, 'sitemap')
feeds_index = get(BASE + '/sitemap-feeds.xml')
if feeds_index.status_code == 200:
    save('sitemap-feeds.xml', feeds_index.content)
    for u in locs(feeds_index.text):
        r = get(BASE + u)
        if r.status_code == 200:
            save(u.strip('/'), r.content)
            for post in locs(r.text):
                add(post, 'feed-sitemap')
robots = get(BASE + '/robots.txt', timeout=30)
save('robots.txt', robots.content)
for m in re.findall(r'Disallow:\s*(\S+)', robots.text):
    if m.startswith('/tilda/') or '*' in m: continue
    add(m, 'robots')
r = get(BASE + '/custom.css')
if r.status_code == 200:
    save('custom.css', r.content)

meta = {}
# --fresh: скачать все страницы заново (иначе уже скачанные пропускаются)
if os.path.exists(os.path.join(ROOT, 'crawl.json')) and not FRESH:
    meta = json.load(open(os.path.join(ROOT, 'crawl.json'), encoding='utf-8'))
assets_links = set()
feed_uids = set()
rss_links = set()
i = 0
while i < len(queue):
    path, src = queue[i]; i += 1
    fn = fname(path)
    rec = meta.get(path)
    if rec and rec.get('status') == 200 and os.path.exists(os.path.join(OUT, fn)):
        html = open(os.path.join(OUT, fn), encoding='utf-8', errors='replace', newline='').read()
    else:
        try:
            r = get(BASE + path, allow_redirects=False)
        except Exception as e:
            meta[path] = {'status': 'ERR', 'err': str(e), 'src': src}; continue
        rec = {'status': r.status_code, 'src': src, 'location': r.headers.get('Location'),
               'last_modified': r.headers.get('last-modified'), 'len': len(r.content)}
        if r.status_code in (301, 302, 307, 308):
            loc = urljoin(BASE + path, r.headers.get('Location', ''))
            lp = urlparse(loc)
            if lp.netloc in HOSTS:
                add(lp.path, 'redirect:' + path)
            meta[path] = rec
            print(r.status_code, path, '->', loc, flush=True)
            time.sleep(0.4); continue
        html = r.content.decode('utf-8', errors='replace')
        if r.status_code == 200:
            # Байт в байт, как отдала Tilda (без перевода строк Windows)
            open(os.path.join(OUT, fn), 'wb').write(r.content)
        rec['file'] = fn
        meta[path] = rec
        print(r.status_code, path, len(r.content), flush=True)
        time.sleep(0.6)
    if rec.get('status') != 200: continue
    feed_uids.update(re.findall(r"feeduid:\s*'(\d+)'", html))
    feed_uids.update(re.findall(r'data-feed-popup-feeduid="(\d+)"', html))
    rss_links.update(re.findall(r'href="https?://[^/"]+/(rss-feed-\d+\.xml)"', html))
    # Ссылки ищем регуляркой: страницы Tilda по 1–3 МБ, полноценный разбор HTML слишком медленный
    for h in re.findall(r'<a\b[^>]*?\shref\s*=\s*["\']([^"\']*)["\']', html, re.I):
        h = htmllib.unescape(h).strip()
        if not h or h.startswith(('#', 'tel:', 'mailto:', 'javascript:', 'whatsapp:', 'viber:', 'tg:', 'skype:')): continue
        full = urljoin(BASE + path, h)
        p = urlparse(full)
        if p.netloc not in HOSTS: continue
        if p.path.startswith('/tilda/'): continue
        if re.search(r'\.(pdf|jpe?g|png|gif|webp|svg|zip|rar|docx?|xlsx?|pptx?|mp4|txt|xml)$', p.path, re.I):
            assets_links.add(p.path); continue
        add(p.path, 'link:' + path)
    if i % 20 == 0:
        json.dump(meta, open(os.path.join(ROOT, 'crawl.json'), 'w', encoding='utf-8'), ensure_ascii=False, indent=1)

json.dump(meta, open(os.path.join(ROOT, 'crawl.json'), 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
json.dump(sorted(assets_links), open(os.path.join(ROOT, 'asset_links.json'), 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
print('DONE', len(meta), 'paths;', sum(1 for v in meta.values() if v.get('status') == 200), 'ok')

# Ленты Tilda (Feeds): список постов и их полные тексты. На Tilda их отдаёт API feeds.tildaapi.com,
# новый сайт отвечает на те же запросы сам (данные — в базе после импорта).
for uid in sorted(feed_uids):
    target = os.path.join(FEEDS_OUT, uid + '.json')
    if not os.path.exists(target) or FRESH:
        r = get(FEEDS_API + '/getfeed/', params={'feeduid': uid, 'size': 1000, 'slice': 1, 'sort[date]': 'desc',
                                                'filters[date]': '', 'getparts': 'true', 'c': int(time.time() * 1000)},
                headers={'Referer': BASE + '/'})
        feed = r.json()
        if 'posts' not in feed:
            print('  ! лента', uid, feed); continue
        full = []
        for post in feed['posts']:
            pr = get(FEEDS_API + '/getpost/', params={'postuid': post['uid'], 'c': int(time.time() * 1000)},
                     headers={'Referer': BASE + '/'})
            full.append({'list': post, 'post': pr.json().get('post', {})})
            time.sleep(0.2)
        feed['posts'] = full
        json.dump(feed, open(target, 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
        print('Лента', uid, feed.get('feedtitle'), '— постов:', len(full), flush=True)
    # Страницы постов, которых нет в карте сайта (Tilda не включает туда часть постов)
    for entry in json.load(open(target, encoding='utf-8'))['posts']:
        path = norm(urlparse(entry['list'].get('url', '')).path)
        if '/tpost/' not in path or meta.get(path, {}).get('status') == 200:
            continue
        r = get(BASE + path, allow_redirects=False)
        meta[path] = {'status': r.status_code, 'src': 'feed:' + uid, 'location': r.headers.get('Location'),
                      'last_modified': r.headers.get('last-modified'), 'len': len(r.content), 'file': fname(path)}
        if r.status_code == 200:
            open(os.path.join(OUT, fname(path)), 'wb').write(r.content)
        print(r.status_code, path, len(r.content), flush=True)
        time.sleep(0.6)

# AMP-версии постов лент (?amp=true): на них ссылается <link rel="amphtml"> в каждом посте
for path, rec in meta.items():
    if rec.get('status') != 200 or '/tpost/' not in path:
        continue
    amp = rec['file'][:-len('.html')] + '.amp.html'
    if not os.path.exists(os.path.join(OUT, amp)) or FRESH:
        r = get(BASE + path, params={'amp': 'true'}, allow_redirects=False)
        if r.status_code != 200:
            print('  ! AMP', path, r.status_code, flush=True); continue
        open(os.path.join(OUT, amp), 'wb').write(r.content)
        print('AMP', path, len(r.content), flush=True)
        time.sleep(0.4)
    rec['amp_file'] = amp
json.dump(meta, open(os.path.join(ROOT, 'crawl.json'), 'w', encoding='utf-8'), ensure_ascii=False, indent=1)

# Какую страницу Tilda показывает на несуществующих адресах (страница 404 в настройках проекта)
r = get(BASE + '/tilda-mirror-404-check-' + str(int(time.time())), allow_redirects=False)
m = re.search(r'<div id="allrecords"[^>]*data-tilda-page-id="(\d+)"', r.content.decode('utf-8', errors='replace'))
json.dump({'not_found_status': r.status_code, 'not_found_tilda_page_id': int(m.group(1)) if m else None},
          open(os.path.join(ROOT, 'site.json'), 'w', encoding='utf-8'), ensure_ascii=False, indent=1)

# RSS лент, на которые ссылаются страницы постов
for name in sorted(rss_links):
    r = get(BASE + '/' + name)
    if r.status_code == 200:
        save(name, r.content)

print('Готово:', ROOT)
