#!/usr/bin/env python3
"""Extract X/Twitter cookies from Chrome and save for twikit (same as docker container)"""
import json
import os
from pathlib import Path

try:
    import rookiepy
except ImportError:
    print("ERROR: pip install rookiepy")
    exit(1)

OUTPUT = Path(__file__).parent / 'x_cookies.json'

print("[*] Extracting Chrome cookies for x.com / twitter.com...")
cookies = rookiepy.chrome(domains=["x.com", ".x.com", "twitter.com", ".twitter.com"])

if not cookies:
    print("[!] No cookies found for x.com or twitter.com")
    exit(1)

print(f"[+] Found {len(cookies)} cookies")

# Show key cookie names (auth indicators)
cookie_names = [c['name'] for c in cookies]
auth_cookies = [n for n in cookie_names if n in ['auth_token', 'ct0', 'twid', 'kdt']]
print(f"[+] Auth cookies found: {auth_cookies}")

# Save as twikit-compatible format (dict of name:value)
cookie_dict = {c['name']: c['value'] for c in cookies}
with open(OUTPUT, 'w') as f:
    json.dump(cookie_dict, f, indent=2)

print(f"[+] Cookies saved to {OUTPUT}")

# Verify critical cookies
has_auth = 'auth_token' in cookie_dict
has_ct0 = 'ct0' in cookie_dict
print(f"auth_token: {'YES' if has_auth else 'MISSING'}")
print(f"ct0: {'YES' if has_ct0 else 'MISSING'}")

if not (has_auth and has_ct0):
    print("\n[!] WARNING: Missing critical auth cookies. Log into X in Chrome first.")
    exit(1)

print("\n[+] Cookies ready for twikit!")
