import sys
import time
from playwright.sync_api import sync_playwright

USER_DATA_DIR = "C:/Projects/Historical/FacebookAutoPoster/chrome_profile"

def post_to_facebook(content: str, page_url: str = "https://www.facebook.com/"):
    print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] Agent đang ra lệnh đăng bài...")
    with sync_playwright() as p:
        browser = p.chromium.launch_persistent_context(
            user_data_dir=USER_DATA_DIR,
            headless=False,
            args=["--disable-notifications"]
        )
        page = browser.pages[0]
        
        try:
            page.goto(page_url, wait_until="domcontentloaded", timeout=60000)
            page.wait_for_timeout(5000)
            
            # KIỂM TRA TRẠNG THÁI ĐĂNG NHẬP
            if "login" in page.url or page.locator('input[name="email"]').is_visible():
                print("⚠️ CẢNH BÁO: Trình duyệt chưa đăng nhập hoặc bị văng session!")
                print("👉 HÃY NHÌN VÀO CỬA SỔ CHROME VÀ TỰ TAY ĐĂNG NHẬP NGAY BÂY GIỜ.")
                print("⏳ Bot sẽ đứng chờ 60 giây để bạn thao tác...")
                page.wait_for_timeout(60000)
                
                if "login" in page.url or page.locator('input[name="email"]').is_visible():
                    print("❌ Vẫn chưa đăng nhập thành công. Bot tự động hủy.")
                    return
            
            print("Đang mở form đăng bài (Phím tắt 'P')...")
            page.keyboard.press("Escape")
            page.wait_for_timeout(1000)
            
            page.keyboard.press("p")
            page.wait_for_timeout(4000)
            
            print("Đang điền nội dung...")
            textbox = page.locator("div[role='textbox'][contenteditable='true']")
            if textbox.count() > 0:
                textbox.last.click(timeout=3000)
                page.wait_for_timeout(500)
                page.keyboard.insert_text(content)
            else:
                print("Cảnh báo: Không tìm thấy textbox. Bắt đầu click cơ học...")
                page.mouse.click(500, 300)
                page.wait_for_timeout(2000)
                if textbox.count() > 0:
                    textbox.last.click()
                    page.keyboard.insert_text(content)
                else:
                    print("❌ Vẫn không tìm thấy textbox.")
                    return
                    
            page.wait_for_timeout(3000)
            
            print("Đang bấm đăng (Ctrl + Enter)...")
            page.keyboard.down("Control")
            page.keyboard.press("Enter")
            page.keyboard.up("Control")
            
            print("✅ Đã phát lệnh Đăng bài thành công!")
            page.wait_for_timeout(8000)
                
        except Exception as e:
            print(f"❌ Lỗi: {e}")
        finally:
            browser.close()

if __name__ == "__main__":
    if len(sys.argv) > 1:
        file_path = sys.argv[1]
        with open(file_path, "r", encoding="utf-8") as f:
            content = f.read()
        post_to_facebook(content)
