"""
Facebook Group Persona Agent - Seven Nguyen
Module tương tác hội nhóm tự nhiên theo đúng vị thế nhân vật:
- Tên: Seven Nguyen (35 tuổi)
- Nghề nghiệp: Nhà làm phim / Đạo diễn tư liệu tại The History Vault
- Nơi sống: San Jose, California (cựu sinh viên San Jose State University - SJSU)
- Phong cách: Lịch thiệp, khiêm tốn, giàu trải nghiệm sống ở Mỹ, am hiểu nghệ thuật - điện ảnh - văn hóa.
- Nguyên tắc: KHÔNG spam link, KHÔNG nói sáo rỗng. Chia sẻ kinh nghiệm thực tế hoặc góc nhìn thẩm mỹ có giá trị.
"""

import os
import sys
import time
import json
import random
from pathlib import Path
from playwright.sync_api import sync_playwright

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

CDP_URL = "http://127.0.0.1:9224"
INTERACTIONS_FILE = Path("FacebookAutoPoster/group_interactions.json")

# Danh sách hội nhóm mục tiêu ưu tiên
DEFAULT_GROUPS = [
    {
        "name": "Hội du học sinh Việt Nam tại bang California",
        "url": "https://www.facebook.com/groups/835457716553897/",
        "focus": "Du học sinh, đời sống học tập & sinh hoạt tại California, DMV, nhà ở, nghệ thuật"
    },
    {
        "name": "Hội Du Học Sinh Việt Nam Tại Úc",
        "url": "https://www.facebook.com/groups/HoiDuHocSinhVietNamTaiUc/",
        "focus": "Giao lưu cộng đồng du học sinh quốc tế"
    }
]

def load_interactions():
    if INTERACTIONS_FILE.exists():
        try:
            with open(INTERACTIONS_FILE, "r", encoding="utf-8") as f:
                return json.load(f)
        except Exception:
            return []
    return []

def save_interaction(record):
    interactions = load_interactions()
    interactions.append(record)
    with open(INTERACTIONS_FILE, "w", encoding="utf-8") as f:
        json.dump(interactions, f, ensure_ascii=False, indent=2)

def generate_persona_response(post_text: str, author_name: str) -> str:
    """
    Suy luận và tạo câu trả lời từ góc nhìn nhân vật Seven Nguyen (35 tuổi, San Jose, Nhà làm phim).
    """
    text_lower = post_text.lower()
    
    # Chủ đề 1: Hỏi về thi lái xe / DMV / Bằng lái tại California
    if any(k in text_lower for k in ["lái xe", "dmv", "bằng lái", "road test", "thầy dạy lái"]):
        templates = [
            "Khu Garden Grove hoặc Westminster em có thể dợt quanh DMV Westminster hoặc Fullerton cho quen sơ đồ đường. Nhớ kỹ vụ full stop đủ 3 giây ở stop sign với xoay hẳn vai check blind spot dứt khoát là qua dễ dàng em nhé. Chúc em sớm có bằng lái!",
            "Kinh nghiệm thi DMV ở Cali là tâm lý phải thật bình tĩnh em ạ. Trước khi chuyển làn nhớ signal sớm 3-4 giây, quay đầu nhìn vai rõ ràng cho examiner thấy. Chúc em thi một lần là pass luôn nhé!"
        ]
        return random.choice(templates)

    # Chủ đề 2: Âm nhạc / Nghệ thuật / Hình ảnh / Video cổ phong
    elif any(k in text_lower for k in ["ca khúc", "nhạc", "bài hát", "mộng ảo", "thước phim", "video", "youtube", "bến nước"]):
        templates = [
            f"Visual và tone màu hoài niệm đẹp quá bạn. Đoạn bến nước sương khói nhìn có chất điện ảnh ghê. Nghe giữa trưa thấy tĩnh tâm hẳn. Chúc bạn một ngày an lành nhé!",
            "Giai điệu mộc mạc và sâu lắng thật sự. Những bối cảnh cổ phong thế này luôn tạo được cảm xúc rất riêng. Cảm ơn bạn đã chia sẻ ca khúc hay!"
        ]
        return random.choice(templates)

    # Chủ đề 3: Học tập / Đời sống tại San Jose / California
    elif any(k in text_lower for k in ["san jose", "sjsu", "bay area", "cali", "california", "thuê nhà", "trường học"]):
        templates = [
            "Chào bạn, mình cũng sống ở khu San Jose nhiều năm rồi. Nhịp sống bên này quen rồi thì rất thích, khí hậu dễ chịu và cộng đồng người Việt mình cũng đông vui, ấm áp. Chúc bạn có những trải nghiệm thật đáng nhớ tại Cali nhé!",
            "Ở California thời gian đầu mới qua có thể hơi bỡ ngỡ về phương tiện và nhịp sống, nhưng khu Bay Area hay San Jose có rất nhiều chỗ hỗ trợ cộng đồng sinh viên. Cần kinh nghiệm gì cứ hỏi mọi người nhé!"
        ]
        return random.choice(templates)

    # Chủ đề 4: Tương tác chúc mừng / Giao lưu chung
    else:
        templates = [
            "Chia sẻ rất ý nghĩa và năng lượng tích cực! Chúc bạn và mọi người trong nhóm một tuần mới thật nhiều may mắn và suôn sẻ nhé.",
            "Một góc nhìn rất thú vị. Cảm ơn bạn đã chia sẻ thông tin hữu ích cho cộng đồng du học sinh bên này nhé!"
        ]
        return random.choice(templates)

def ensure_chrome_running():
    import urllib.request
    import subprocess
    try:
        with urllib.request.urlopen("http://127.0.0.1:9224/json", timeout=2) as resp:
            if resp.status == 200:
                return True
    except Exception:
        pass

    print("[Tự động hồi phục] Chrome cổng 9224 chưa chạy, đang khởi động Chrome Native...")
    ps1_path = r"C:\Projects\Historical\FacebookAutoPoster\open_stealth_chrome.ps1"
    subprocess.Popen(["powershell.exe", "-ExecutionPolicy", "Bypass", "-File", ps1_path])

    for i in range(15):
        time.sleep(1)
        try:
            with urllib.request.urlopen("http://127.0.0.1:9224/json", timeout=2) as resp:
                if resp.status == 200:
                    print(f"✅ Chrome Native cổng 9224 đã sẵn sàng sau {i+1}s!")
                    return True
        except Exception:
            pass
    return False

def engage_group(group_url: str = None, max_comments: int = 1):
    ensure_chrome_running()
    if not group_url:
        target = random.choice(DEFAULT_GROUPS)
        group_url = target["url"]
        group_name = target["name"]
    else:
        group_name = "Nhóm chỉ định"

    print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 🚀 Bắt đầu phiên tương tác hội nhóm từ vị thế Seven Nguyen...")
    print(f"👉 Nhóm mục tiêu: {group_name} ({group_url})")

    with sync_playwright() as p:
        try:
            browser = p.chromium.connect_over_cdp(CDP_URL)
        except Exception as e:
            print(f"❌ Không thể kết nối tới Chrome cổng 9224: {e}")
            return False

        context = browser.contexts[0]
        page = context.pages[0] if context.pages else context.new_page()

        page.goto(group_url, wait_until="domcontentloaded", timeout=60000)
        page.wait_for_timeout(4000)

        # Cuộn tự nhiên để đọc bài viết
        page.mouse.wheel(0, 600)
        page.wait_for_timeout(3000)

        # Quét các ô bình luận đang sẵn sàng trên feed
        comment_inputs = page.locator(
            "div[role='textbox'][contenteditable='true'][aria-label*='Write a public comment'], "
            "div[role='textbox'][contenteditable='true'][aria-label*='Viết bình luận công khai'], "
            "div[role='textbox'][contenteditable='true'][aria-label*='comment']"
        )
        total_boxes = comment_inputs.count()
        print(f"🔍 Tìm thấy {total_boxes} ô bình luận tiềm năng trên Feed nhóm.")

        if total_boxes == 0:
            # Thử click nút Comment nếu ô nhập bị thu gọn
            comment_btns = page.locator("div[role='button'][aria-label*='Comment'], div[role='button'][aria-label*='Bình luận']")
            if comment_btns.count() > 0:
                comment_btns.first.click()
                page.wait_for_timeout(2000)
                comment_inputs = page.locator("div[role='textbox'][contenteditable='true']")
                total_boxes = comment_inputs.count()

        if total_boxes == 0:
            print("⚠️ Không có bài viết nào mở bình luận hoặc cần cuộn thêm.")
            return False

        # Chọn 1 ô bình luận thích hợp (ví dụ bài thứ 1 hoặc thứ 2)
        target_idx = min(1, total_boxes - 1)
        target_box = comment_inputs.nth(target_idx)
        target_box.scroll_into_view_if_needed()
        page.wait_for_timeout(1000)

        # Tìm ngữ cảnh bài viết gần ô comment này
        parent_post = target_box.locator("xpath=ancestor::div[@role='feed']/*")
        post_snippet = parent_post.inner_text() if parent_post.count() > 0 else ""
        print(f"\n📖 [Đọc bài viết]:\n{post_snippet[:250]}...\n")

        # Suy ngẫm trong vai Seven Nguyen
        reply_content = generate_persona_response(post_snippet, "bạn")
        print(f"🧠 [Seven Nguyen Suy Nghĩ & Phản Hồi]:\n\"{reply_content}\"\n")

        # Di chuột tự nhiên vào ô nhập
        box_rect = target_box.bounding_box()
        if box_rect:
            page.mouse.move(box_rect['x'] + 20, box_rect['y'] + 10, steps=8)
            time.sleep(0.3)
            page.mouse.click(box_rect['x'] + 20, box_rect['y'] + 10)
        else:
            target_box.click()

        page.wait_for_timeout(800)

        # Gõ từng ký tự mô phỏng người thật
        print("✍️ Đang gõ bình luận tự nhiên...")
        for ch in reply_content:
            page.keyboard.insert_text(ch)
            time.sleep(random.uniform(0.02, 0.08))

        page.wait_for_timeout(1500)
        print("🚀 Gửi bình luận...")
        page.keyboard.press("Enter")
        page.wait_for_timeout(5000)

        # Lưu ảnh bằng chứng
        ss_path = f"FacebookAutoPoster/group_comment_verified_{int(time.time())}.png"
        page.screenshot(path=ss_path)
        print(f"📸 Đã chụp ảnh xác thực tại: {ss_path}")

        # Ghi nhật ký tương tác
        record = {
            "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
            "group_name": group_name,
            "group_url": group_url,
            "post_snippet": post_snippet[:200],
            "reply_content": reply_content,
            "screenshot": ss_path
        }
        save_interaction(record)
        print("✅ Hoàn tất tương tác hội nhóm thành công!")
        return True

if __name__ == "__main__":
    url_arg = sys.argv[1] if len(sys.argv) > 1 else None
    engage_group(group_url=url_arg)
