#!/usr/bin/env python3
"""Retweet cannabis news and updates from reliable sources"""
import asyncio
import json
import os
import random
import re
from datetime import datetime, timezone
from pathlib import Path

os.environ.setdefault("DISPLAY", ":99")

from patchright.async_api import async_playwright

PROFILE_DIR = Path("/workspace/browser_profile/x_headed")
COOKIES_PATH = Path("/workspace/scripts/x_cookies.json")
RETWEET_LOG = Path("/workspace/retweet_log.jsonl")

# Reliable sources to check
GOOD_SOURCES = [
    "ABORFL",           # FL cannabis news
    "LegalizeItFL",     # FL legalization
    "FLCannabisAct",    # FL cannabis act
    "NORMLorg",         # National NORML
    "MarijuanaPolicy",  # MPP
    "FLDispensaries",   # FL dispensary updates
    "TheFloweryFL",     # The Flowery
    "JungleBoysFL",     # Jungle Boys
    "CookiesFL",        # Cookies Florida
    "GoldFlowerFL",     # Gold Flower
    "SunburnCannabis",  # Sunburn
    "Trulieve",         # Trulieve
]

def log_retweet(action, tweet_url, author, text):
    """Log what we retweeted."""
    entry = {
        "timestamp": datetime.now().isoformat(),
        "action": action,
        "tweet_url": tweet_url,
        "author": author,
        "text": text[:150] if text else "",
    }
    with open(RETWEET_LOG, "a") as f:
        f.write(json.dumps(entry) + "\n")
    print(f"📝 Logged: {action} - {author}")

async def inject_cookies(context):
    """Inject X cookies from file."""
    cookies = json.loads(COOKIES_PATH.read_text())
    cookie_list = [
        {"name": k, "value": v, "domain": ".x.com", "path": "/"}
        for k, v in cookies.items()
    ]
    await context.add_cookies(cookie_list)
    print(f"✅ Injected {len(cookie_list)} cookies")

async def perform_retweet(page, tweet_url):
    """Perform the retweet action."""
    try:
        print(f"🔄 Navigating to: {tweet_url}")
        await page.goto(tweet_url, wait_until="domcontentloaded", timeout=15000)
        await asyncio.sleep(3)
        
        # Look for retweet button
        retweet_selectors = [
            '[data-testid="retweet"]',
            '[data-testid="unretweet"]',
            'button[aria-label*="Retweet"]',
            'button[aria-label*="repost"]',
        ]
        
        for selector in retweet_selectors:
            btn = await page.query_selector(selector)
            if btn:
                print(f"🖱️ Found retweet button: {selector}")
                await btn.click()
                await asyncio.sleep(1.5)
                
                # Click "Repost" in the confirmation dialog
                confirm_selectors = [
                    '[data-testid="retweetConfirm"]',
                    'div[role="menuitem"]:has-text("Repost")',
                    'div[role="menuitem"]:has-text("Retweet")',
                ]
                
                for confirm in confirm_selectors:
                    confirm_btn = await page.query_selector(confirm)
                    if confirm_btn:
                        await confirm_btn.click()
                        await asyncio.sleep(2)
                        print("✅ Retweet confirmed")
                        return True
                        
        print("⚠️ Could not complete retweet")
        return False
        
    except Exception as e:
        print(f"❌ Retweet error: {e}")
        return False

async def search_and_retweet():
    """Search for cannabis content and retweet interesting posts."""
    async with async_playwright() as p:
        browser = await p.chromium.launch_persistent_context(
            user_data_dir=str(PROFILE_DIR),
            headless=False,
            args=[
                "--disable-blink-features=AutomationControlled",
                "--disable-web-security",
                "--disable-features=IsolateOrigins,site-per-process",
            ],
            viewport={"width": 1280, "height": 800},
        )
        
        page = browser.pages[0] if browser.pages else await browser.new_page()
        await inject_cookies(browser)
        
        retweeted = 0
        max_retweets = 2
        
        # Try each source
        random.shuffle(GOOD_SOURCES)
        
        for source in GOOD_SOURCES:
            if retweeted >= max_retweets:
                break
                
            print(f"\n🔍 Checking @{source}...")
            
            try:
                # Go to user's profile
                await page.goto(f"https://x.com/{source}", 
                              wait_until="domcontentloaded", timeout=15000)
                await asyncio.sleep(3)
                
                # Get recent tweets
                tweets = await page.query_selector_all('article[data-testid="tweet"]')
                print(f"  Found {len(tweets)} tweets")
                
                for tweet in tweets[:3]:  # Check first 3 tweets
                    if retweeted >= max_retweets:
                        break
                        
                    # Get tweet text
                    text_el = await tweet.query_selector('[data-testid="tweetText"]')
                    if not text_el:
                        continue
                        
                    text = await text_el.inner_text()
                    text_lower = text.lower()
                    
                    # Skip if already retweeted (check for retweet indicator)
                    unretweet_btn = await tweet.query_selector('[data-testid="unretweet"]')
                    if unretweet_btn:
                        print(f"  ⏭️ Already retweeted: {text[:60]}...")
                        continue
                    
                    # Skip replies (start with @)
                    if text.startswith("@"):
                        continue
                    
                    # Look for newsworthy content
                    is_newsworthy = any(kw in text_lower for kw in [
                        "announce", "launch", "new", "update", "legal", 
                        "bill", "vote", "pass", "approve", "sale", "deal",
                        "available", "drop", "strain", "flower", "concentrate"
                    ])
                    
                    # Skip controversial/political opinions
                    skip_terms = ["trump", "biden", "democrat", "republican", 
                                  "liberal", "conservative", "fight", "war"]
                    if any(term in text_lower for term in skip_terms):
                        print(f"  ⏭️ Skipping political: {text[:60]}...")
                        continue
                    
                    if is_newsworthy:
                        print(f"  📰 Found newsworthy tweet: {text[:80]}...")
                        
                        # Get tweet link
                        link_el = await tweet.query_selector('a[href*="/status/"]')
                        if link_el:
                            href = await link_el.get_attribute("href")
                            tweet_url = f"https://x.com{href}"
                            
                            # Perform retweet
                            success = await perform_retweet(page, tweet_url)
                            if success:
                                log_retweet("retweet", tweet_url, source, text)
                                retweeted += 1
                                await asyncio.sleep(5)
                            
            except Exception as e:
                print(f"  ⚠️ Error checking {source}: {e}")
                continue
        
        print(f"\n✅ Done! Retweeted {retweeted} posts")
        await browser.close()
        return retweeted

if __name__ == "__main__":
    print("🌿 Cannabis Retweet Bot Starting...")
    print(f"Sources: {len(GOOD_SOURCES)}")
    count = asyncio.run(search_and_retweet())
    print(f"\n🏁 Complete! Retweeted {count} posts.")
