from django.core.management.base import BaseCommand
from django.utils import timezone
from datetime import datetime, timedelta
from news.models import News, NewsView
import random

class Command(BaseCommand):
    help = 'Create dummy views for news articles'

    def handle(self, *args, **options):
        self.stdout.write('Creating dummy views for news articles...')
        
        # Get all published news
        news_articles = News.objects.filter(status='published')
        
        if not news_articles.exists():
            self.stdout.write(self.style.WARNING('No published news found. Please create news articles first.'))
            return
        
        created_count = 0
        
        # Create views for each news article
        for news in news_articles:
            # Random number of views (10-100 per article)
            num_views = random.randint(10, 100)
            
            # Create views over the last 30 days
            for i in range(num_views):
                # Random date within last 30 days
                random_days = random.randint(0, 30)
                random_hours = random.randint(0, 23)
                random_minutes = random.randint(0, 59)
                
                view_date = timezone.now() - timedelta(
                    days=random_days,
                    hours=random_hours,
                    minutes=random_minutes
                )
                
                # Create NewsView with unique session_key
                news_view = NewsView.objects.create(
                    news=news,
                    view_date=view_date,
                    ip_address=f'192.168.1.{random.randint(1, 255)}',
                    user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                    session_key=f'session_{random.randint(100000, 999999)}_{i}'
                )
                
                created_count += 1
            
            self.stdout.write(f'Created {num_views} views for news: {news.title[:50]}...')
        
        self.stdout.write(
            self.style.SUCCESS(f'Successfully created {created_count} views for news articles')
        )
