import requests
from bs4 import BeautifulSoup

def post_to_site(site, title, content):
    try:
        session = requests.Session()

        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                        'AppleWebKit/537.36 (KHTML, like Gecko) '
                        'Chrome/124.0.0.0 Safari/537.36',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Language': 'en-US,en;q=0.5',
        }
        session.headers.update(headers)

        # Login
        login_page = session.get(f'{site.url}/wp-login.php')
        soup = BeautifulSoup(login_page.text, 'html.parser')
        redirect_input = soup.find('input', {'name': 'redirect_to'})
        redirect_to = redirect_input['value'] if redirect_input else f'{site.url}/wp-admin/'

        login_payload = {
            'log': site.wp_login,
            'pwd': site.wp_password,
            'redirect_to': redirect_to,
            'testcookie': '1'
        }

        login_resp = session.post(f'{site.url}/wp-login.php', data=login_payload)
        if "action=confirm_admin_email" in login_resp.url:
            print("[INFO] Пропускаем подтверждение email")

        # Create draft
        post_new = session.get(f'{site.url}/wp-admin/post-new.php')
        soup = BeautifulSoup(post_new.text, 'html.parser')

        nonce = soup.find('input', {'name': '_wpnonce'})
        post_id = soup.find('input', {'name': 'post_ID'})

        if not nonce or not post_id:
            return False, "Не удалось получить nonce или post_ID"

        nonce_value = nonce['value']
        post_id_value = post_id['value']

        # Update post with content
        post_payload = {
            'post_ID': post_id_value,
            'post_title': title,
            'content': content,
            'excerpt': '',
            'visibility': 'public',
            'action': 'editpost',
            'meta-box-order-nonce': nonce_value,
            'closedpostboxesnonce': nonce_value,
            '_wpnonce': nonce_value,
            '_wp_http_referer': '/wp-admin/post-new.php',
            'post_status': 'publish',
            'original_publish': 'Опубликовать',
            'publish': 'Опубликовать',
            'post_type': 'post'
        }

        post_url = f'{site.url}/wp-admin/post.php'
        post_resp = session.post(post_url, data=post_payload)

        # Try to get pretty permalink
        fallback = f'{site.url}/?p={post_id_value}'
        final = session.get(fallback, allow_redirects=True)
        post_link = final.url

        return True, {
            "url": post_link,
            "post_id": int(post_id_value)
        }

    except Exception as e:
        return False, str(e)
