#!/usr/bin/env python3
"""
Mid-morning Engagement as Sarah (Late 30s Professional)
Runs with virtual display (Xvfb) in Docker container.

Usage:
  # In Docker container canna:
  docker exec -e DISPLAY=:99 canna python3 /workspace/scripts/sarah_engagement.py
"""

import asyncio
import json
import random
import sys
import os
from datetime import datetime
from pathlib import Path

# Ensure display is set for headed mode
if "DISPLAY" not in os.environ:
    os.environ["DISPLAY"] = ":99"

# Add paths for imports
script_dir = Path(__file__).parent
sys.path.append(str(script_dir))

try:
    from patchright.async_api import async_playwright
except ImportError:
    print("ERROR: pip install patchright")
    sys.exit(1)

# Import helper functions from stealth engagement script
import x_stealth_engagement as stealth

# Override VOICE_PROFILE with Sarah's persona
stealth.VOICE_PROFILE = """You are Sarah — mid-30s professional, bubbly, approachable.

SARAH'S VOICE:
- Professional but warm — knows her stuff, not stuffy
- Friendly and social — like texting a colleague
- Experienced — shares genuine insights
- Uses emojis naturally 💚☺️😂
- NO gen-z slang (fr fr, no cap, etc.)

REPLY STYLE:
- Short (under 200 chars ideally, max 280)
- React to what they ACTUALLY said
- Professional but approachable

SARAH EXAMPLES:
- "Ooh I've been curious about that one! Is it more of a daytime or evening strain? ☺️"
- "Cookies has been dropping some solid $30 eighths lately! Worth checking out 💚"
- "Same here! I always end up at Jungle Boys on Fridays but the wait can be brutal 😂"
- "Ugh I totally get that! The 35-day cycle is such a pain. Calendar planning is essential 😅"

BAD REPLIES:
- "fr fr", "no cap", "hits different"
- "We recommend checking our website"
- Corporate jargon
"""

async def search_and_engage(page, query: str, reply_count: int, stats: dict):
    print(f"🔍 Searching for: {query}")
    # X search URL
    search_url = f"https://x.com/search?q={query}&f=live"
    await page.goto(search_url, wait_until="domcontentloaded")
    await asyncio.sleep(4)
    
    # Warm up search results
    await stealth.human_scroll(page, 2)
    
    tweets = await page.locator('[data-testid="tweet"]').all()
    print(f"  Found {len(tweets)} tweets in search results")
    
    replies_this_query = 0
    for i, tweet in enumerate(tweets[:8]): # Look at top 8
        if stats["replies"] >= reply_count or replies_this_query >= 2:
            break
            
        try:
            # Skip if it's our own tweet or an ad
            promoted = await tweet.locator('text=Promoted').count() > 0
            if promoted:
                continue
            
            # Get tweet text and username
            username = ""
            try:
                user_elem = tweet.locator('[data-testid="User-Name"]')
                username = (await user_elem.inner_text()).split('@')[-1].split('\n')[0]
            except:
                pass
            
            if username.lower() == "cannadealsfl":
                continue
                
            tweet_text = ""
            try:
                text_elem = tweet.locator('[data-testid="tweetText"]')
                tweet_text = await text_elem.inner_text()
            except:
                pass
            
            # Like anyway
            like_btn = tweet.locator('[data-testid="like"]')
            if await like_btn.is_visible():
                await like_btn.click()
                stats["likes"] += 1
                await asyncio.sleep(random.uniform(1, 2))
            
            # Reply
            reply_btn = tweet.locator('[data-testid="reply"]')
            if await reply_btn.is_visible():
                await reply_btn.click()
                await asyncio.sleep(random.uniform(2, 3))
                
                reply_text = stealth.generate_smart_reply(tweet_text, username)
                
                textarea = page.locator('[data-testid="tweetTextarea_0"]')
                if await textarea.is_visible():
                    await stealth.human_type(page, '[data-testid="tweetTextarea_0"]', reply_text)
                    await asyncio.sleep(1)
                    
                    submit_btn = page.locator('[data-testid="tweetButton"]')
                    if await submit_btn.is_enabled():
                        await submit_btn.click()
                        await asyncio.sleep(3)
                        
                        # Verify
                        dialog_still_open = await textarea.is_visible()
                        if not dialog_still_open:
                            stats["replies"] += 1
                            replies_this_query += 1
                            stealth.log_action("SARAH_REPLY", f"@{username}: {reply_text[:40]}...")
                            print(f"  ✅ Sarah replied to @{username}")
                        else:
                            await page.keyboard.press("Escape")
                else:
                    await page.keyboard.press("Escape")
        except Exception as e:
            print(f"  Error engaging with tweet: {e}")
            continue

async def main():
    print("💚 Starting Sarah's Mid-Morning Engagement Loop")
    
    stealth.USER_DATA_DIR.mkdir(exist_ok=True)
    
    async with async_playwright() as p:
        context = await p.chromium.launch_persistent_context(
            str(stealth.USER_DATA_DIR),
            headless=False,  # Must use headed mode - headless returns 0 tweets due to X detection
            viewport={"width": 1366, "height": 768},
            args=["--no-sandbox", "--disable-dev-shm-usage"]
        )
        
        page = context.pages[0] if context.pages else await context.new_page()
        stats = {"likes": 0, "replies": 0}
        
        try:
            browser_cookies = stealth.load_cookies_for_browser()
            if browser_cookies:
                await context.add_cookies(browser_cookies)
            
            await page.goto("https://x.com/home", wait_until="domcontentloaded")
            await asyncio.sleep(5)
            
            if "login" in page.url.lower():
                print("❌ Login required.")
                return
            
            # Search Queries from Task
            queries = ["#MMJFlorida", "Florida medical cannabis", "#FLMedicalTrees"]
            random.shuffle(queries)
            
            for q in queries:
                if stats["replies"] >= 3:
                    break
                await search_and_engage(page, q, 3, stats)
                await asyncio.sleep(random.uniform(5, 10))
            
            # Engage with target accounts (FALLBACK if search fails)
            if stats["replies"] < 1:
                print("⚠️ Search yielded no results, trying target accounts fallback...")
                targets = random.sample(stealth.TARGET_ACCOUNTS, min(3, len(stealth.TARGET_ACCOUNTS)))
                for username in targets:
                    print(f"👤 Engaging with @{username}...")
                    await page.goto(f"https://x.com/{username}", wait_until="domcontentloaded")
                    await asyncio.sleep(4)
                    await stealth.human_scroll(page, 2)
                    tweets = await page.locator('[data-testid="tweet"]').all()
                    for i, tweet in enumerate(tweets[:3]):
                        if stats["replies"] >= 3: break
                        try:
                            # Skip ads and own
                            if await tweet.locator('text=Promoted').count() > 0: continue
                            
                            # Get tweet text
                            tweet_text = ""
                            try:
                                text_elem = tweet.locator('[data-testid="tweetText"]')
                                tweet_text = await text_elem.inner_text()
                            except: pass

                            # Like
                            like_btn = tweet.locator('[data-testid="like"]')
                            if await like_btn.is_visible():
                                await like_btn.click()
                                stats["likes"] += 1
                                await asyncio.sleep(1)

                            # Reply (1 per target)
                            if i == 0:
                                reply_btn = tweet.locator('[data-testid="reply"]')
                                if await reply_btn.is_visible():
                                    await reply_btn.click()
                                    await asyncio.sleep(2)
                                    reply_text = stealth.generate_smart_reply(tweet_text, username)
                                    textarea = page.locator('[data-testid="tweetTextarea_0"]')
                                    if await textarea.is_visible():
                                        await stealth.human_type(page, '[data-testid="tweetTextarea_0"]', reply_text)
                                        await asyncio.sleep(1)
                                        submit_btn = page.locator('[data-testid="tweetButton"]')
                                        if await submit_btn.is_enabled():
                                            await submit_btn.click()
                                            await asyncio.sleep(3)
                                            if not await textarea.is_visible():
                                                stats["replies"] += 1
                                                stealth.log_action("SARAH_REPLY_FALLBACK", f"@{username}: {reply_text[:40]}...")
                                                print(f"  ✅ Sarah replied to @{username}")
                                            else:
                                                await page.keyboard.press("Escape")
                                    else:
                                        await page.keyboard.press("Escape")
                        except Exception as e:
                            print(f"  Error: {e}")
                            continue

            print(f"\n✨ Done! Likes: {stats['likes']}, Replies: {stats['replies']}")
            
        except Exception as e:
            print(f"Critical Error: {e}")
        finally:
            await context.close()

if __name__ == "__main__":
    asyncio.run(main())
