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

class GenericAiHandler(BasePlatformHandler):
    """
    Universal AI-driven handler for social media platforms.
    Uses Gemini AI to inspect the live condensed DOM, detect input fields and buttons,
    and execute the posting pipeline dynamically.
    """

    def __init__(self, brain=None, domain: str = "generic"):
        super().__init__(brain=brain)
        self.domain = domain
        self.PLATFORM_NAME = domain.capitalize()

    def phase_upload(self, page, flyer_path: str, guide: Optional[Dict[str, Any]] = None) -> bool:
        """
        Sesi 1: Upload Media
        Membuka halaman target, memeriksa status login, dan melampirkan berkas flyer ke input file.
        """
        target_url = (guide and guide.get("direct_upload_url")) or f"https://{self.domain}/"
        self.log(f"AI Engine membuka {target_url}...")

        try:
            page.goto(target_url, wait_until="domcontentloaded", timeout=45000)
        except Exception as nav_err:
            self.log(f"Navigasi awal ({nav_err}), melanjutkan...", "WARN")

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

        # 1. Cek Login Universal
        if self.check_login_required(page, guide):
            self.log(f"{self.PLATFORM_NAME} membutuhkan login. Silakan login akun di Chrome Bot!", "ERROR")
            return False

        # 2. Dismiss modal kustom dari guide jika ada
        custom_dismiss = (guide and guide.get("dismiss_modal_selectors")) or []
        for sel in custom_dismiss:
            try:
                btn = page.locator(sel).first
                if btn.is_visible(timeout=1500):
                    btn.click()
                    time.sleep(1)
            except Exception:
                pass

        # 3. Klik tombol Create Post / Buat Proyek jika diperlukan
        create_selectors = (guide and guide.get("create_post_button_selectors")) or [
            "button:has-text('Create')", "button:has-text('Post')", "a[href*='submit']",
            "svg[aria-label='Create']", "div[role='button']:has-text('Create')",
            "a:has-text('Share Work')", "button:has-text('New Post')"
        ]
        for sel in create_selectors:
            try:
                btn = page.locator(sel).first
                if btn.is_visible(timeout=2000):
                    btn.click()
                    time.sleep(2)
                    break
            except Exception:
                pass

        # 4. Unggah Flyer Berkas langsung ke input file DOM
        self.log(f"Mengunggah flyer gambar ke {self.PLATFORM_NAME}...")
        file_selectors = (guide and guide.get("file_input_selectors")) or [
            "input[type='file'][accept*='image']",
            "input[type='file']"
        ]
        file_uploaded = False
        abs_flyer = os.path.abspath(flyer_path)

        for sel in file_selectors:
            try:
                inputs = page.locator(sel).all()
                for inp in inputs:
                    try:
                        inp.set_input_files(abs_flyer)
                        file_uploaded = True
                        self.log(f"Flyer terpasang via selector ({sel}).")
                        time.sleep(2.5)
                        break
                    except Exception:
                        continue
                if file_uploaded:
                    break
            except Exception:
                continue

        # Vision Fallback jika input file belum terpasang
        if not file_uploaded and self.brain:
            self.log(f"Area upload belum ditemukan via CSS. Memanggil AI Vision untuk melihat {self.PLATFORM_NAME}...", "WARN")
            v_res = self.consult_vision(page, f"Di mana tombol atau area unggah gambar/flyer pada halaman {self.PLATFORM_NAME} ini?")
            if v_res.get("coordinates_percent"):
                try:
                    self.click_visual_target(page, v_res, step_name=f"{self.domain}_upload_area")
                    time.sleep(1.5)
                    # Coba pasang lagi ke input file
                    page.locator("input[type='file']").first.set_input_files(abs_flyer)
                    file_uploaded = True
                except Exception:
                    pass

        if not file_uploaded:
            self.log(f"Flyer gagal dipasang ke input file {self.PLATFORM_NAME}.", "ERROR")
            return False

        self.log(f"Verifikasi Sesi 1 Sukses: Flyer terpasang di {self.PLATFORM_NAME}.", "SUCCESS")
        return True

    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
        Memasukkan teks judul, keterangan postingan, dan tautan sasaran.
        """
        self.log(f"Mengisi judul dan caption untuk {self.PLATFORM_NAME}...")

        # 1. Isi Judul jika tersedia
        title_selectors = (guide and guide.get("title_input_selectors")) or [
            "input[placeholder*='Title']", "textarea[placeholder*='Title']",
            "input[aria-label*='Title']", "input[name='title']"
        ]
        for sel in title_selectors:
            try:
                tbox = page.locator(sel).first
                if tbox.is_visible(timeout=1500):
                    tbox.click()
                    time.sleep(0.3)
                    tbox.fill(title[:120])
                    time.sleep(1)
                    break
            except Exception:
                continue

        # 2. Isi Caption / Konten Deskripsi
        caption_selectors = (guide and guide.get("caption_input_selectors")) or [
            "div[contenteditable='true']", "textarea", "div[role='textbox']"
        ]
        full_text = f"{title}\n\n{caption}"
        if target_link:
            full_text += f"\n\nLink: {target_link}"

        caption_filled = False
        for sel in caption_selectors:
            try:
                cbox = page.locator(sel).first
                if cbox.is_visible(timeout=2500):
                    cbox.click()
                    time.sleep(0.4)
                    page.keyboard.type(full_text, delay=10)
                    caption_filled = True
                    time.sleep(1.5)
                    break
            except Exception:
                continue

        # 3. Isi Destination Link jika tersedia
        link_selectors = (guide and guide.get("link_input_selectors")) or []
        if target_link and link_selectors:
            for sel in link_selectors:
                try:
                    lbox = page.locator(sel).first
                    if lbox.is_visible(timeout=1500):
                        lbox.fill(target_link)
                        time.sleep(1)
                        break
                except Exception:
                    continue

        self.log(f"Sesi 2 Sukses: Konten dan metadata berhasil diinputkan ke {self.PLATFORM_NAME}.", "SUCCESS")
        return True

    def phase_publish(self, page, guide: Optional[Dict[str, Any]] = None) -> bool:
        """
        Sesi 3: Publish / Kirim
        Menekan tombol kirim atau publikasi postingan.
        """
        self.log(f"Menekan tombol Publish / Post pada {self.PLATFORM_NAME}...")
        submit_selectors = (guide and guide.get("submit_button_selectors")) or [
            "button:has-text('Post')", "button:has-text('Publish')", "button:has-text('Share')",
            "div[role='button']:has-text('Post')", "div[role='button']:has-text('Publish')"
        ]
        submitted = False
        for sel in submit_selectors:
            try:
                btn = page.locator(sel).first
                if btn.is_visible(timeout=2500):
                    btn.click()
                    submitted = True
                    self.log(f"Tombol submit berhasil diklik ({sel}).")
                    time.sleep(6)
                    break
            except Exception:
                continue

        # Vision Fallback jika tombol submit belum tertekan
        if not submitted and self.brain:
            self.log(f"Tombol kirim tidak ditemukan via CSS. Memanggil AI Vision...", "WARN")
            v_res = self.consult_vision(page, f"Cari tombol Post, Kirim, Publish, atau Simpan pada halaman {self.PLATFORM_NAME} ini.")
            if v_res.get("coordinates_percent"):
                submitted = self.click_visual_target(page, v_res, step_name=f"{self.domain}_submit_btn")
                time.sleep(6)

        return submitted

    def phase_extract_link(self, page, title: str, guide: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        """
        Sesi 4: Ekstraksi Tautan Postingan
        Mengambil tautan permalink spesifik dari halaman atau menu share.
        """
        self.log(f"Mendeteksi tautan postingan spesifik pada {self.PLATFORM_NAME}...")
        post_url = None

        # 1. Cek apakah ada tautan tertangkap di clipboard interceptor
        c = self.get_intercepted_clipboard(page)
        if c and c.startswith("http") and self.domain in c:
            post_url = c
            self.log(f"Tautan postingan terdeteksi dari clipboard interceptor: {post_url}", "SUCCESS")

        # 2. Cek selector tautan dari guide
        if not post_url:
            share_guide = (guide and guide.get("share_link_guide")) or {}
            share_selectors = share_guide.get("selectors", [])

            for s_sel in share_selectors:
                try:
                    link_el = page.locator(s_sel).first
                    if link_el.is_visible(timeout=2000):
                        href = link_el.get_attribute("href")
                        if href and href != "#":
                            post_url = href if href.startswith("http") else f"https://{self.domain}" + href
                            self.log(f"Link postingan ditemukan via ({s_sel}): {post_url}", "SUCCESS")
                            break
                        else:
                            # Coba klik tombol share / copy link
                            link_el.click()
                            time.sleep(1.0)
                            copied = self.get_intercepted_clipboard(page)
                            if copied and copied.startswith("http"):
                                post_url = copied
                                self.log(f"Link postingan berhasil disalin via klik ({s_sel}): {post_url}", "SUCCESS")
                                break
                except Exception:
                    continue

        # 3. Cek URL browser saat ini jika berpindah ke halaman postingan spesifik
        if not post_url:
            curr = page.url
            if curr and curr != f"https://{self.domain}/" and "/submit" not in curr and "/create" not in curr:
                post_url = curr
                self.log(f"Tautan terverifikasi dari URL browser: {post_url}", "SUCCESS")

        if not post_url:
            self.log(f"Tautan spesifik tidak dapat diekstraksi pada {self.PLATFORM_NAME}.", "WARN")
            return {
                "success": False,
                "post_url": None,
                "message": f"FAILED: Postingan {self.PLATFORM_NAME} terkirim tapi URL spesifik tidak dapat disalin."
            }

        self.log(f"Selesai! Link postingan {self.PLATFORM_NAME}: {post_url}", "SUCCESS")
        return {
            "success": True,
            "post_url": post_url,
            "message": f"Postingan flyer berhasil dikirimkan di {self.PLATFORM_NAME}!"
        }
