import time
import os
from typing import Dict, Any, Optional
from automation.platform_handlers.base_handler import BasePlatformHandler

class PinterestHandler(BasePlatformHandler):
    PLATFORM_NAME = "Pinterest"
    BASE_URL = "https://www.pinterest.com/pin-builder/"

    def __init__(self, brain=None):
        super().__init__(brain)
        self.captured_pin_id = [None]
        self._response_listener = None

    def phase_upload(self, page, flyer_path: str, guide: Optional[Dict[str, Any]] = None) -> bool:
        """
        Sesi 1: Upload Media
        Membuka Pinterest Pin Builder dan mengunggah flyer ke canvas.
        """
        upload_url = (guide and guide.get("direct_upload_url")) or self.BASE_URL
        self.log(f"Membuka Pinterest ({upload_url})...")
        try:
            page.goto(upload_url, wait_until="domcontentloaded", timeout=45000)
        except Exception as ne:
            self.log(f"Navigasi awal: {ne}", "WARN")

        time.sleep(3)
        self.dismiss_common_modals(page)
        self.setup_clipboard_interceptor(page)

        # Cek jika login diperlukan
        if self.check_login_required(page, guide):
            self.log("Pinterest membutuhkan login. Silakan login akun di Chrome Bot terlebih dahulu!", "ERROR")
            return False

        # Pastikan berada di Pin Builder / Create Pin
        is_builder = ("pin-builder" in page.url.lower()) or page.locator("input[type='file'], div[data-test-id='media-upload']").first.is_visible(timeout=2000)
        if not is_builder:
            self.log("Mencari tombol navigasi Buat Pin...")
            create_triggers = [
                "button[data-test-id='header-create-button']",
                "a[href*='pin-creation']",
                "a[href*='pin-builder']",
                "button:has-text('Create')",
                "button:has-text('Buat')"
            ]
            for ct in create_triggers:
                try:
                    c_el = page.locator(ct).first
                    if c_el.is_visible(timeout=1500):
                        c_el.click()
                        time.sleep(1.5)
                        break
                except Exception:
                    continue

        # Upload file flyer
        self.log("Mengunggah flyer gambar ke Pin Builder...")
        abs_flyer = os.path.abspath(flyer_path)
        file_uploaded = False

        try:
            page.set_input_files("input[type='file']", abs_flyer, timeout=4000)
            file_uploaded = True
            self.log("File flyer berhasil diunggah langsung ke input file.")
            time.sleep(2.5)
        except Exception:
            pass

        if not file_uploaded:
            dropzone_selectors = [
                "div[data-test-id='media-upload']",
                "div[data-test-id='storyboard-draft-media-upload-button']",
                "div[aria-label*='Upload']",
                "div:has-text('Choose a file')",
                "div:has-text('Pilih file')"
            ]
            for dz in dropzone_selectors:
                try:
                    dz_el = page.locator(dz).first
                    if dz_el.is_visible(timeout=1500):
                        try:
                            with page.expect_file_chooser(timeout=3000) as fc_info:
                                dz_el.click()
                            fc = fc_info.value
                            fc.set_files(abs_flyer)
                            file_uploaded = True
                            self.log(f"Flyer berhasil diunggah via file chooser ({dz}).")
                            time.sleep(2.5)
                            break
                        except Exception:
                            page.set_input_files("input[type='file']", abs_flyer)
                            file_uploaded = True
                            break
                except Exception:
                    continue

        # Vision Fallback jika dropzone tidak ditemukan
        if not file_uploaded and self.brain:
            self.log("Dropzone upload foto belum terdeteksi. Memanggil AI Vision...", "WARN")
            v_res = self.consult_vision(page, "Di mana area kotak klik untuk upload foto/gambar di Pinterest Pin Builder ini?")
            if v_res.get("coordinates_percent"):
                try:
                    with page.expect_file_chooser(timeout=3000) as fc_info:
                        self.click_visual_target(page, v_res, step_name="pinterest_dropzone")
                    fc = fc_info.value
                    fc.set_files(abs_flyer)
                    file_uploaded = True
                    time.sleep(2.5)
                except Exception:
                    try:
                        page.set_input_files("input[type='file']", abs_flyer)
                        file_uploaded = True
                    except Exception:
                        pass

        # Verifikasi: Cek apakah gambar muncul atau input form siap
        is_ready = file_uploaded or page.locator("input[placeholder*='title' i], #storyboard-selector-title").first.is_visible(timeout=3000)
        if is_ready:
            self.log("Sesi 1 (Upload Media) Pinterest terverifikasi sukses!", "SUCCESS")
        return is_ready

    def phase_metadata(self, page, title: str, caption: str, target_link: Optional[str] = None, guide: Optional[Dict[str, Any]] = None) -> bool:
        """
        Sesi 2: Content & Metadata
        Mengisi Judul, Deskripsi, Link, dan memilih Board (Papan).
        """
        self.log("Mengisi Judul, Deskripsi, dan memilih Papan (Board) Pinterest...")

        # 1. Judul Pin (Langsung tanpa auto-scroll liar)
        try:
            t_input = page.locator("input[placeholder*='title' i], input[placeholder*='judul' i], #storyboard-selector-title").first
            if t_input.is_visible(timeout=2000):
                t_input.fill(title[:95])
            else:
                page.keyboard.insert_text(title[:95])
            self.log("Judul Pin terisi.")
        except Exception as te:
            self.log(f"Isi judul: {te}", "WARN")

        # 2. Deskripsi Pin
        try:
            d_input = page.locator("div[contenteditable='true'], textarea[placeholder*='Pin' i], div[data-slate-editor='true']").first
            if d_input.is_visible(timeout=2000):
                d_input.fill(caption)
            self.log("Deskripsi Pin terisi.")
        except Exception as de:
            self.log(f"Isi deskripsi: {de}", "WARN")

        # 3. Link Tujuan (jika ada)
        if target_link:
            try:
                l_input = page.locator("input[placeholder*='link' i], input[placeholder*='tautan' i], input[id*='pin-draft-link']").first
                if l_input.is_visible(timeout=2000):
                    l_input.fill(target_link)
                self.log("Link tujuan terisi.")
            except Exception:
                pass

        time.sleep(1.0)

        # 4. Pemilihan Board (Wajib untuk Pinterest)
        self.log("Memeriksa dan memilih Board Pinterest...")
        board_selected = False
        board_triggers = [
            "button[data-test-id='board-dropdown-select-button']",
            "div[data-test-id='board-dropdown-select-button']",
            "button:has-text('Choose a board')",
            "button:has-text('Pilih papan')"
        ]
        for b_trig in board_triggers:
            try:
                b_el = page.locator(b_trig).first
                if b_el.is_visible(timeout=1000):
                    b_el.click()
                    time.sleep(1.2)
                    first_board = page.locator("div[role='listbox'] div[role='option'], div[data-test-id*='board-row'], div[role='option']").first
                    if first_board.is_visible(timeout=2000):
                        first_board.click()
                        board_selected = True
                        self.log("Board Pinterest berhasil dipilih.")
                        time.sleep(1.0)
                        break
            except Exception:
                continue

        # Vision Fallback jika board belum terpilih
        if not board_selected and self.brain:
            self.log("Menu Board Pinterest belum terpilih via selector. Memanggil AI Vision...", "WARN")
            v_res = self.consult_vision(page, "Cari tombol atau menu dropdown untuk memilih Board atau Papan di Pinterest Pin Builder. Berikan koordinatnya.")
            if v_res.get("coordinates_percent"):
                self.click_visual_target(page, v_res, step_name="pinterest_board_select")
                time.sleep(1.5)
                first_board = page.locator("div[role='listbox'] div[role='option'], div[role='option']").first
                if first_board.is_visible(timeout=2000):
                    first_board.click()
                    board_selected = True
                    time.sleep(1.0)

        return True

    def phase_publish(self, page, guide: Optional[Dict[str, Any]] = None) -> bool:
        """
        Sesi 3: Publish
        Menyiapkan penangkap respon API dan menekan tombol Publish / Simpan.
        """
        self.log("Menyiapkan pemantau jaringan dan menekan tombol Publish...")

        # Pasang listener jaringan untuk menangkap ID Pin secara instan
        self.captured_pin_id = [None]
        def on_response(response):
            try:
                r_url = response.url
                if any(k in r_url for k in ["PinResource/create", "PinResource", "/v3/pins/"]):
                    data = response.json()
                    res_data = data.get("resource_response", {}).get("data", {}) or data.get("data", {})
                    p_id = res_data.get("id") or res_data.get("pin_id")
                    if p_id:
                        self.captured_pin_id[0] = str(p_id)
            except Exception:
                pass

        self._response_listener = on_response
        page.on("response", on_response)

        publish_selectors = [
            "button[data-test-id='storyboard-creation-save-button']",
            "button[data-test-id='board-dropdown-save-button']",
            "button:has-text('Publish')",
            "button:has-text('Terbitkan')",
            "button:has-text('Save')",
            "button:has-text('Simpan')"
        ]
        clicked = False

        for _ in range(2):
            for sel in publish_selectors:
                try:
                    btn = page.locator(sel).first
                    if btn.is_visible(timeout=1000):
                        aria_dis = btn.get_attribute("aria-disabled")
                        if aria_dis != "true":
                            try:
                                btn.click(force=True)
                            except Exception:
                                btn.evaluate("el => el.click()")
                            clicked = True
                            self.log(f"Tombol Publish Pinterest berhasil diklik via ({sel})!", "SUCCESS")
                            break
                        else:
                            self.log("Tombol Publish Pinterest masih disabled (menunggu board/media)...", "INFO")
                except Exception:
                    continue
            if clicked:
                break
            time.sleep(1.5)

        # Vision Fallback jika tombol Publish masih disabled atau tidak terklik
        if not clicked and self.brain:
            self.log("Tombol Publish masih disabled atau tidak ditemukan. Memanggil AI Vision...", "WARN")
            v_res = self.consult_vision(page, "Cari tombol Publish atau Simpan Pin di Pinterest yang berwarna merah aktif. Berikan koordinatnya.")
            if v_res.get("coordinates_percent"):
                clicked = self.click_visual_target(page, v_res, step_name="pinterest_publish_btn")
                time.sleep(2)

        return clicked

    def phase_extract_link(self, page, title: str, guide: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        """
        Sesi 4: Ekstraksi Tautan
        1. Cek notifikasi toast 'See your Pin' / 'Lihat Pin Anda'.
        2. Cek ID Pin dari penangkap jaringan API.
        3. Cek URL browser langsung.
        4. Buka tab Created (https://www.pinterest.com/me/_created/).
        """
        self.log("Menunggu konfirmasi publikasi postingan Pinterest (jeda sabar 6s)...")
        time.sleep(6)
        self.dismiss_common_modals(page)

        pin_url = None

        # 1. Notifikasi toast 'See your Pin'
        try:
            see_pin = page.locator("a:has-text('See your Pin'), a:has-text('Lihat Pin Anda'), div[data-test-id*='toast'] a[href*='/pin/']").first
            if see_pin.is_visible(timeout=4000):
                href = see_pin.get_attribute("href")
                if href and "/pin/" in href:
                    pin_url = href if href.startswith("http") else f"https://www.pinterest.com{href}"
                    self.log(f"Tautan Pin ditemukan di toast: {pin_url}", "SUCCESS")
        except Exception:
            pass

        # 2. Respon jaringan API
        if not pin_url and self.captured_pin_id[0]:
            pin_url = f"https://www.pinterest.com/pin/{self.captured_pin_id[0]}/"
            self.log(f"Tautan Pin diekstrak dari respon API jaringan: {pin_url}", "SUCCESS")

        # 3. URL browser langsung
        if not pin_url and "/pin/" in page.url and "pin-builder" not in page.url:
            pin_url = page.url
            self.log(f"URL browser mengarah ke Pin: {pin_url}", "SUCCESS")

        # 4. Tab Created profil akun sendiri
        if not pin_url:
            self.log("Membuka tab Created profil Pinterest sendiri untuk menyalin link pin terbaru...")
            try:
                page.goto("https://www.pinterest.com/me/_created/", wait_until="domcontentloaded", timeout=25000)
                time.sleep(3.5)
                newest_pin = page.locator("div[data-test-id='pin'] a[href*='/pin/'], a[href*='/pin/']").first
                if newest_pin.is_visible(timeout=4000):
                    href = newest_pin.get_attribute("href")
                    if href and "/pin/" in href:
                        pin_url = href if href.startswith("http") else f"https://www.pinterest.com{href}"
                        self.log(f"Tautan Pin ditemukan di tab Created: {pin_url}", "SUCCESS")
            except Exception as pe:
                self.log(f"Pemeriksaan tab Created: {pe}", "WARN")

        # Cleanup listener
        if self._response_listener:
            try:
                page.remove_listener("response", self._response_listener)
            except Exception:
                pass

        if not pin_url or "pin-builder" in pin_url:
            self.log("Gagal memverifikasi URL spesifik Pin (/pin/...). Tidak mencatat pin-builder.", "ERROR")
            return {
                "success": False,
                "post_url": None,
                "message": "FAILED: Pin berhasil diunggah tapi tautan spesifik pin (/pin/...) tidak dapat diverifikasi."
            }

        self.log(f"Berhasil! Tautan Pin terverifikasi: {pin_url}", "SUCCESS")
        return {
            "success": True,
            "post_url": pin_url,
            "message": "Pin berhasil dipublikasikan di Pinterest!"
        }
