import praw
import json
from datetime import datetime

# Reddit API credentials
reddit = praw.Reddit(
    client_id="YOUR_CLIENT_ID",
    client_secret="YOUR_CLIENT_SECRET",
    username="YOUR_USERNAME",
    password="YOUR_PASSWORD",
    user_agent="MyApp/1.0 by YourUsername"
)

def get_user_feed(username, limit=25):
    """
    Get a user's Reddit feed (their posts and comments)
    
    Args:
        username (str): Reddit username
        limit (int): Number of items to retrieve
    
    Returns:
        list: List of posts and comments
    """
    try:
        user = reddit.redditor(username)
        feed_items = []
        
        # Get user's submissions (posts)
        for submission in user.submissions.new(limit=limit):
            feed_items.append({
                'type': 'submission',
                'id': submission.id,
                'title': submission.title,
                'subreddit': str(submission.subreddit),
                'score': submission.score,
                'created_utc': submission.created_utc,
                'url': submission.url,
                'selftext': submission.selftext,
                'num_comments': submission.num_comments
            })
        
        # Get user's comments
        for comment in user.comments.new(limit=limit):
            feed_items.append({
                'type': 'comment',
                'id': comment.id,
                'subreddit': str(comment.subreddit),
                'score': comment.score,
                'created_utc': comment.created_utc,
                'body': comment.body,
                'parent_id': comment.parent_id,
                'submission_title': comment.submission.title
            })
        
        # Sort by creation time (newest first)
        feed_items.sort(key=lambda x: x['created_utc'], reverse=True)
        
        return feed_items
        
    except Exception as e:
        print(f"Error fetching feed: {e}")
        return []

def get_home_feed(limit=25):
    """
    Get the authenticated user's home feed
    
    Args:
        limit (int): Number of posts to retrieve
    
    Returns:
        list: List of posts from subscribed subreddits
    """
    try:
        feed_items = []
        
        # Get hot posts from home feed
        for submission in reddit.front.hot(limit=limit):
            feed_items.append({
                'type': 'submission',
                'id': submission.id,
                'title': submission.title,
                'subreddit': str(submission.subreddit),
                'author': str(submission.author),
                'score': submission.score,
                'created_utc': submission.created_utc,
                'url': submission.url,
                'selftext': submission.selftext,
                'num_comments': submission.num_comments,
                'upvote_ratio': submission.upvote_ratio
            })
        
        return feed_items
        
    except Exception as e:
        print(f"Error fetching home feed: {e}")
        return []

def display_feed(feed_items):
    """Display feed items in a readable format"""
    for item in feed_items:
        timestamp = datetime.fromtimestamp(item['created_utc'])
        
        if item['type'] == 'submission':
            print(f"\n📝 POST in r/{item['subreddit']}")
            print(f"   Title: {item['title']}")
            print(f"   Score: {item['score']} | Comments: {item['num_comments']}")
            print(f"   Posted: {timestamp.strftime('%Y-%m-%d %H:%M:%S')}")
            if item['selftext']:
                print(f"   Text: {item['selftext'][:100]}...")
                
        elif item['type'] == 'comment':
            print(f"\n💬 COMMENT in r/{item['subreddit']}")
            print(f"   On: {item['submission_title']}")
            print(f"   Score: {item['score']}")
            print(f"   Posted: {timestamp.strftime('%Y-%m-%d %H:%M:%S')}")
            print(f"   Comment: {item['body'][:100]}...")

# Example usage
if __name__ == "__main__":
    # Get a specific user's feed
    user_feed = get_user_feed("spez", limit=10)  # Replace with actual username
    print("=== USER FEED ===")
    display_feed(user_feed)
    
    # Get your home feed (requires authentication)
    print("\n\n=== HOME FEED ===")
    home_feed = get_home_feed(limit=10)
    display_feed(home_feed)
    
    # Save to JSON file
    with open('reddit_feed.json', 'w') as f:
        json.dump({
            'user_feed': user_feed,
            'home_feed': home_feed,
            'timestamp': datetime.now().isoformat()
        }, f, indent=2)