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

class InstagramHandler(BasePlatformHandler):
    PLATFORM_NAME = "Instagram"
    BASE_URL = "https://www.instagram.com/"

    def phase_upload(self, page, flyer_path: str, guide: Optional[Dict[str, Any]] = None) -> bool:
        """
        Sesi 1: Upload Media
        Membuka Instagram, menekan tombol Buat/Create, mengunggah file flyer,
        dan melewati layar Crop & Filter.
        """
        upload_url = (guide and guide.get("direct_upload_url")) or self.BASE_URL
        self.log(f"Membuka Instagram ({upload_url})...")
        page.goto(upload_url, wait_until="domcontentloaded", timeout=45000)
        time.sleep(3)
        self.dismiss_common_modals(page)
        self.setup_clipboard_interceptor(page)

        # Cek apakah butuh login / 2FA menggunakan validator universal
        if self.check_login_required(page, guide):
            self.log("Instagram membutuhkan login atau verifikasi 2FA. Silakan login di Chrome Bot!", "ERROR")
            return False

        # 1. Klik tombol Buat / Create (+) di sidebar
        self.log("Mencari tombol Buat / Create (+)...")
        create_selectors = [
            "svg[aria-label='New post']",
            "svg[aria-label='Postingan baru']",
            "span:has-text('Create')",
            "span:has-text('Buat')",
            "a[href='#']:has-text('Create')",
            "div[role='button']:has-text('Create')"
        ]
        opened = False
        for sel in create_selectors:
            try:
                el = page.locator(sel).first
                if el.is_visible(timeout=1500):
                    el.click()
                    opened = True
                    break
            except Exception:
                continue

        # Vision Fallback jika tombol Create tidak ditemukan
        if not opened and self.brain:
            self.log("Tombol Create tidak ditemukan via CSS. Memanggil AI Vision...", "WARN")
            v_res = self.consult_vision(page, "Cari tombol Buat atau icon '+' untuk membuat postingan baru di sidebar Instagram.")
            if v_res.get("coordinates_percent"):
                opened = self.click_visual_target(page, v_res, step_name="instagram_create_btn")

        time.sleep(2)

        # 2. Upload file flyer (prioritaskan DOM input file tanpa memicu OS dialog)
        self.log("Mengunggah file flyer ke Instagram...")
        abs_flyer = os.path.abspath(flyer_path)
        file_uploaded = False
        try:
            file_input = page.locator("input[type='file']").first
            file_input.set_input_files(abs_flyer, timeout=4000)
            file_uploaded = True
            time.sleep(2)
        except Exception:
            select_btn = page.locator("button:has-text('Select from computer'), button:has-text('Pilih dari komputer')").first
            if select_btn.is_visible(timeout=2000):
                try:
                    select_btn.click()
                    time.sleep(1)
                    page.locator("input[type='file']").first.set_input_files(abs_flyer)
                    file_uploaded = True
                    time.sleep(2)
                except Exception:
                    pass

        if not file_uploaded:
            try:
                all_inputs = page.locator("input[type='file']").all()
                for inp in all_inputs:
                    try:
                        inp.set_input_files(abs_flyer)
                        file_uploaded = True
                        break
                    except Exception:
                        continue
            except Exception:
                pass

        modal = page.locator("div[role='dialog']").first

        # 3. Next button 1 (Crop -> Filter)
        self.log("Navigasi tahap pemotongan (Next 1)...")
        time.sleep(1.5)
        next_btn = modal.locator("div[role='button']:has-text('Next'), button:has-text('Next'), div[role='button']:has-text('Selanjutnya')").first
        if not next_btn.is_visible(timeout=2000):
            next_btn = page.locator("div[role='button']:has-text('Next'), button:has-text('Next'), div[role='button']:has-text('Selanjutnya')").first

        if next_btn.is_visible(timeout=3000):
            next_btn.click()
            time.sleep(2)
        elif self.brain:
            v_res = self.consult_vision(page, "Cari tombol Next atau Selanjutnya berwarna biru di sudut kanan atas dialog Instagram.")
            if v_res.get("coordinates_percent"):
                self.click_visual_target(page, v_res, step_name="instagram_next_crop")
                time.sleep(2)

        # 4. Next button 2 (Filter -> Caption)
        self.log("Navigasi tahap filter (Next 2)...")
        next_btn2 = modal.locator("div[role='button']:has-text('Next'), button:has-text('Next'), div[role='button']:has-text('Selanjutnya')").first
        if not next_btn2.is_visible(timeout=2000):
            next_btn2 = page.locator("div[role='button']:has-text('Next'), button:has-text('Next'), div[role='button']:has-text('Selanjutnya')").first

        if next_btn2.is_visible(timeout=3000):
            next_btn2.click()
            time.sleep(2)
        elif self.brain:
            v_res = self.consult_vision(page, "Cari tombol Next atau Selanjutnya kedua di sudut kanan atas dialog Instagram.")
            if v_res.get("coordinates_percent"):
                self.click_visual_target(page, v_res, step_name="instagram_next_filter")
                time.sleep(2)

        # Verifikasi: Kotak caption atau form posting siap
        caption_box = modal.locator("div[aria-label*='caption' i], div[aria-label*='keterangan' i], div[contenteditable='true']").first
        if not caption_box.is_visible(timeout=3000):
            caption_box = page.locator("div[aria-label*='caption' i], div[aria-label*='keterangan' i], div[contenteditable='true']").first

        ready = caption_box.is_visible(timeout=3000)
        if ready:
            self.log("Sesi 1 (Upload Media) Instagram terverifikasi sukses!", "SUCCESS")
        return 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 keterangan/caption pada Instagram.
        """
        self.log("Mengisi teks caption Instagram...")
        full_caption = f"{title}\n\n{caption}"
        if target_link:
            full_caption += f"\n\nLink: {target_link}"

        modal = page.locator("div[role='dialog']").first
        caption_box = modal.locator("div[aria-label*='caption' i], div[aria-label*='keterangan' i], div[contenteditable='true']").first
        if not caption_box.is_visible(timeout=2000):
            caption_box = page.locator("div[aria-label*='caption' i], div[aria-label*='keterangan' i], div[contenteditable='true']").first

        if caption_box.is_visible(timeout=3000):
            caption_box.click()
            time.sleep(0.5)
            try:
                page.keyboard.insert_text(full_caption)
            except Exception:
                page.keyboard.type(full_caption, delay=10)
            time.sleep(1.5)
            self.log("Caption berhasil dimasukkan ke form.", "SUCCESS")
            return True
        elif self.brain:
            v_res = self.consult_vision(page, "Cari kotak teks 'Write a caption' atau 'Tulis keterangan' di dialog Instagram.")
            if v_res.get("coordinates_percent"):
                self.click_visual_target(page, v_res, step_name="instagram_caption_box")
                time.sleep(0.5)
                page.keyboard.insert_text(full_caption)
                return True

        return False

    def phase_publish(self, page, guide: Optional[Dict[str, Any]] = None) -> bool:
        """
        Sesi 3: Publish
        Menekan tombol Bagikan / Share dan menunggu dialog konfirmasi selesai.
        """
        self.log("Menekan tombol Bagikan / Share Instagram...")
        modal = page.locator("div[role='dialog']").first
        share_btn = modal.locator("div[role='button']:has-text('Share'), button:has-text('Share'), div[role='button']:has-text('Bagikan')").first
        if not share_btn.is_visible(timeout=2000):
            share_btn = page.locator("div[role='button']:has-text('Share'), button:has-text('Share'), div[role='button']:has-text('Bagikan')").first

        shared = False
        if share_btn.is_visible(timeout=3000):
            share_btn.click()
            shared = True
            self.log("Tombol Share berhasil ditekan. Menunggu proses server...")
        elif self.brain:
            v_res = self.consult_vision(page, "Cari tombol Share atau Bagikan berwarna biru di sudut kanan dialog Instagram.")
            if v_res.get("coordinates_percent"):
                shared = self.click_visual_target(page, v_res, step_name="instagram_share_btn")

        if not shared:
            return False

        # Menunggu konfirmasi posting berhasil (hingga 20 detik)
        self.log("Menunggu respon konfirmasi upload...")
        start_wait = time.time()
        while time.time() - start_wait < 20:
            # Cek teks sukses
            if page.locator("span:has-text('Your post has been shared'), span:has-text('Postingan Anda telah dibagikan')").first.is_visible(timeout=500):
                self.log("Konfirmasi sukses: Postingan telah dibagikan!", "SUCCESS")
                return True
            # Cek jika dialog tertutup otomatis
            if not page.locator("div[role='dialog']").first.is_visible(timeout=500):
                self.log("Dialog upload telah tertutup otomatis.", "SUCCESS")
                return True
            time.sleep(1.5)

        return True

    def phase_extract_link(self, page, title: str, guide: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        """
        Sesi 4: Ekstraksi Tautan
        1. Cek tombol Copy Link / Salin tautan di dialog sukses.
        2. Cek URL browser langsung.
        3. Navigasi ke profil akun sendiri, ambil postingan paling kiri atas di grid, dan salin URL-nya.
        """
        post_url = None

        # 0. Cek apakah link sudah tersimpan di clipboard interceptor
        c = self.get_intercepted_clipboard(page)
        if c and ("/p/" in c or "/reel/" in c):
            post_url = c
            self.log(f"Tautan postingan terdeteksi dari clipboard interceptor: {post_url}", "SUCCESS")

        # 1. Cek tombol atau tautan langsung di dialog konfirmasi
        if not post_url:
            try:
                # Cek tautan View Post di dialog
                vp = page.locator("div[role='dialog'] a[href*='/p/'], div[role='dialog'] a[href*='/reel/']").first
                if vp.is_visible(timeout=1000):
                    h = vp.get_attribute("href")
                    if h:
                        post_url = h if h.startswith("http") else f"https://www.instagram.com{h}"
                        self.log(f"Tautan View post langsung terdeteksi: {post_url}", "SUCCESS")
            except Exception:
                pass

        # Coba klik 'Copy link' / 'Salin tautan' di dialog konfirmasi
        if not post_url:
            try:
                copy_btn = page.locator("div[role='dialog'] div[role='button']:has-text('Copy link'), div[role='dialog'] button:has-text('Copy link'), div[role='dialog'] div[role='button']:has-text('Salin tautan'), div[role='dialog'] button:has-text('Salin tautan')").first
                if copy_btn.is_visible(timeout=1500):
                    copy_btn.click()
                    time.sleep(1.0)
                    copied = self.get_intercepted_clipboard(page)
                    if not copied:
                        try:
                            copied = page.evaluate("() => navigator.clipboard.readText()")
                        except Exception:
                            pass
                    if copied and ("/p/" in copied or "/reel/" in copied):
                        post_url = copied
                        self.log(f"Tautan berhasil disalin via tombol Copy link dialog: {post_url}", "SUCCESS")
            except Exception:
                pass

        # Tutup dialog jika masih terbuka
        try:
            page.keyboard.press("Escape")
            time.sleep(1)
        except Exception:
            pass

        # 2. Cek URL browser
        if not post_url and ("/p/" in page.url or "/reel/" in page.url):
            post_url = page.url
            self.log(f"URL browser mengarah ke postingan: {post_url}", "SUCCESS")

        # 3. Navigasi ke profil sendiri untuk mengambil postingan teratas paling kiri
        if not post_url:
            self.log("Membuka profil akun sendiri untuk mengambil postingan teratas paling kiri...")
            prof_clicked = False
            prof_triggers = [
                "a:has-text('Profile')",
                "a:has-text('Profil')",
                "a[href^='/'][role='link']:has(svg[aria-label*='Profil'])",
                "a[href^='/'][role='link']:has(svg[aria-label*='Profile'])",
                "a[href^='/'][role='link']:has(img)"
            ]
            for pt in prof_triggers:
                try:
                    p_el = page.locator(pt).first
                    if p_el.is_visible(timeout=1500):
                        p_el.click()
                        prof_clicked = True
                        time.sleep(3)
                        break
                except Exception:
                    continue

            # Vision Fallback jika menu profil tidak ditemukan
            if not prof_clicked and self.brain:
                v_res = self.consult_vision(page, "Cari tombol menu Profil di sidebar kiri Instagram.")
                if v_res.get("coordinates_percent"):
                    self.click_visual_target(page, v_res, step_name="instagram_profile_nav")
                    time.sleep(3)

            # Cari postingan paling kiri atas di grid profil
            try:
                top_post = page.locator("main article a[href*='/p/'], main article a[href*='/reel/'], main div[style*='grid'] a[href*='/p/'], div[role='tabpanel'] a[href*='/p/'], a[href*='/p/'], a[href*='/reel/']").first
                if top_post.is_visible(timeout=3500):
                    href = top_post.get_attribute("href")
                    if href and ("/p/" in href or "/reel/" in href):
                        post_url = href if href.startswith("http") else f"https://www.instagram.com{href}"
                        self.log(f"Tautan postingan paling kiri di profil terverifikasi: {post_url}", "SUCCESS")
                    else:
                        top_post.click()
                        time.sleep(2)
                        if "/p/" in page.url or "/reel/" in page.url:
                            post_url = page.url
                            self.log(f"Postingan teratas dibuka & URL disalin: {post_url}", "SUCCESS")
            except Exception as te:
                self.log(f"Selector postingan profil: {te}", "WARN")

            # Vision Fallback untuk postingan paling kiri di grid
            if not post_url and self.brain:
                v_res = self.consult_vision(page, "Cari foto atau postingan paling kiri atas pada grid profil Instagram ini. Tunjukkan titik tengahnya.")
                if v_res.get("coordinates_percent"):
                    self.click_visual_target(page, v_res, step_name="instagram_top_left_post")
                    time.sleep(2)
                    if "/p/" in page.url or "/reel/" in page.url:
                        post_url = page.url
                        self.log(f"Postingan berhasil diklik via AI Vision! URL: {post_url}", "SUCCESS")

        if not post_url or ("/p/" not in post_url and "/reel/" not in post_url):
            self.log("Gagal menemukan tautan postingan spesifik (/p/... atau /reel/...). Tidak mencatat tautan palsu.", "ERROR")
            return {
                "success": False,
                "post_url": None,
                "message": "FAILED: Postingan terkirim tapi tautan spesifik (/p/...) tidak dapat diverifikasi."
            }

        self.log(f"Posting Instagram sukses & terverifikasi! Tautan: {post_url}", "SUCCESS")
        return {
            "success": True,
            "post_url": post_url,
            "message": "Postingan flyer berhasil dibagikan & dicatat di Instagram!"
        }
