import os
import sys
import time
import random
from pathlib import Path
from playwright.sync_api import sync_playwright

sys.stdout.reconfigure(encoding='utf-8')

CDP_URL = "http://localhost:9224"

def organic_surf(duration_minutes: float = 2.0, max_likes: int = 1):
    print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 🌙 Bắt đầu phiên lướt Facebook hữu cơ (Dự kiến: {duration_minutes} phút)...")
    
    with sync_playwright() as p:
        try:
            browser = p.chromium.connect_over_cdp(CDP_URL)
        except Exception as e:
            print(f"❌ Không thể kết nối tới Chrome cổng 9224: {e}")
            return False
            
        context = browser.contexts[0]
        page = context.pages[0] if context.pages else context.new_page()
        
        # 1. Điều hướng tới News Feed
        print("🌐 Đang vào bảng tin Facebook (News Feed)...")
        if "facebook.com" not in page.url or page.url == "chrome://intro/":
            page.goto("https://www.facebook.com/", wait_until="domcontentloaded", timeout=45000)
            page.wait_for_timeout(4000)
        else:
            page.goto("https://www.facebook.com/", wait_until="domcontentloaded", timeout=45000)
            page.wait_for_timeout(3000)
            
        # Kiểm tra trạng thái đăng nhập
        if "login" in page.url:
            print("⚠️ CẢNH BÁO: Trình duyệt chưa đăng nhập Facebook!")
            return False
            
        print("✅ Đã kết nối vào bảng tin chính của tài khoản Seven Nguyen!")
        page.screenshot(path=r"C:\Projects\Historical\FacebookAutoPoster\feed_start.png")
        
        start_time = time.time()
        end_time = start_time + (duration_minutes * 60)
        scroll_count = 0
        likes_given = 0
        
        while time.time() < end_time:
            scroll_count += 1
            # 1. Cuộn một đoạn ngẫu nhiên (mô phỏng con lăn chuột tự nhiên)
            delta_y = random.randint(300, 750)
            page.mouse.wheel(0, delta_y)
            
            # 2. Dwell time: Thời gian dừng lại đọc bài ngẫu nhiên (2 - 7 giây)
            dwell = random.uniform(2.5, 6.5)
            # Thỉnh thoảng (20% xác suất) dừng lại lâu hơn như đang xem video hoặc đọc bài dài (8 - 14 giây)
            if random.random() < 0.20:
                dwell = random.uniform(8.0, 14.0)
                print(f"  👀 [Dừng đọc kỹ/Xem clip] Đang xem bài viết trong {dwell:.1f}s...")
            else:
                print(f"  📜 [Cuộn #{scroll_count}] Cuộn {delta_y}px -> Dừng đọc {dwell:.1f}s...")
                
            time.sleep(dwell)
            
            # 3. Di chuột ngẫu nhiên nhẹ nhàng
            viewport = page.viewport_size or {"width": 1280, "height": 800}
            target_x = random.randint(300, viewport["width"] - 300)
            target_y = random.randint(200, viewport["height"] - 200)
            page.mouse.move(target_x, target_y, steps=random.randint(5, 15))
            
            # 4. Tương tác nhẹ (thả Like cho 1 bài viết phù hợp, tránh bài quảng cáo tài trợ)
            if likes_given < max_likes and random.random() < 0.25:
                # Tìm các nút Like đang hiển thị trong viewport
                like_btns = page.locator("div[role='button'][aria-label*='Like'], div[role='button'][aria-label*='Thích']").all()
                for btn in like_btns:
                    try:
                        box = btn.bounding_box()
                        # Chỉ bấm nút like nếu nó đang nằm trọn trong vùng nhìn thấy của màn hình
                        if box and 100 < box['y'] < (viewport['height'] - 100):
                            # Kiểm tra xem bài này có bị Sponsored không
                            parent_post = btn.locator("xpath=ancestor::div[@role='feed']/*")
                            btn.hover()
                            time.sleep(random.uniform(0.5, 1.2))
                            btn.click()
                            likes_given += 1
                            print(f"  👍 [Tương tác hữu cơ] Đã thả Like cho 1 bài viết tự nhiên trên Feed (Tổng: {likes_given}/{max_likes})")
                            time.sleep(random.uniform(2.0, 4.0))
                            break
                    except Exception:
                        continue
                        
        print(f"\n[{time.strftime('%Y-%m-%d %H:%M:%S')}] 🌙 Hoàn tất phiên lướt đêm! Tổng số lần cuộn: {scroll_count}, Đã Like: {likes_given}")
        page.screenshot(path=r"C:\Projects\Historical\FacebookAutoPoster\feed_finish.png")
        print("📸 Đã lưu ảnh chụp màn hình cuối phiên: feed_finish.png")
        return True

if __name__ == "__main__":
    dur = float(sys.argv[1]) if len(sys.argv) > 1 else 1.5
    organic_surf(duration_minutes=dur)
