#!/usr/bin/env python3
"""X Daily Content Poster - Uses twikit cookies (no browser automation)"""

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

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

# Load cookies
COOKIES_PATH = Path(__file__).parent.parent / "cdc-social-poster" / "scripts" / "x_cookies.json"

# Daily Content Pipeline
CONTENT_PIPELINE = {
    "questions": [
        "What's the most you've saved on a single dispensary trip? Florida deals are getting wild lately 🔥",
        "Flower vs concentrates: where are you finding the best value in FL right now?",
        "Which dispensary has the most consistent sales? Not the biggest %, just the most reliable.",
        "Anyone else tracking deals across multiple menus or is that just me? 👀",
        "Best dispensary loyalty program in Florida — fight me. (I'm partial to ones that actually stack)",
    ],
    "takes": [
        "Florida's medical market is expensive, but the deals are there if you know where to look. Jungle Boys dropping $30 eighths changed the game.",
        "Stop sleeping on GoldFlower. Their smalls program hits different for the price.",
        "The Flowery's freshness is worth the premium. Other spots need to take notes on packaging.",
        "Cookies in Florida is finally priced competitively. Took long enough.",
        "If you're paying full price at Trulieve, you're doing it wrong. They run 30% off almost weekly.",
    ],
    "comparisons": [
        "Jungle Boys vs The Flowery: Both top tier, but JB wins on consistency. Flowery wins on freshness. Your move depends on priorities.",
        "MUV rosin vs Jungle Boys live rosin: JB has the terps, MUV has the convenience. Price similar when both on sale.",
        "Tier 1 vs Tier 2 flower at most FL dispensaries: The gap isn't worth the price jump most of the time. Small buds for the win.",
        "Sunburn vs GoldFlower: Both bringing heat at lower price points. Sunburn's genetics are wild, GoldFlower's quality control is tighter.",
    ],
}

# Engagement forecasts
FORECASTS = {
    "question": {"impressions": "200-400", "engagements": "15-30", "reasoning": "Questions drive replies and quote tweets"},
    "take": {"impressions": "300-500", "engagements": "20-40", "reasoning": "Hot takes generate quote tweets and debates"},
    "comparison": {"impressions": "250-450", "engagements": "18-35", "reasoning": "Comparisons attract informed comments from experienced patients"},
}


def select_content():
    """Select content based on day of week."""
    today = datetime.now()
    day_of_week = today.weekday()  # 0=Monday
    
    # Rotate: questions (0,3), takes (1,4), comparisons (2,5,6)
    if day_of_week in [0, 3]:
        content_type = "question"
        pool = CONTENT_PIPELINE["questions"]
    elif day_of_week in [1, 4]:
        content_type = "take"
        pool = CONTENT_PIPELINE["takes"]
    else:
        content_type = "comparison"
        pool = CONTENT_PIPELINE["comparisons"]
    
    # Select based on day to ensure variety
    content_index = day_of_week % len(pool)
    return content_type, pool[content_index]


async def post_to_x(text: str) -> dict:
    """Post tweet using twikit with cookies."""
    if not COOKIES_PATH.exists():
        return {"success": False, "error": f"Cookies not found at {COOKIES_PATH}"}
    
    client = Client(language='en-US')
    
    # Load and set cookies
    cookies = json.loads(COOKIES_PATH.read_text())
    client.set_cookies(cookies)
    
    try:
        tweet = await client.create_tweet(text=text)
        return {
            "success": True,
            "tweet_id": tweet.id,
            "text": text,
            "url": f"https://x.com/cannadealsfl/status/{tweet.id}"
        }
    except Exception as e:
        return {"success": False, "error": str(e)}


async def main():
    print("=" * 60)
    print("X Daily Content Poster - @cannadealsfl")
    print(f"Time: {datetime.now().isoformat()}")
    print("=" * 60)
    
    # Select content
    content_type, tweet_text = select_content()
    forecast = FORECASTS[content_type]
    
    print(f"\n📋 Content Type: {content_type.upper()}")
    print(f"📝 Tweet Text: {tweet_text}")
    print(f"\n📊 Engagement Forecast:")
    print(f"   - Estimated Impressions: {forecast['impressions']}")
    print(f"   - Estimated Engagements: {forecast['engagements']}")
    print(f"   - Reasoning: {forecast['reasoning']}")
    
    # Post
    print(f"\n🚀 Posting to X...")
    result = await post_to_x(tweet_text)
    
    if result["success"]:
        print(f"\n✅ SUCCESS!")
        print(f"   Tweet URL: {result['url']}")
        print(f"   Tweet ID: {result['tweet_id']}")
    else:
        print(f"\n❌ FAILED: {result['error']}")
        return 1
    
    # Final summary
    print("\n" + "=" * 60)
    print("SUMMARY")
    print("=" * 60)
    print(f"Posted: {tweet_text}")
    print(f"Type: {content_type}")
    print(f"Forecast: {forecast['impressions']} impressions, {forecast['engagements']} engagements")
    print(f"Status: {'✅ Posted' if result['success'] else '❌ Failed'}")
    if result.get('url'):
        print(f"URL: {result['url']}")
    
    return 0 if result["success"] else 1


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