#!/usr/bin/env python3
# IndexNow pour nos sites (24/11/2026). Usage : python3 indexnow_all.py [--envoyer] domaine=docroot ...
# - garde la clé existante (fichier <clé>.txt dont le contenu = clé) ; sinon en crée une ;
# - vérifie que https://<host>/<clé>.txt répond avec la clé (sinon essaie docroot/public) ;
# - lit le sitemap (robots.txt puis /sitemap.xml, index de sitemaps gérés) ;
# - avec --envoyer : soumet toutes les URL du host à api.indexnow.org (lots de 10 000).
import os, re, sys, json, secrets, ssl, urllib.request, urllib.error
UA = {'User-Agent': 'Mozilla/5.0 (compatible; indexnow-client/1.0)'}
CTX = ssl.create_default_context()
SEND = '--envoyer' in sys.argv

def get(u, n=20_000_000):
    try:
        r = urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=40, context=CTX)
        return r.status, r.geturl(), r.read(n).decode('utf-8', 'ignore')
    except urllib.error.HTTPError as e:
        return e.code, u, ''
    except Exception as e:
        return 0, u, ''

def find_key(root):
    for f in os.listdir(root):
        m = re.fullmatch(r'([0-9a-zA-Z-]{8,128})\.txt', f)
        if m:
            try:
                if open(os.path.join(root, f)).read().strip() == m.group(1):
                    return m.group(1)
            except Exception:
                pass
    return None

def ensure_key(host, root):
    roots = [root] + ([os.path.join(root, 'public')] if os.path.isdir(os.path.join(root, 'public')) else [])
    for r in roots:
        k = find_key(r)
        if k and get(f'https://{host}/{k}.txt')[2].strip() == k:
            return k, r, 'existante'
    k = next((find_key(r) for r in roots if find_key(r)), None) or secrets.token_hex(16)
    for r in roots:
        p = os.path.join(r, k + '.txt')
        created = not os.path.exists(p)
        if created:
            open(p, 'w').write(k)
            try:
                st = os.stat(r); os.chown(p, st.st_uid, st.st_gid)
            except Exception:
                pass
            os.chmod(p, 0o644)
        if get(f'https://{host}/{k}.txt')[2].strip() == k:
            return k, r, 'créée' if created else 'existante'
        if created:
            os.remove(p)
    return None, None, 'clé injoignable en ligne'

def sitemap_urls(host):
    base = f'https://{host}'
    _, _, rob = get(base + '/robots.txt')
    todo = re.findall(r'(?im)^\s*sitemap:\s*(\S+)', rob) or [base + '/sitemap.xml']
    seen, urls = set(), []
    while todo and len(seen) < 200:
        s = todo.pop(0)
        if s in seen: continue
        seen.add(s)
        _, _, x = get(s)
        locs = [l.strip().replace('&amp;', '&') for l in re.findall(r'<loc>\s*([^<]+?)\s*</loc>', x)]
        if '<sitemapindex' in x: todo += locs
        else: urls += locs
    return list(dict.fromkeys(u for u in urls if re.match(rf'https?://{re.escape(host)}/', u) or re.match(rf'https?://{re.escape(host)}$', u)))

res = []
for arg in [a for a in sys.argv[1:] if '=' in a]:
    dom, root = arg.split('=', 1)
    st, fin, _ = get(f'https://{dom}/')
    host = re.sub(r'^https?://([^/]+).*', r'\1', fin)
    r = {'domaine': dom, 'host': host, 'http': st}
    if st != 200 or host.replace('www.', '') != dom.replace('www.', ''):
        r['etat'] = 'ignoré (redirige ou erreur)'; res.append(r); print(json.dumps(r, ensure_ascii=False)); continue
    k, kr, how = ensure_key(host, root)
    r.update(cle=how, dossier=kr)
    if not k:
        res.append(r); print(json.dumps(r, ensure_ascii=False)); continue
    urls = sitemap_urls(host)
    r['urls'] = len(urls)
    if SEND and urls:
        codes = []
        for i in range(0, len(urls), 10000):
            body = json.dumps({'host': host, 'key': k, 'keyLocation': f'https://{host}/{k}.txt', 'urlList': urls[i:i+10000]}).encode()
            req = urllib.request.Request('https://api.indexnow.org/indexnow', data=body,
                                         headers={'Content-Type': 'application/json; charset=utf-8'})
            try:
                codes.append(urllib.request.urlopen(req, timeout=60, context=CTX).status)
            except urllib.error.HTTPError as e:
                codes.append(e.code)
            except Exception:
                codes.append(0)
        r['indexnow'] = codes
    res.append(r); print(json.dumps(r, ensure_ascii=False))
