#!/usr/bin/env python3
"""X Engagement Script using twikit - Targeted approach (no search API)"""

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"
LOG_PATH = Path(__file__).parent.parent.parent.parent / "PROGRESS-LOG.md"

# Target accounts to engage with (FL cannabis space - VERIFIED)
TARGET_ACCOUNTS = [
    "Trulieve",           # 41K followers
    "MUV_FL",             # 4.8K followers
    "TheFloweryFL",       # 6.1K followers
    "GrowHealthyFL",      # 4.1K followers
    "SunburnCannabis",    # 1.7K followers
    "FLCannabis",         # 1K followers
    "FloridaMMTC",        # 731 followers
    "JungleBoysFL",       # Small but relevant
]

# Reply variations - always personalize based on tweet content
REPLY_STARTERS = [
    "Good info here —",
    "Appreciate this!",
    "Been wondering about this.",
    "Thanks for sharing.",
    "This is helpful 🙌",
]


def log_action(action: str, details: str = "") -> None:
    """Log to progress file and console."""
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    print(f"[{timestamp}] {action}: {details}", flush=True)
    
    try:
        content = LOG_PATH.read_text() if LOG_PATH.exists() else "# PROGRESS-LOG.md\n\n"
        today = datetime.now().strftime("%Y-%m-%d")
        
        if f"### {today}" not in content:
            content += f"\n### {today}\n| Time | Action | Details |\n|------|--------|--------|\n"
        
        content += f"| {timestamp} | {action} | {details} |\n"
        LOG_PATH.write_text(content)
    except Exception as e:
        print(f"Log failed: {e}", flush=True)


async def get_client() -> Client:
    """Initialize twikit client."""
    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 get_user_tweets(client: Client, username: str, count: int = 5) -> List:
    """Get recent tweets from a user."""
    try:
        user = await client.get_user_by_screen_name(username)
        if not user:
            return []
        tweets = await user.get_tweets('Tweets', count=count)
        return list(tweets) if tweets else []
    except Exception as e:
        print(f"Could not get tweets for @{username}: {e}", flush=True)
        return []


async def like_tweet(client: Client, tweet_id: str) -> bool:
    """Like a tweet."""
    try:
        await client.favorite_tweet(tweet_id)
        return True
    except Exception as e:
        print(f"Like failed: {e}", flush=True)
        return False


async def reply_to_tweet(client: Client, tweet_id: str, text: str) -> bool:
    """Reply to a tweet."""
    try:
        await client.create_tweet(text=text, reply_to=tweet_id)
        return True
    except Exception as e:
        print(f"Reply failed: {e}", flush=True)
        return False


async def follow_user(client: Client, user_id: str) -> bool:
    """Follow a user."""
    try:
        await client.follow_user(user_id)
        return True
    except Exception as e:
        print(f"Follow failed: {e}", flush=True)
        return False


def generate_reply(tweet_text: str) -> str:
    """Generate a contextual reply."""
    starter = random.choice(REPLY_STARTERS)
    
    tweet_lower = tweet_text.lower()
    
    # Context-aware additions
    if any(w in tweet_lower for w in ["deal", "sale", "discount", "%"]):
        addition = "Been tracking prices and this is solid."
    elif any(w in tweet_lower for w in ["flower", "strain", "bud"]):
        addition = "Quality matters most. Good to see updates."
    elif any(w in tweet_lower for w in ["law", "legal", "bill", "legislature"]):
        addition = "Progress is progress 🙏"
    elif any(w in tweet_lower for w in ["dispensary", "dispo"]):
        addition = "The FL market keeps growing."
    else:
        addition = "FL patients need more of this."
    
    return f"{starter} {addition}"


async def run_engagement_round(
    like_count: int = 5,
    reply_count: int = 2,
    follow_count: int = 2
) -> dict:
    """Run targeted engagement round."""
    
    print("🚀 Starting X Engagement Round (twikit)", flush=True)
    print("=" * 50, flush=True)
    
    client = await get_client()
    stats = {"likes": 0, "replies": 0, "follows": 0, "errors": 0}
    
    # Shuffle targets for variety
    targets = random.sample(TARGET_ACCOUNTS, min(4, len(TARGET_ACCOUNTS)))
    
    for username in targets:
        print(f"\n👤 Engaging with @{username}...", flush=True)
        
        try:
            user = await client.get_user_by_screen_name(username)
            if not user:
                continue
            
            # Follow if not already following
            if stats["follows"] < follow_count:
                if await follow_user(client, user.id):
                    stats["follows"] += 1
                    log_action("FOLLOW", f"@{username}")
                await asyncio.sleep(random.uniform(2, 4))
            
            # Get their recent tweets
            tweets = await get_user_tweets(client, username, count=5)
            
            for tweet in tweets[:2]:  # Engage with top 2 tweets per user
                # Like
                if stats["likes"] < like_count:
                    if await like_tweet(client, tweet.id):
                        stats["likes"] += 1
                        log_action("LIKE", f"@{username}'s tweet")
                    await asyncio.sleep(random.uniform(1, 3))
                
                # Reply - DISABLED: Error 226 automation detection
                # Log suggestions for manual posting instead
                if stats["replies"] < reply_count and len(tweet.text) > 50:
                    reply_text = generate_reply(tweet.text)
                    # Queue for manual posting:
                    log_action("REPLY_QUEUE", f"@{username} | {reply_text}")
                    stats["replies"] += 1
            
            await asyncio.sleep(random.uniform(3, 6))
            
        except Exception as e:
            print(f"Error engaging with @{username}: {e}", flush=True)
            stats["errors"] += 1
    
    # Summary
    print("\n" + "=" * 50, flush=True)
    print("📊 ENGAGEMENT COMPLETE", flush=True)
    print(f"   Likes: {stats['likes']}", flush=True)
    print(f"   Replies: {stats['replies']}", flush=True)
    print(f"   Follows: {stats['follows']}", flush=True)
    print(f"   Errors: {stats['errors']}", flush=True)
    print("=" * 50, flush=True)
    
    log_action("ROUND_DONE", f"L:{stats['likes']} R:{stats['replies']} F:{stats['follows']}")
    
    return stats


async def main():
    """Main entry."""
    like_count = 5
    reply_count = 2
    follow_count = 2
    
    if "--heavy" in sys.argv:
        like_count, reply_count, follow_count = 10, 4, 3
    if "--light" in sys.argv:
        like_count, reply_count, follow_count = 3, 1, 1
    if "--dry-run" in sys.argv:
        print("DRY RUN - would engage:", flush=True)
        print(f"  Likes: {like_count}", flush=True)
        print(f"  Replies: {reply_count}", flush=True)
        print(f"  Follows: {follow_count}", flush=True)
        return
    
    await run_engagement_round(like_count, reply_count, follow_count)


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