"""
SiliconBridge + Selenium integration.

Intercepts human-required steps (OTP, KYC, approval, GMB) during
Selenium browser automation.  Zero extra cost — just pip install siliconbridge.

Usage:
    from selenium import webdriver
    from siliconbridge.integrations.selenium_bridge import SeleniumBridge

    driver = webdriver.Chrome()
    sb = SeleniumBridge(api_key="sb_...", driver=driver)

    # When your agent hits a 2FA wall
    code = sb.request_otp(phone="+15551234567")
    driver.find_element(By.ID, "otp-input").send_keys(code)

    # Take a screenshot of whatever the agent is stuck on, send to human
    answer = sb.screenshot_and_solve(instructions="Type the code you see")
"""

import base64
import tempfile
from typing import Optional, Dict, Any

from siliconbridge.client import SiliconBridge


class SeleniumBridge:
    """Wraps SiliconBridge SDK for use inside Selenium automation."""

    def __init__(self, api_key: str, driver=None, base_url: str = None, timeout: int = 300):
        self.sb = SiliconBridge(api_key=api_key, base_url=base_url)
        self.driver = driver
        self.timeout = timeout

    def set_driver(self, driver):
        """Attach or swap the Selenium WebDriver instance."""
        self.driver = driver

    # ── Screenshot-based solving ──────────────────────────────────

    def screenshot_and_solve(
        self,
        instructions: str = "Solve what you see in this screenshot",
        service_type: str = "captcha",
        timeout: int = None,
    ) -> str:
        """
        Capture the current browser viewport, send to a human operator,
        and return the typed answer.
        """
        png_bytes = self.driver.get_screenshot_as_png()
        b64 = base64.b64encode(png_bytes).decode("utf-8")
        task = self.sb.submit_task(
            service_type,
            {"image_data": f"data:image/png;base64,{b64}", "instructions": instructions},
        )
        result = self.sb.wait_for_result(task["task_id"], timeout=timeout or self.timeout)
        return result.get("result", {}).get("solution", "")

    def screenshot_element_and_solve(
        self,
        element,
        instructions: str = "Solve what you see",
        service_type: str = "captcha",
        timeout: int = None,
    ) -> str:
        """Screenshot a specific WebElement and send to human."""
        png_bytes = element.screenshot_as_png
        b64 = base64.b64encode(png_bytes).decode("utf-8")
        task = self.sb.submit_task(
            service_type,
            {"image_data": f"data:image/png;base64,{b64}", "instructions": instructions},
        )
        result = self.sb.wait_for_result(task["task_id"], timeout=timeout or self.timeout)
        return result.get("result", {}).get("solution", "")

    # ── OTP / 2FA ─────────────────────────────────────────────────

    def request_otp(
        self,
        phone: str = None,
        email: str = None,
        instructions: str = "Enter the OTP/2FA code",
        timeout: int = None,
    ) -> str:
        """Ask a human operator to relay an OTP or 2FA code."""
        payload: Dict[str, Any] = {"instructions": instructions}
        if phone:
            payload["phone"] = phone
        if email:
            payload["email"] = email
        # Also attach a screenshot of the current page for context
        if self.driver:
            png_bytes = self.driver.get_screenshot_as_png()
            payload["screenshot"] = base64.b64encode(png_bytes).decode("utf-8")
        task = self.sb.submit_task("otp", payload)
        result = self.sb.wait_for_result(task["task_id"], timeout=timeout or self.timeout)
        return result.get("result", {}).get("solution", "")

    # ── Human Approval Gate ───────────────────────────────────────

    def request_approval(
        self,
        action_description: str,
        context: Dict[str, Any] = None,
        timeout: int = None,
    ) -> bool:
        """
        Ask a human operator to approve or deny an action.
        Returns True if approved, False if denied.
        """
        payload = {"instructions": action_description}
        if context:
            payload.update(context)
        if self.driver:
            png_bytes = self.driver.get_screenshot_as_png()
            payload["screenshot"] = base64.b64encode(png_bytes).decode("utf-8")
        task = self.sb.submit_task("approval", payload)
        result = self.sb.wait_for_result(task["task_id"], timeout=timeout or self.timeout)
        return result.get("result", {}).get("approved", False)

    # ── KYC / Identity ────────────────────────────────────────────

    def request_kyc_review(
        self,
        document_urls: Dict[str, str],
        personal_info: Dict[str, str] = None,
        timeout: int = None,
    ) -> Dict:
        """
        Submit identity documents for human KYC review.

        Args:
            document_urls: e.g. {"id_front": "https://...", "selfie": "https://..."}
            personal_info: e.g. {"name": "John Doe", "dob": "1990-01-15"}
        """
        payload = {**document_urls}
        if personal_info:
            payload["personal_info"] = personal_info
        task = self.sb.submit_task("kyc_verification", payload)
        result = self.sb.wait_for_result(task["task_id"], timeout=timeout or self.timeout)
        return result.get("result", {})

    # ── Cleanup ───────────────────────────────────────────────────

    def close(self):
        self.sb.close()

    def __enter__(self):
        return self

    def __exit__(self, *args):
        self.close()
