from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from django.db import transaction
from apps.users.models import UserProfile
from apps.channels.models import Channel
from apps.campaigns.models import Campaign
from apps.advertisers.models import Advertiser, Adspot
from apps.analytics.models import VastTemplate
from apps.vast.models import AdDecisionEngine
import os

User = get_user_model()


class Command(BaseCommand):
    help = 'Initialize the project with sample data and configurations'
    
    def add_arguments(self, parser):
        parser.add_argument(
            '--create-superuser',
            action='store_true',
            help='Create a superuser account',
        )
        parser.add_argument(
            '--load-sample-data',
            action='store_true',
            help='Load sample data for testing',
        )
        parser.add_argument(
            '--migrate-from-old',
            action='store_true',
            help='Migrate data from old project (requires old database access)',
        )
    
    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('Starting project initialization...'))
        
        if options['create_superuser']:
            self.create_superuser()
        
        if options['load_sample_data']:
            self.load_sample_data()
        
        if options['migrate_from_old']:
            self.migrate_from_old()
        
        self.stdout.write(self.style.SUCCESS('Project initialization completed!'))
    
    def create_superuser(self):
        """Create a superuser if one doesn't exist"""
        self.stdout.write('Creating superuser...')
        
        if User.objects.filter(is_superuser=True).exists():
            self.stdout.write(self.style.WARNING('Superuser already exists'))
            return
        
        username = input('Username: ') or 'admin'
        email = input('Email: ') or 'admin@adtlas.com'
        password = input('Password: ') or 'admin123'
        
        user = User.objects.create_superuser(
            username=username,
            email=email,
            password=password
        )
        
        # Create user profile
        UserProfile.objects.create(
            user=user,
            role='admin',
            is_active=True
        )
        
        self.stdout.write(self.style.SUCCESS(f'Superuser "{username}" created successfully'))
    
    def load_sample_data(self):
        """Load sample data for testing"""
        self.stdout.write('Loading sample data...')
        
        with transaction.atomic():
            # Create sample channels
            channels_data = [
                {'name': '2M TV', 'code': '2M', 'description': 'Morocco 2M Television'},
                {'name': 'Al Aoula', 'code': 'AOULA', 'description': 'Al Aoula TV Channel'},
                {'name': 'Medi1 TV', 'code': 'MEDI1', 'description': 'Medi1 TV Channel'},
            ]
            
            for channel_data in channels_data:
                channel, created = Channel.objects.get_or_create(
                    code=channel_data['code'],
                    defaults={
                        'name': channel_data['name'],
                        'description': channel_data['description'],
                        'is_active': True
                    }
                )
                if created:
                    self.stdout.write(f'Created channel: {channel.name}')
            
            # Create sample advertisers
            advertisers_data = [
                {'name': 'Coca Cola Morocco', 'contact_email': 'contact@cocacola.ma'},
                {'name': 'Maroc Telecom', 'contact_email': 'contact@iam.ma'},
                {'name': 'BMCE Bank', 'contact_email': 'contact@bmcebank.ma'},
            ]
            
            for advertiser_data in advertisers_data:
                advertiser, created = Advertiser.objects.get_or_create(
                    name=advertiser_data['name'],
                    defaults={
                        'contact_email': advertiser_data['contact_email'],
                        'is_active': True
                    }
                )
                if created:
                    self.stdout.write(f'Created advertiser: {advertiser.name}')
            
            # Create sample campaigns
            if Advertiser.objects.exists() and Channel.objects.exists():
                advertiser = Advertiser.objects.first()
                channel = Channel.objects.first()
                
                campaign, created = Campaign.objects.get_or_create(
                    name='Summer Campaign 2024',
                    defaults={
                        'advertiser': advertiser,
                        'description': 'Summer promotional campaign',
                        'status': 'active',
                        'priority': 1
                    }
                )
                if created:
                    self.stdout.write(f'Created campaign: {campaign.name}')
                    
                    # Create sample adspot
                    adspot, created = Adspot.objects.get_or_create(
                        adspot_name='Coca Cola Summer Ad',
                        defaults={
                            'campaign': campaign,
                            'channel': channel,
                            'duration': 30,
                            'status': 'active',
                            'original_filepath': '/media/ads/sample_ad.mp4',
                            'url_from_vast': 'https://www.cocacola.ma'
                        }
                    )
                    if created:
                        self.stdout.write(f'Created adspot: {adspot.adspot_name}')
            
            # Create VAST templates
            vast_template_xml = '''
                <?xml version="1.0" encoding="UTF-8"?>
                <VAST version="3.0">
                    <Ad id="{{ adspot.id }}">
                        <InLine>
                            <AdSystem>Adtlas</AdSystem>
                            <AdTitle><![CDATA[{{ adspot.adspot_name }}]]></AdTitle>
                            <Impression><![CDATA[{{ impression_url }}]]></Impression>
                            <Creatives>
                                <Creative>
                                    <Linear>
                                        <Duration>{{ duration }}</Duration>
                                        <TrackingEvents>
                                            <Tracking event="start"><![CDATA[{{ start_url }}]]></Tracking>
                                            <Tracking event="firstQuartile"><![CDATA[{{ firstquartile_url }}]]></Tracking>
                                            <Tracking event="midpoint"><![CDATA[{{ midpoint_url }}]]></Tracking>
                                            <Tracking event="thirdQuartile"><![CDATA[{{ thirdquartile_url }}]]></Tracking>
                                            <Tracking event="complete"><![CDATA[{{ complete_url }}]]></Tracking>
                                        </TrackingEvents>
                                        <VideoClicks>
                                            <ClickThrough><![CDATA[{{ click_through_url }}]]></ClickThrough>
                                            <ClickTracking><![CDATA[{{ click_url }}]]></ClickTracking>
                                        </VideoClicks>
                                        <MediaFiles>
                                            <MediaFile delivery="progressive" type="video/mp4" width="{{ width }}" height="{{ height }}">
                                                <![CDATA[{{ media_url }}]]>
                                            </MediaFile>
                                        </MediaFiles>
                                    </Linear>
                                </Creative>
                            </Creatives>
                        </InLine>
                    </Ad>
                </VAST>
            '''
            
            template, created = VastTemplate.objects.get_or_create(
                name='Default Linear VAST Template',
                defaults={
                    'ad_type': 'linear',
                    'template_xml': vast_template_xml.strip(),
                    'is_active': True,
                    'description': 'Default template for linear video ads'
                }
            )
            if created:
                self.stdout.write(f'Created VAST template: {template.name}')
            
            # Create ad decision engine
            if Campaign.objects.exists():
                engine, created = AdDecisionEngine.objects.get_or_create(
                    name='Default Round Robin',
                    defaults={
                        'decision_type': 'round_robin',
                        'priority': 1,
                        'is_active': True,
                        'configuration': {
                            'rotation_type': 'sequential',
                            'reset_on_empty': True
                        }
                    }
                )
                if created:
                    # Add campaigns to the engine
                    engine.campaigns.add(*Campaign.objects.all())
                    self.stdout.write(f'Created ad decision engine: {engine.name}')
        
        self.stdout.write(self.style.SUCCESS('Sample data loaded successfully'))
    
    def migrate_from_old(self):
        """Migrate data from old project"""
        self.stdout.write('Starting migration from old project...')
        
        # This would require access to the old database
        # For now, we'll just show the structure
        
        migration_steps = [
            'Connect to old database',
            'Extract user data',
            'Extract channel data',
            'Extract advertiser data',
            'Extract campaign data',
            'Extract adspot data',
            'Extract analytics data',
            'Transform and load into new structure'
        ]
        
        for step in migration_steps:
            self.stdout.write(f'TODO: {step}')
        
        self.stdout.write(self.style.WARNING(
            'Migration from old project requires manual implementation '
            'based on the old database schema'
        ))
