from playwright.sync_api import sync_playwright
import time
import re
from bs4 import BeautifulSoup
from config import PROXY_HOST, PROXY_USER, proxy_password, proxy_port
import random


def get_nonce_with_selenium(site):
    """
    Получает nonce и post_id через Playwright с прокси.
    """
    port = proxy_port()
    proxy_server = f"http://{PROXY_HOST}:{port}"
    print(f"🧪 Используем прокси: {proxy_server}")

    browser = None
    context = None
    try:
        with sync_playwright() as p:
            browser = p.chromium.launch(
                headless=True,
                args=[
                    '--disable-dev-shm-usage',
                    '--no-sandbox',
                    '--disable-gpu',
                    '--single-process',
                ],
                proxy={
                    "server": proxy_server,
                    "username": PROXY_USER,
                    "password": proxy_password()
                }
            )
            context = browser.new_context(
                ignore_https_errors=True,
                user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
            )
            page = context.new_page()

            try:
                # Проверка IP
                try:
                    page.goto("https://httpbin.org/ip", timeout=15000)
                    body = page.locator("body").text_content()
                    print(f"🌐 IP через прокси: {body}")
                except Exception as e:
                    print(f"⚠️ Не удалось проверить IP: {e}")

                # Открываем wp-login
                login_url = getattr(site, "login_url", None) or f"{site.url}/wp-login.php"
                page.goto(login_url, timeout=30000)
                time.sleep(1)

                # Вводим логин/пароль
                page.fill("#user_login", site.wp_login)
                page.fill("#user_pass", site.wp_password)
                page.click("#wp-submit")
                page.wait_for_load_state("networkidle", timeout=15000)

                # Переход в редактор
                post_url = f"{site.url}/wp-admin/post-new.php"
                page.goto(post_url, timeout=30000)
                page.wait_for_load_state("networkidle", timeout=15000)

                # Парсим страницу
                html = page.content()
                soup = BeautifulSoup(html, 'html.parser')

                post_id_input = soup.find("input", {"name": "post_ID"})
                post_id = post_id_input["value"] if post_id_input else None

                nonce_input = soup.find("input", {"name": "_wpnonce"})
                nonce = nonce_input["value"] if nonce_input else None

                # Fallback через regex
                if not nonce:
                    match = re.search(r'"nonce"\s*:\s*"([a-zA-Z0-9]+)"', html)
                    if match:
                        nonce = match.group(1)

                print(f"[PLAYWRIGHT] post_ID: {post_id}")
                print(f"[PLAYWRIGHT] nonce: {nonce}")

                # Получаем cookies и user-agent
                cookies = context.cookies()
                user_agent = page.evaluate("() => navigator.userAgent")

                return {
                    "post_id": post_id,
                    "nonce": nonce,
                    "cookies": cookies,
                    "agent": user_agent
                }

            finally:
                # Гарантированный cleanup внутри with блока
                if context:
                    context.close()
                if browser:
                    browser.close()

    except Exception as e:
        print("[PLAYWRIGHT ERROR]", e)
        return {"post_id": None, "nonce": None, "cookies": [], "agent": None}


def login_cookies_with_selenium(site):
    """
    Войти в WordPress через браузер и вернуть куки сессии и user-agent —
    для последующих обычных HTTP/REST запросов (как у постов). Нужен, когда
    сайт не пускает логин из requests. Возвращает {"cookies", "agent"} или None.
    """
    port = proxy_port()
    proxy_server = f"http://{PROXY_HOST}:{port}"
    login_url = getattr(site, "login_url", None) or f"{site.url}/wp-login.php"

    browser = context = None
    try:
        with sync_playwright() as p:
            browser = p.chromium.launch(
                headless=True,
                args=['--disable-dev-shm-usage', '--no-sandbox', '--disable-gpu', '--single-process'],
                proxy={"server": proxy_server, "username": PROXY_USER, "password": proxy_password()},
            )
            context = browser.new_context(
                ignore_https_errors=True,
                user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
            )
            page = context.new_page()
            try:
                page.goto(login_url, timeout=30000)
                page.fill("#user_login", site.wp_login)
                page.fill("#user_pass", site.wp_password)
                page.click("#wp-submit")
                page.wait_for_load_state("networkidle", timeout=15000)

                # Признак успешного входа — cookie wordpress_logged_in_*.
                cookies = context.cookies()
                if not any(c["name"].startswith("wordpress_logged_in") for c in cookies):
                    print("[PLAYWRIGHT LOGIN] не вижу cookie входа")
                    return None

                return {"cookies": cookies, "agent": page.evaluate("() => navigator.userAgent")}
            finally:
                if context:
                    context.close()
                if browser:
                    browser.close()
    except Exception as e:
        print("[PLAYWRIGHT LOGIN ERROR]", e)
        return None
