#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Inspecte la zone de reponse + le selecteur d'identite (page vs profil)."""
import sys, time, json
from fb_common import session_facebook, DATA
from selenium.webdriver.common.by import By

cid = sys.argv[1]
snap = json.load(open(DATA + "/snapshot.json"))
link = None
for p in snap["posts"]:
    for c in p["comments"]:
        if c["id"] == cid:
            link = c.get("reply_link"); break
print("LIEN:", link)
d = session_facebook(); d.get(link); time.sleep(6)

# 1) trouver l'article du commentaire cible (celui dont un lien contient comment_id=<cid>)
target = None
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("article cible trouve:", bool(target))

# 2) dans cet article, bouton "Répondre"
if target:
    rb = target.find_elements(By.XPATH, ".//div[@role='button'][.//text()[contains(.,'Répondre')]] | .//span[text()='Répondre']")
    print("boutons Répondre dans l'article cible:", len(rb))
    if rb:
        d.execute_script("arguments[0].scrollIntoView({block:'center'});", rb[0])
        d.execute_script("arguments[0].click();", rb[0]); time.sleep(2.5)

# 3) inventaire des zones editables + leur aria (identite)
boxes = d.find_elements(By.CSS_SELECTOR, 'div[contenteditable="true"][role="textbox"]')
print("zones editables:", len(boxes))
for b in boxes:
    print("   aria:", (b.get_attribute("aria-label") or b.get_attribute("aria-placeholder") or "")[:90])

# 4) chercher un selecteur d'identite "en tant que" / nom de la page
print("=== controles 'en tant que' / identite ===")
for el in d.find_elements(By.XPATH, "//*[contains(@aria-label,'tant que') or contains(@aria-label,'Collectif de Citoyens')]")[:12]:
    tag = el.tag_name; al = el.get_attribute("aria-label"); role = el.get_attribute("role")
    print("   <%s role=%s> %s" % (tag, role, (al or "")[:80]))

# 5) avatars/boutons cliquables proches de la 1ere box (pour switch)
if boxes:
    js = """
    const box=arguments[0];
    let n=box; const out=[];
    for(let i=0;i<5 && n;i++){n=n.parentElement;}
    if(n){n.querySelectorAll('[role=button],[aria-label]').forEach(e=>{
      const al=e.getAttribute('aria-label')||''; if(al) out.push(e.tagName+':'+al.slice(0,60));});}
    return out.slice(0,20);
    """
    near = d.execute_script(js, boxes[-1])
    print("=== controles proches de la zone de reponse ===")
    for x in near: print("   ", x)
d.quit()

