import os
import sys
import time
import json
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_coastal_highway1.jpg").resolve())
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"

print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 🚀 Bắt đầu đăng Lifestyle Post 2 (Seven Highway 1 Coastal Road Trip)...")

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

    # Đóng mọi modal đang dở
    page.keyboard.press("Escape")
    time.sleep(1)

    print(f"1. Điều hướng tới Profile cá nhân: {PROFILE_URL}...")
    page.goto(PROFILE_URL, wait_until="domcontentloaded", timeout=40000)
    time.sleep(3)
    page.keyboard.press("Escape")
    time.sleep(1)

    # 2. Click nút Photo/video hoặc What's on your mind
    print("2. Mở hộp thoại tạo bài viết trên Timeline...")
    photo_btn = page.locator("div[role='main'] div[role='button']:has-text('Photo/video'), div[role='main'] div[role='button']:has-text('Ảnh/video')").first
    if photo_btn.is_visible():
        print("Bấm nút Photo/video trực tiếp...")
        photo_btn.click(force=True)
        time.sleep(2)
    else:
        wom = page.locator("div[role='main'] div[role='button']:has-text(\"What's on your mind\"), div[role='main'] div[role='button']:has-text(\"Bạn đang nghĩ gì\")").first
        if wom.is_visible():
            print("Bấm nút What's on your mind...")
            wom.click(force=True)
            time.sleep(2)

    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 bằng Native CDP
    print(f"3. Nạp ảnh {IMAGE_PATH} qua CDP...")
    cdp = page.context.new_cdp_session(page)
    doc = cdp.send("DOM.getDocument")
    root_node_id = doc["root"]["nodeId"]
    res = cdp.send("DOM.querySelectorAll", {
        "nodeId": root_node_id,
        "selector": "input[type='file']"
    })
    node_ids = res.get("nodeIds", [])
    print(f"Tìm thấy {len(node_ids)} input file nodeIds: {node_ids}")

    if node_ids:
        cdp.send("DOM.setFileInputFiles", {
            "files": [IMAGE_PATH],
            "nodeId": node_ids[0]
        })
        print("✅ Đã setFileInputFiles thành công! Chờ 4s để ảnh nạp vào modal...")
        time.sleep(4)
    else:
        # Fallback qua FileChooser nếu cần
        add_photo_btn = create_dialog.locator("div[role='button'][aria-label*='Photo/video'], div[role='button'][aria-label*='Ảnh/video']").first
        if add_photo_btn.is_visible():
            with page.expect_file_chooser(timeout=5000) as fc_info:
                add_photo_btn.click(force=True)
            fc = fc_info.value
            fc.set_files(IMAGE_PATH)
            time.sleep(4)

    # 4. Gõ caption
    print("4. Nhập caption bài viết...")
    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.5)
        page.keyboard.press("Escape")
        time.sleep(1)
        print("✅ Đã nhập caption hoàn tất!")

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

    # 5. Bấm nút Post
    post_btn = create_dialog.locator("div[role='button'][aria-label='Post'], div[role='button']:has-text('Post'), div[role='button']:has-text('Đăng')").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("⏳ Chờ modal đóng (tối đa 40s)...")
        try:
            create_dialog.wait_for(state="hidden", timeout=40000)
            print("🎉 Modal Create post đã đóng thành công!")
        except Exception as e:
            print("Modal wait timeout/info:", e)

    # 6. Chờ Facebook render và tải lại trang profile để verify
    print("⏳ Chờ 10s và refresh Profile...")
    time.sleep(10)
    page.goto(PROFILE_URL, wait_until="domcontentloaded", timeout=40000)
    time.sleep(4)
    page.mouse.wheel(0, 450)
    time.sleep(3)
    page.screenshot(path="FacebookAutoPoster/lifestyle2_live_verified.png")
    print("📸 Đã chụp màn hình bài đăng mới: FacebookAutoPoster/lifestyle2_live_verified.png")

    # 7. Cập nhật LIFESTYLE_SCHEDULE.json
    try:
        with open(SCHEDULE_FILE, "r", encoding="utf-8") as f:
            data = json.load(f)
        for p_item in data.get("posts", []):
            if p_item.get("id") == "lifestyle_2":
                p_item["status"] = "published"
                p_item["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("Lỗi ghi file schedule:", e)

print("🎯 Hoàn thành xuất sắc đăng bài Lifestyle 2!")
