#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Utilitaires communs : cookies + driver Selenium headless (projet suivi commentaires)."""
import os, json, time

ICI   = os.path.dirname(os.path.abspath(__file__))
DATA  = "/home/collectifweil/suivi_data"
COOKIES_JSON = os.path.join(DATA, "cookies_fb.json")
COOKIES_PAGE = os.path.join(DATA, "cookies_fb_page.json")

CHROME_BIN = "/usr/bin/google-chrome"
CHROMEDRIVER = "/usr/local/bin/chromedriver"
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
      "(KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36")


def charger_cookies_fb(path=COOKIES_JSON):
    """Retourne une liste de cookies au format Selenium pour .facebook.com."""
    txt = open(path, encoding="utf-8", errors="replace").read().strip()
    arr = json.loads(txt)
    if isinstance(arr, dict):
        arr = arr.get("cookies", [])
    out = []
    for c in arr:
        dom = c.get("domain", "") or ""
        if "facebook" not in dom:
            continue
        ck = {
            "name":  c.get("name"),
            "value": c.get("value", ""),
            "domain": dom if dom.startswith(".") else "." + dom.lstrip("."),
            "path":  c.get("path", "/") or "/",
        }
        out.append(ck)
    return out


def driver():
    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    from selenium.webdriver.chrome.service import Service
    o = Options()
    for a in ["--headless=new", "--no-sandbox", "--disable-dev-shm-usage",
              "--disable-gpu", "--window-size=1366,3000", "--lang=fr-FR",
              "--user-agent=" + UA]:
        o.add_argument(a)
    o.binary_location = CHROME_BIN
    d = webdriver.Chrome(service=Service(CHROMEDRIVER), options=o)
    d.set_page_load_timeout(60)
    return d


def session_facebook(cookies_path=COOKIES_JSON):
    """Ouvre un driver, injecte les cookies, renvoie le driver connecté."""
    d = driver()
    d.get("https://www.facebook.com/")
    time.sleep(2)
    for c in charger_cookies_fb(cookies_path):
        try:
            d.add_cookie(c)
        except Exception:
            pass
    return d

