#!/usr/bin/env python3
"""
EasyStream Content Syndication Script
Extracts video metadata and reposts to other platforms
"""

import requests
import json
import time
from datetime import datetime

class EasyStreamSyndicator:
    def __init__(self, api_base_url, jwt_token):
        self.api_base_url = api_base_url.rstrip('/')
        self.headers = {
            'Authorization': f'Bearer {jwt_token}',
            'Content-Type': 'application/json'
        }
    
    def get_videos(self, limit=50, category=None, since_date=None):
        """Get videos from EasyStream API"""
        params = {'limit': limit}
        if category:
            params['category'] = category
        if since_date:
            params['since'] = since_date
            
        response = requests.get(
            f'{self.api_base_url}/api/v1/videos',
            headers=self.headers,
            params=params
        )
        
        if response.status_code == 200:
            return response.json()['data']['videos']
        else:
            print(f"Error fetching videos: {response.status_code}")
            return []
    
    def get_video_details(self, video_id):
        """Get detailed video information"""
        response = requests.get(
            f'{self.api_base_url}/api/v1/videos/{video_id}',
            headers=self.headers
        )
        
        if response.status_code == 200:
            return response.json()['data']
        else:
            print(f"Error fetching video {video_id}: {response.status_code}")
            return None
    
    def post_to_youtube(self, video_data):
        """Post video metadata to YouTube (example)"""
        # YouTube API integration would go here
        youtube_data = {
            'title': video_data['title'],
            'description': self.format_description_for_youtube(video_data),
            'tags': video_data.get('tags', []),
            'category': self.map_category_to_youtube(video_data.get('category')),
            'privacy': 'public' if video_data.get('privacy') == 'public' else 'unlisted'
        }
        
        print(f"Would post to YouTube: {youtube_data['title']}")
        return youtube_data
    
    def post_to_tiktok(self, video_data):
        """Post video metadata to TikTok (example)"""
        # TikTok API integration would go here
        tiktok_data = {
            'title': self.truncate_title_for_tiktok(video_data['title']),
            'description': self.format_description_for_tiktok(video_data),
            'hashtags': self.extract_hashtags(video_data)
        }
        
        print(f"Would post to TikTok: {tiktok_data['title']}")
        return tiktok_data
    
    def post_to_twitter(self, video_data):
        """Post video announcement to Twitter"""
        # Twitter API integration would go here
        tweet_text = self.format_tweet(video_data)
        
        twitter_data = {
            'text': tweet_text,
            'media_url': f"{self.api_base_url}{video_data['thumbnail_url']}",
            'video_url': f"{self.api_base_url}{video_data['video_url']}"
        }
        
        print(f"Would tweet: {tweet_text}")
        return twitter_data
    
    def post_to_facebook(self, video_data):
        """Post to Facebook Page"""
        # Facebook API integration would go here
        facebook_data = {
            'message': self.format_facebook_post(video_data),
            'link': f"{self.api_base_url}{video_data['video_url']}",
            'name': video_data['title'],
            'description': video_data['description'][:200] + '...'
        }
        
        print(f"Would post to Facebook: {video_data['title']}")
        return facebook_data
    
    def syndicate_content(self, platforms=['youtube', 'twitter', 'facebook']):
        """Main syndication function"""
        print("🚀 Starting content syndication...")
        
        # Get recent videos (last 24 hours)
        since_date = datetime.now().strftime('%Y-%m-%d')
        videos = self.get_videos(limit=10, since_date=since_date)
        
        print(f"📹 Found {len(videos)} videos to syndicate")
        
        for video in videos:
            print(f"\n📝 Processing: {video['title']}")
            
            # Get detailed video info
            video_details = self.get_video_details(video['id'])
            if not video_details:
                continue
            
            # Post to selected platforms
            if 'youtube' in platforms:
                self.post_to_youtube(video_details)
            
            if 'tiktok' in platforms:
                self.post_to_tiktok(video_details)
            
            if 'twitter' in platforms:
                self.post_to_twitter(video_details)
            
            if 'facebook' in platforms:
                self.post_to_facebook(video_details)
            
            # Rate limiting
            time.sleep(2)
        
        print("\n✅ Content syndication completed!")
    
    # Helper methods for formatting content
    def format_description_for_youtube(self, video_data):
        """Format description for YouTube"""
        description = video_data['description']
        
        # Add source attribution
        description += f"\n\n🎥 Originally posted on EasyStream"
        description += f"\n👤 Creator: {video_data['uploader']['display_name']}"
        description += f"\n🔗 Watch original: {self.api_base_url}{video_data['video_url']}"
        
        # Add hashtags
        if video_data.get('tags'):
            hashtags = ' '.join([f"#{tag}" for tag in video_data['tags'][:10]])
            description += f"\n\n{hashtags}"
        
        return description
    
    def format_description_for_tiktok(self, video_data):
        """Format description for TikTok (shorter)"""
        description = video_data['description'][:100] + '...'
        
        # Add hashtags
        hashtags = self.extract_hashtags(video_data)
        return f"{description} {hashtags}"
    
    def format_tweet(self, video_data):
        """Format tweet (280 char limit)"""
        title = video_data['title'][:100]
        url = f"{self.api_base_url}{video_data['video_url']}"
        
        # Calculate remaining space for hashtags
        base_text = f"🎥 {title}\n\n👀 Watch: {url}"
        remaining = 280 - len(base_text) - 10  # Buffer
        
        hashtags = self.extract_hashtags(video_data, max_length=remaining)
        
        return f"{base_text}\n\n{hashtags}"
    
    def format_facebook_post(self, video_data):
        """Format Facebook post"""
        post = f"🎥 New Video: {video_data['title']}\n\n"
        post += f"{video_data['description'][:300]}...\n\n"
        post += f"👤 By: {video_data['uploader']['display_name']}\n"
        post += f"👀 {video_data['views']} views\n\n"
        post += f"Watch now: {self.api_base_url}{video_data['video_url']}"
        
        return post
    
    def extract_hashtags(self, video_data, max_length=100):
        """Extract and format hashtags"""
        tags = video_data.get('tags', [])
        category = video_data.get('category', '')
        
        hashtags = []
        if category:
            hashtags.append(f"#{category}")
        
        for tag in tags:
            hashtag = f"#{tag.replace(' ', '')}"
            if len(' '.join(hashtags + [hashtag])) <= max_length:
                hashtags.append(hashtag)
            else:
                break
        
        return ' '.join(hashtags)
    
    def truncate_title_for_tiktok(self, title):
        """Truncate title for TikTok"""
        return title[:50] + '...' if len(title) > 50 else title
    
    def map_category_to_youtube(self, category):
        """Map EasyStream category to YouTube category"""
        category_map = {
            'gaming': 'Gaming',
            'music': 'Music',
            'education': 'Education',
            'entertainment': 'Entertainment',
            'sports': 'Sports',
            'tech': 'Science & Technology'
        }
        return category_map.get(category, 'Entertainment')

# Usage example
if __name__ == "__main__":
    # Configuration
    API_BASE_URL = "https://yourdomain.com"
    JWT_TOKEN = "your_jwt_token_here"
    
    # Initialize syndicator
    syndicator = EasyStreamSyndicator(API_BASE_URL, JWT_TOKEN)
    
    # Syndicate to all platforms
    syndicator.syndicate_content(['youtube', 'twitter', 'facebook', 'tiktok'])