#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Poste une reponse a un commentaire — avec garde-fou d'identite.
Usage:
  post_reply.py <cid|reply_link> "<texte>"            -> ESSAI A BLANC (rien publie)
  post_reply.py <cid|reply_link> "<texte>" --go       -> publie SI identite = page
  post_reply.py <cid|reply_link> "<texte>" --go --as-perso  -> autorise la publication sous le profil perso
Securite : par defaut --dry ; en --go, refuse de publier si l'identite n'est pas la page,
sauf --as-perso explicite.
"""
import sys, time, json
from fb_common import session_facebook, DATA, COOKIES_PAGE
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

PAGE_NAME = "Collectif de Citoyens Ucclois"

def resolve(arg):
    if arg.startswith("http"):
        return arg, None
    snap = json.load(open(DATA + "/snapshot.json"))
    for p in snap["posts"]:
        for c in p["comments"]:
            if c["id"] == arg:
                return (c.get("reply_link") or p["url"] + "?comment_id=" + arg), arg
    raise SystemExit("cid introuvable: " + arg)

def main():
    if len(sys.argv) < 3:
        raise SystemExit(__doc__)
    link, cid = resolve(sys.argv[1])
    texte = sys.argv[2]
    go = "--go" in sys.argv[3:]
    as_perso = "--as-perso" in sys.argv[3:]
    print("LIEN:", link)
    print("TEXTE:", texte)
    print("MODE:", "PUBLICATION REELLE" if go else "ESSAI A BLANC (rien publie)")
    import os
    if os.path.exists(COOKIES_PAGE):
        print("COOKIE: mode page (%s)" % COOKIES_PAGE)
        d = session_facebook(COOKIES_PAGE)
    else:
        print("COOKIE: profil perso (cookie page absent)")
        d = session_facebook()
    d.get(link); time.sleep(6)

    # cibler l'article du commentaire par cid
    target = None
    if cid:
        for a in d.find_elements(By.CSS_SELECTOR, '[aria-label^="Commentaire de"]'):
            hrefs = " ".join((x.get_attribute("href") or "") for x in a.find_elements(By.CSS_SELECTOR, "a"))
            if ("comment_id=" + cid) in hrefs:
                target = a; break
    print("commentaire cible localise:", bool(target))
    scope = target if target else d
    # cliquer le "Répondre" du commentaire cible
    rb = scope.find_elements(By.XPATH, ".//div[@role='button'][.//text()[contains(.,'Répondre')]] | .//span[text()='Répondre']") if target \
        else d.find_elements(By.XPATH, "//span[text()='Répondre']")
    if rb:
        d.execute_script("arguments[0].scrollIntoView({block:'center'});", rb[0])
        d.execute_script("arguments[0].click();", rb[0]); time.sleep(2.5)

    # selectionner la zone "Répondre en tant que ..." (pas la zone globale "Commenter")
    box = None
    for b in d.find_elements(By.CSS_SELECTOR, 'div[contenteditable="true"][role="textbox"]'):
        al = (b.get_attribute("aria-label") or "")
        if al.startswith("Répondre"):
            box = b; break
    if not box:
        print("ECHEC: zone de réponse introuvable"); d.quit(); return
    aria = box.get_attribute("aria-label") or ""
    print("zone de réponse:", aria[:90])

    # identifier l'identite courante
    identity = ""
    if "en tant que" in aria:
        identity = aria.split("en tant que", 1)[1].strip()
    print("IDENTITE COURANTE:", identity or "(inconnue)")
    is_page = (identity == PAGE_NAME)

    if go and not is_page and not as_perso:
        print("⛔ PUBLICATION REFUSEE : l'identite n'est pas la page (%s)." % (identity or "?"))
        print("   -> Pour publier en tant que la page, ouvrez une session Facebook")
        print("      'en tant que %s', re-exportez les cookies, puis relancez." % PAGE_NAME)
        print("   -> Ou ajoutez --as-perso pour publier volontairement sous le profil perso.")
        d.quit(); return

    d.execute_script("arguments[0].scrollIntoView({block:'center'});", box)
    box.click(); time.sleep(1); box.send_keys(texte); time.sleep(1)
    print("texte saisi.")
    if not go:
        print(">>> ESSAI A BLANC : arrêt ici, RIEN n'est publié.")
        d.quit(); return
    box.send_keys(Keys.ENTER); time.sleep(4)
    print(">>> PUBLIÉ en tant que:", identity)
    d.quit()

if __name__ == "__main__":
    main()

