#!/usr/bin/env python3
"""Retweet cannabis news using twikit (API-based, no browser)"""

import asyncio
import json
import random
import sys
from datetime import datetime
from pathlib import Path
from typing import List, Optional

try:
    from twikit import Client
except ImportError:
    print("ERROR: pip install twikit")
    sys.exit(1)

COOKIES_PATH = Path(__file__).parent / "x_cookies.json"
RETWEET_LOG = Path(__file__).parent / "retweet_log.jsonl"

# Reliable sources to check for retweets
GOOD_SOURCES = [
    "ABORFL",           # FL cannabis news
    "LegalizeItFL",     # FL legalization
    "FLCannabisAct",    # FL cannabis act
    "NORMLorg",         # National NORML
    "MarijuanaPolicy",  # MPP
    "TheFloweryFL",     # The Flowery
    "JungleBoysFL",     # Jungle Boys
    "CookiesFlorida",   # Cookies Florida
    "GoldFlowerFL",     # Gold Flower
    "SunburnCannabis",  # Sunburn
    "Trulieve",         # Trulieve
    "MUV_FL",           # MUV
    "FLCannabis",       # FL Cannabis Coalition
    "FloridaMMTC",      # FL MMTC
]

# Search terms for finding shareable content
SEARCH_QUERIES = [
    "Florida cannabis news",
    "FL medical marijuana",
    "cannabis legalization",
    "dispensary deal Florida",
    "new strain drop",
]


def log_retweet(action: str, tweet_url: str, author: str, text: str = ""):
    """Log retweet activity."""
    entry = {
        "timestamp": datetime.now().isoformat(),
        "action": action,
        "tweet_url": tweet_url,
        "author": author,
        "text": text[:100] if text else "",
    }
    with open(RETWEET_LOG, "a") as f:
        f.write(json.dumps(entry) + "\n")
    print(f"📝 Logged: {action} by @{author}")


async def get_client() -> Client:
    """Initialize twikit client with cookies."""
    if not COOKIES_PATH.exists():
        raise FileNotFoundError(f"Cookies not found: {COOKIES_PATH}")
    
    cookies = json.loads(COOKIES_PATH.read_text())
    client = Client('en-US')
    client.set_cookies({
        'auth_token': cookies.get('auth_token'),
        'ct0': cookies.get('ct0'),
    })
    return client


async def check_source_for_retweets(client: Client, username: str, max_retweets: int = 2) -> int:
    """Check a source for retweetable content."""
    retweeted = 0
    
    try:
        print(f"\n🔍 Checking @{username}...")
        
        user = await client.get_user_by_screen_name(username)
        if not user:
            print(f"  ⚠️ Could not find user @{username}")
            return 0
        
        # Get recent tweets
        tweets = await user.get_tweets('Tweets', count=5)
        if not tweets:
            print(f"  No tweets found")
            return 0
        
        print(f"  Found {len(list(tweets))} tweets")
        
        for tweet in tweets[:3]:  # Check first 3 tweets
            # Skip replies (start with @)
            if tweet.text.startswith("@"):
                continue
            
            # Skip if already retweeted
            if hasattr(tweet, 'retweeted') and tweet.retweeted:
                print(f"  ⏭️ Already retweeted: {tweet.text[:60]}...")
                continue
            
            text_lower = tweet.text.lower()
            
            # Skip controversial/political content
            skip_terms = ["trump", "biden", "democrat", "republican", 
                         "liberal", "conservative", "fight", "war", "election"]
            if any(term in text_lower for term in skip_terms):
                print(f"  ⏭️ Skipping political: {tweet.text[:60]}...")
                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",
                "now open", "coming soon", "exclusive", "limited"
            ])
            
            if is_newsworthy:
                print(f"  📰 Newsworthy: {tweet.text[:80]}...")
                
                try:
                    # Perform retweet
                    await client.retweet(tweet.id)
                    tweet_url = f"https://x.com/{username}/status/{tweet.id}"
                    log_retweet("retweet", tweet_url, username, tweet.text)
                    print(f"  ✅ RETWEETED!")
                    retweeted += 1
                    
                    if retweeted >= max_retweets:
                        break
                    
                    await asyncio.sleep(random.uniform(3, 6))
                    
                except Exception as e:
                    print(f"  ❌ Retweet failed: {e}")
                    continue
        
    except Exception as e:
        print(f"  ⚠️ Error checking @{username}: {e}")
    
    return retweeted


async def search_and_retweet(client: Client, query: str, max_retweets: int = 2) -> int:
    """Search for tweets and retweet relevant ones."""
    retweeted = 0
    
    try:
        print(f"\n🔍 Searching: '{query}'...")
        
        tweets = await client.search_tweet(query, 'Top', count=10)
        if not tweets:
            print(f"  No tweets found")
            return 0
        
        print(f"  Found {len(list(tweets))} tweets")
        
        for tweet in tweets[:5]:
            # Skip replies
            if tweet.text.startswith("@"):
                continue
            
            # Skip if already retweeted
            if hasattr(tweet, 'retweeted') and tweet.retweeted:
                continue
            
            text_lower = tweet.text.lower()
            
            # Skip controversial content
            skip_terms = ["trump", "biden", "democrat", "republican", 
                         "liberal", "conservative"]
            if any(term in text_lower for term in skip_terms):
                continue
            
            # Check if from a good source or has good engagement
            is_good_source = tweet.user.name in GOOD_SOURCES or tweet.user.screen_name in GOOD_SOURCES
            has_engagement = tweet.favorite_count > 10 or tweet.retweet_count > 5
            
            if is_good_source or has_engagement:
                # Check for news value
                is_newsworthy = any(kw in text_lower for kw in [
                    "news", "update", "announce", "new", "launch",
                    "legal", "bill", "pass", "approve", "deal", "sale"
                ])
                
                if is_newsworthy:
                    print(f"  📰 Found: @{tweet.user.screen_name}: {tweet.text[:80]}...")
                    
                    try:
                        await client.retweet(tweet.id)
                        tweet_url = f"https://x.com/{tweet.user.screen_name}/status/{tweet.id}"
                        log_retweet("retweet_search", tweet_url, tweet.user.screen_name, tweet.text)
                        print(f"  ✅ RETWEETED!")
                        retweeted += 1
                        
                        if retweeted >= max_retweets:
                            break
                        
                        await asyncio.sleep(random.uniform(3, 6))
                        
                    except Exception as e:
                        print(f"  ❌ Failed: {e}")
                        continue
    
    except Exception as e:
        print(f"  ⚠️ Search error: {e}")
    
    return retweeted


async def main():
    """Main retweet routine."""
    print("🌿 Cannabis Retweet Bot Starting...")
    print(f"Sources: {len(GOOD_SOURCES)}")
    print("=" * 50)
    
    try:
        client = await get_client()
        print("✅ Connected to X")
    except Exception as e:
        print(f"❌ Failed to connect: {e}")
        sys.exit(1)
    
    total_retweeted = 0
    max_total = 2  # Max retweets per session
    
    # Shuffle sources for variety
    random.shuffle(GOOD_SOURCES)
    
    # Check priority sources
    for source in GOOD_SOURCES[:6]:
        if total_retweeted >= max_total:
            break
        
        count = await check_source_for_retweets(client, source, max_total - total_retweeted)
        total_retweeted += count
        
        await asyncio.sleep(random.uniform(2, 4))
    
    # If we haven't found enough, try search
    if total_retweeted < max_total:
        query = random.choice(SEARCH_QUERIES)
        count = await search_and_retweet(client, query, max_total - total_retweeted)
        total_retweeted += count
    
    print("\n" + "=" * 50)
    print(f"🏁 Done! Retweeted {total_retweeted} posts")
    print("=" * 50)
    
    return total_retweeted


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