import os
import sys
import time
from pathlib import Path
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"
IMAGE_PATH = str(Path("FacebookAutoPoster/lifestyle_media/seven_santana_row_cafe.jpg").resolve())
CAPTION = (
    "Trời Cali hôm nay dịu nắng, tranh thủ ngồi nhâm nhi ly cà phê sáng ở Santana Row trước khi vào guồng dựng phim cho tuần mới. ☀️☕️\n\n"
    "Sometimes the best inspiration comes when you just step away from the timeline, sit outside, and let your thoughts wander. Wishing everyone a peaceful and productive weekend!\n\n"
    "📍 Santana Row, San Jose"
)

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

    print(f"Navigating to {PROFILE_URL}...")
    page.goto(PROFILE_URL, wait_until="domcontentloaded", timeout=40000)
    time.sleep(3)
    page.keyboard.press("Escape")
    time.sleep(1)

    # 1. Mở Create post
    print("Mở hộp thoại tạo bài viết trên trang cá nhân...")
    wom = page.locator("div[role='main'] div[role='button']:has-text(\"What's on your mind\"), div[role='button']:has-text(\"Bạn đang nghĩ gì\")").first
    if wom.is_visible():
        wom.click(force=True)
        time.sleep(2)

    # 2. Định vị modal Create post
    create_dialog = page.locator("div[role='dialog']:has-text('Create post'), div[role='dialog']:has-text('Tạo bài viết')").first
    print("Create post dialog visible:", create_dialog.is_visible())

    # 3. Nạp ảnh qua Photo/video
    photo_btn = create_dialog.locator("div[role='button'][aria-label*='Photo/video'], div[role='button'][aria-label*='Ảnh/video']").first
    if photo_btn.is_visible():
        try:
            with page.expect_file_chooser(timeout=7000) as fc_info:
                photo_btn.click(force=True)
            fc = fc_info.value
            fc.set_files(IMAGE_PATH)
            print("✅ Đã nạp ảnh Santana Row qua file chooser! Chờ 5s...")
            time.sleep(5)
        except Exception as e:
            print("File chooser exception:", e)
            file_input = page.locator("input[type='file']").first
            if file_input.count() > 0:
                file_input.set_input_files(IMAGE_PATH)
                time.sleep(5)

    # 4. Nhập caption
    textbox = create_dialog.locator("div[role='textbox'][contenteditable='true']").first
    if textbox.is_visible():
        textbox.click(force=True)
        time.sleep(0.5)
        page.keyboard.insert_text(CAPTION)
        time.sleep(1)
        page.keyboard.press("Escape")
        time.sleep(1)
        print("✅ Đã nhập caption xong!")

    page.screenshot(path="FacebookAutoPoster/post1_cafe_ready.png")
    print("Saved post1_cafe_ready.png")

    # 5. Bấm nút Post
    post_btn = create_dialog.locator("div[role='button'][aria-label='Post'], div[role='button']:has-text('Post')").last
    print("Post button visible:", post_btn.is_visible())
    if post_btn.is_visible():
        post_btn.click(force=True)
        print("🚀 Đã bấm Post! Chờ modal đóng...")
        time.sleep(8)

    # 6. Cuộn xuống kiểm tra bài đăng mới
    page.mouse.wheel(0, 400)
    time.sleep(3)
    page.screenshot(path="FacebookAutoPoster/post1_cafe_live.png")
    print("Saved post1_cafe_live.png")
