import sys
import time
from playwright.sync_api import sync_playwright

if hasattr(sys.stdout, 'reconfigure'):
    sys.stdout.reconfigure(encoding='utf-8')

PROFILE_URL = "https://www.facebook.com/profile.php?id=61594841053758"

print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 🏄 Bắt đầu lướt các hội nhóm và tương tác tự nhiên...")

with sync_playwright() as p:
    browser = p.chromium.connect_over_cdp("http://127.0.0.1:9224")
    page = browser.contexts[0].pages[0]

    # 1. Kiểm tra số lượng bạn bè mới trên profile
    print(f"1. Kiểm tra số bạn bè mới trên Profile...")
    page.goto(PROFILE_URL, wait_until="domcontentloaded", timeout=40000)
    time.sleep(3)
    friends_el = page.locator("a[href*='friends']:has-text('friends'), a[href*='friends']:has-text('bạn bè')").first
    print("👉 Số lượng bạn bè hiện tại:", friends_el.inner_text().strip().replace('\n', ' ') if friends_el.is_visible() else "N/A")
    page.screenshot(path="FacebookAutoPoster/profile_milestone_friends.png")
    print("📸 Saved: FacebookAutoPoster/profile_milestone_friends.png")

    # 2. Vào Groups Feed (Bảng tin hội nhóm)
    print("\n2. Mở Bảng tin nhóm (Groups Feed)...")
    page.goto("https://www.facebook.com/groups/feed/", wait_until="domcontentloaded", timeout=40000)
    time.sleep(4)
    page.keyboard.press("Escape")
    time.sleep(1)

    page.screenshot(path="FacebookAutoPoster/groups_feed_1.png")
    print("📸 Saved: FacebookAutoPoster/groups_feed_1.png")

    # Cuộn chậm rãi đọc các bài viết trong nhóm
    print("Cuộn xem các bài viết thảo luận trong nhóm...")
    for step in range(3):
        page.mouse.wheel(0, 500)
        time.sleep(2.5)

    page.screenshot(path="FacebookAutoPoster/groups_feed_scrolled.png")
    print("📸 Saved: FacebookAutoPoster/groups_feed_scrolled.png")

    # 3. Tương tác Like nhẹ nhàng trên 1 bài thảo luận tích cực
    like_btns = page.locator("div[role='button'][aria-label*='Like'], div[role='button'][aria-label*='Thích']").all()
    print(f"Tìm thấy {len(like_btns)} nút Like trong nhóm feed.")
    if len(like_btns) > 1:
        # Bấm like bài thứ 2 hoặc 3 (tự nhiên như người dùng thật)
        target_like = like_btns[1]
        if target_like.is_visible():
            print("👍 Thả Like tương tác tự nhiên trên bài viết nhóm...")
            target_like.click(force=True)
            time.sleep(2)

    # 4. Ghé thăm nhóm Cali người Việt cụ thể
    print("\n3. Ghé thăm nhóm Cộng đồng người Việt tại California / Bay Area...")
    cali_group_url = "https://www.facebook.com/groups/835457716553897/"
    page.goto(cali_group_url, wait_until="domcontentloaded", timeout=40000)
    time.sleep(4)
    page.keyboard.press("Escape")
    time.sleep(1)

    page.mouse.wheel(0, 400)
    time.sleep(3)
    page.screenshot(path="FacebookAutoPoster/cali_group_browsing.png")
    print("📸 Saved: FacebookAutoPoster/cali_group_browsing.png")

    # Đọc tiêu đề một số bài viết đang thảo luận
    articles = page.locator("div[role='feed'] > div, div[role='article']").all()
    print(f"Tìm thấy {len(articles)} bài viết trong nhóm Cali.")
    for idx, art in enumerate(articles[:3]):
        snippet = art.inner_text().strip().replace('\n', ' ')[:150]
        if snippet:
            print(f"  [Bài #{idx+1}]: {snippet}...")

    # Cuộn thêm một chút như người dùng thật đang đọc tin
    page.mouse.wheel(0, 500)
    time.sleep(3)
    page.mouse.wheel(0, -200)
    time.sleep(2)

    # Like 1 bài trong nhóm Cali nếu thấy phù hợp
    cali_likes = page.locator("div[role='button'][aria-label*='Like'], div[role='button'][aria-label*='Thích']").all()
    if cali_likes:
        print("👍 Thả Like cho 1 bài viết đời thường trong nhóm Cali...")
        cali_likes[0].click(force=True)
        time.sleep(2)

    page.screenshot(path="FacebookAutoPoster/cali_group_interacted.png")
    print("📸 Saved: FacebookAutoPoster/cali_group_interacted.png")

print("\n🎉 Hoàn thành xuất sắc toàn bộ chuỗi tương tác tự nhiên trên hội nhóm!")
