from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
import time
import os


class Messenger:
    def __init__(self, headless=False):
        self.driver = None
        self.headless = headless

    def _init_driver(self):
        if self.driver is None:
            options = Options()
            if self.headless:
                options.add_argument("--headless")
            options.add_argument("--disable-notifications")
            options.add_experimental_option("excludeSwitches", ["enable-logging"])
            self.driver = webdriver.Chrome(
                service=Service(ChromeDriverManager().install()), options=options
            )

    def send_whatsapp(self, phone, message):
        try:
            self._init_driver()
            self.driver.get(
                f"https://web.whatsapp.com/send?phone={phone}&text={message}"
            )
            time.sleep(15)
            send_btn = WebDriverWait(self.driver, 20).until(
                EC.element_to_be_clickable((By.XPATH, '//button[@data-tab="10"]'))
            )
            send_btn.click()
            return f"Message sent to WhatsApp: {phone}"
        except Exception as e:
            return f"Failed to send WhatsApp message: {str(e)}"

    def send_telegram(self, chat_id, message, bot_token=None):
        bot_token = bot_token or os.getenv("TELEGRAM_BOT_TOKEN")
        if not bot_token:
            return "Telegram bot token not configured. Set TELEGRAM_BOT_TOKEN in .env"

        import requests

        url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
        data = {"chat_id": chat_id, "text": message}
        response = requests.post(url, data=data)
        if response.ok:
            return f"Message sent to Telegram: {chat_id}"
        return f"Failed to send Telegram message: {response.text}"

    def send_discord(self, webhook_url, message):
        import requests

        data = {"content": message}
        response = requests.post(webhook_url, json=data)
        if response.status_code == 204:
            return "Message sent to Discord"
        return f"Failed to send Discord message: {response.status_code}"

    def send_slack(self, channel, message, webhook_url=None):
        webhook_url = webhook_url or os.getenv("SLACK_WEBHOOK_URL")
        if not webhook_url:
            return "Slack webhook not configured. Set SLACK_WEBHOOK_URL in .env"

        import requests

        data = {"channel": channel, "text": message}
        response = requests.post(webhook_url, json=data)
        if response.ok:
            return f"Message sent to Slack channel: {channel}"
        return f"Failed to send Slack message: {response.status_code}"

    def send_gmail(self, to_email, subject, body):
        from skills.email import Email

        email = Email()
        return email.send(to_email, subject, body)

    def close(self):
        if self.driver:
            self.driver.quit()
            self.driver = None
