import os
import sys
import time
import json
import argparse
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"
SCHEDULE_FILE = "content/LIFESTYLE_SCHEDULE.json"

def publish_lifestyle_post(post_id):
    with open(SCHEDULE_FILE, "r", encoding="utf-8") as f:
        data = json.load(f)

    target = None
    for p in data.get("posts", []):
        if p.get("id") == post_id:
            target = p
            break

    if not target:
        print(f"❌ Không tìm thấy bài đăng với ID: {post_id}")
        return False

    image_path = str(Path(target["image"]).resolve())
    caption = target["caption"]
    title = target["title"]

    print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 🚀 Đang xuất bản bài đời thường: '{title}' ({post_id})...")

    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"Điều hướng về profile {PROFILE_URL}...")
        page.goto(PROFILE_URL, wait_until="domcontentloaded", timeout=40000)
        time.sleep(3)
        page.keyboard.press("Escape")
        time.sleep(1)

        # Mở Create post
        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)

        create_dialog = page.locator("div[role='dialog']:has-text('Create post'), div[role='dialog']:has-text('Tạo bài viết')").first
        if not create_dialog.is_visible():
            print("❌ Không mở được modal tạo bài viết.")
            return False

        # Chọn ảnh
        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(f"✅ Đã nạp file {image_path}!")
                time.sleep(5)
            except Exception as e:
                print("Fallback file_input:", e)
                file_input = page.locator("input[type='file']").first
                if file_input.count() > 0:
                    file_input.set_input_files(image_path)
                    time.sleep(5)

        # 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)

        # Bấm Post
        post_btn = create_dialog.locator("div[role='button'][aria-label='Post'], div[role='button']:has-text('Post')").last
        if post_btn.is_visible():
            post_btn.click(force=True)
            print("🚀 Bấm Post thành công! Chờ hoàn tất...")
            time.sleep(8)

        # Chụp ảnh xác thực
        page.mouse.wheel(0, 400)
        time.sleep(3)
        ss_path = f"FacebookAutoPoster/lifestyle_{post_id}_verified.png"
        page.screenshot(path=ss_path)
        print(f"📸 Lưu ảnh xác thực tại: {ss_path}")

    # Cập nhật schedule
    target["status"] = "published"
    target["published_at"] = time.strftime("%Y-%m-%d %H:%M PST")
    with open(SCHEDULE_FILE, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)
    print(f"✅ Đã cập nhật trạng thái {post_id} thành 'published'!")
    return True

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--id", required=True, help="Post ID from LIFESTYLE_SCHEDULE.json")
    args = parser.parse_args()
    publish_lifestyle_post(args.id)
