import sys
import time
import json
from playwright.sync_api import sync_playwright

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

CAPTION = (
    "Driving down Highway 1 never gets old. Whenever the screen fatigue hits from hours of video rendering, a 45-minute drive out to the coast is the best reset button. 🌊🚗\n\n"
    "Gió biển mát rượi, nhìn sóng vỗ vào vách đá cảm giác nhẹ bẫng. Một buổi chiều nạp lại năng lượng trọn vẹn trước khi trở lại bàn làm việc.\n\n"
    "#Highway1 #NorCal #CaliforniaCoast #WeekendVibes #PacificBreeze"
)
SCHEDULE_FILE = "content/LIFESTYLE_SCHEDULE.json"
PROFILE_URL = "https://www.facebook.com/profile.php?id=61594841053758"

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

    dialog = page.locator("div[role='dialog']:has-text('Create post')").first
    print("Dialog is visible:", dialog.is_visible())

    # Insert caption
    textbox = dialog.locator("div[role='textbox'][contenteditable='true']").first
    if textbox.is_visible():
        print("Clicking textbox and inserting caption...")
        textbox.click(force=True)
        time.sleep(0.5)
        page.keyboard.insert_text(CAPTION)
        time.sleep(1.5)
        print("✅ Caption inserted successfully!")

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

    # Click Post button
    post_btn = dialog.locator("div[role='button'][aria-label='Post'], div[role='button']:has-text('Post')").last
    print("Post button visible:", post_btn.is_visible())
    is_disabled = post_btn.get_attribute("aria-disabled")
    print("Post button aria-disabled:", is_disabled)

    if post_btn.is_visible() and is_disabled != "true":
        print("🚀🚀 BẤM NÚT POST! 🚀🚀")
        post_btn.click(force=True)
        print("⏳ Đang chờ modal đóng...")
        try:
            dialog.wait_for(state="hidden", timeout=30000)
            print("🎉 Modal Create post đã đóng thành công!")
        except Exception as e:
            print("Dialog hidden wait info:", e)

    time.sleep(5)
    print("🔄 Tải lại Profile để chụp ảnh bài viết live...")
    page.goto(PROFILE_URL, wait_until="domcontentloaded", timeout=40000)
    time.sleep(4)
    page.mouse.wheel(0, 500)
    time.sleep(3)

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

    # Update LIFESTYLE_SCHEDULE.json
    try:
        with open(SCHEDULE_FILE, "r", encoding="utf-8") as f:
            data = json.load(f)
        for post in data.get("posts", []):
            if post.get("id") == "lifestyle_2":
                post["status"] = "published"
                post["published_at"] = time.strftime("%Y-%m-%d %H:%M PST")
                break
        with open(SCHEDULE_FILE, "w", encoding="utf-8") as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        print("✅ Đã cập nhật LIFESTYLE_SCHEDULE.json: status=published!")
    except Exception as e:
        print("Error updating schedule json:", e)

print("🎯 Lifestyle 2 published successfully!")
