#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Diagnostic injection cookies via CDP."""
import json, time, re
from fb_common import COOKIES_JSON, driver

arr = json.load(open(COOKIES_JSON, encoding="utf-8"))
if isinstance(arr, dict):
    arr = arr.get("cookies", [])
fb = [c for c in arr if "facebook" in (c.get("domain","") or "")]
print("cookies facebook trouves:", len(fb))
from collections import Counter
print("domaines:", dict(Counter((c.get("domain") for c in fb))))
print("noms:", sorted(c.get("name") for c in fb))

d = driver()
d.get("https://www.facebook.com/")
time.sleep(2)

ok = 0
for c in fb:
    params = {
        "name": c.get("name"),
        "value": c.get("value",""),
        "domain": c.get("domain"),
        "path": c.get("path","/") or "/",
        "secure": bool(c.get("secure", True)),
        "httpOnly": bool(c.get("httpOnly", False)),
    }
    # sameSite mapping
    ss = (c.get("sameSite") or "").lower()
    if ss in ("no_restriction","none"): params["sameSite"]="None"
    elif ss == "lax": params["sameSite"]="Lax"
    elif ss == "strict": params["sameSite"]="Strict"
    exp = c.get("expirationDate") or c.get("expires")
    if exp:
        try: params["expires"] = float(exp)
        except: pass
    try:
        d.execute_cdp_cmd("Network.setCookie", params)
        ok += 1
    except Exception as e:
        print("FAIL", c.get("name"), str(e)[:80])
print("cookies injectes via CDP:", ok, "/", len(fb))

d.get("https://www.facebook.com/me")
time.sleep(5)
cks = {c["name"]: c["value"] for c in d.get_cookies()}
print("URL:", d.current_url)
print("c_user present apres CDP:", "OUI" if cks.get("c_user") else "NON")
html = d.page_source
print("DTSG present:", "OUI" if re.search(r'DTSGInitialData', html) else "NON")
m = re.search(r'<title>([^<]+)</title>', html)
print("titre:", m.group(1)[:120] if m else "?")
d.quit()

