import os
import shutil
import random
import socket
from django.core.management.base import BaseCommand
from django.conf import settings
from apps.crm.models import Project, StudentShowcase, Teacher

class Command(BaseCommand):
    help = 'Populate database with business mock data using existing local images'

    def handle(self, *args, **kwargs):
        # Get local IP
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(('8.8.8.8', 80))
            ip = s.getsockname()[0]
            s.close()
        except Exception:
            ip = '127.0.0.1'

        self.base_url = f"http://{ip}:8000"
        self.stdout.write(f"Using Base URL: {self.base_url}")
        
        self.media_root = settings.MEDIA_ROOT
        self.projects_dir = os.path.join(self.media_root, 'projects')
        self.showcases_dir = os.path.join(self.media_root, 'showcases')
        
        # Ensure directories exist
        os.makedirs(self.projects_dir, exist_ok=True)
        os.makedirs(self.showcases_dir, exist_ok=True)

        self.stdout.write('Starting population...')
        
        # Identify available source images
        source_project_images = [f'project_{i}.jpg' for i in range(1, 9)]
        source_showcase_images = ['showcase_1.jpg', 'showcase_2.jpg']
        
        # Verify at least one source image exists, otherwise warn
        if not os.path.exists(os.path.join(self.projects_dir, source_project_images[0])):
            self.stdout.write(self.style.WARNING("Source images (project_*.jpg) not found! Please ensure default images exist."))
            # Fallback to creating a basic one if absolutely nothing exists? 
            # For now, let's assume they exist as seen in LS.

        # Create a default teacher if needed
        teacher, _ = Teacher.objects.get_or_create(
            name="教务中心",
            defaults={'phone': '13800138000', 'bio': '负责课程教务管理'}
        )

        # 1. Projects Data
        projects_data = [
            {
                'title': '工商管理博士 (DBA)',
                'project_type': 'training',
                'target_name': 'dba.jpg',
                'detail': 'DBA项目旨在培养具有全球视野和战略思维的商业领袖。',
                'teacher': teacher
            },
            {
                'title': '工商管理硕士 (MBA)',
                'project_type': 'training',
                'target_name': 'mba.jpg',
                'detail': 'MBA项目提供全面的商业管理知识，提升管理能力。',
                'teacher': teacher
            },
            {
                'title': '应用心理学硕士',
                'project_type': 'training',
                'target_name': 'psychology.jpg',
                'detail': '深入探索人类心理，应用于管理和生活中。',
                'teacher': teacher
            },
            {
                'title': '人工智能与商业应用',
                'project_type': 'training',
                'target_name': 'ai.jpg',
                'detail': '掌握AI技术，赋能商业创新。',
                'teacher': teacher
            },
            {
                'title': '高级工商管理博士 (EDBA)',
                'project_type': 'training',
                'target_name': 'edba.jpg',
                'detail': '为资深管理者量身定制的最高学位项目。',
                'teacher': teacher
            },
            {
                'title': '2025秋季开学典礼',
                'project_type': 'competition',
                'target_name': 'opening_ceremony.jpg',
                'detail': '欢迎新同学加入我们的大家庭。',
                'teacher': teacher
            },
            {
                'title': '2025届毕业典礼',
                'project_type': 'competition',
                'target_name': 'graduation.jpg',
                'detail': '祝贺各位同学顺利毕业，前程似锦。',
                'teacher': teacher
            },
            {
                'title': '全球商业领袖论坛',
                'project_type': 'competition',
                'target_name': 'forum.jpg',
                'detail': '汇聚全球智慧，探讨商业未来。',
                'teacher': teacher
            },
            {
                'title': '校友会年度聚会',
                'project_type': 'grading',
                'target_name': 'alumni.jpg',
                'detail': '重温同窗情谊，共谋发展机遇。',
                'teacher': teacher
            }
        ]

        for i, p_data in enumerate(projects_data):
            # Cycle through available source images
            src_img_name = source_project_images[i % len(source_project_images)]
            local_path = self.copy_image('projects', src_img_name, 'projects', p_data['target_name'])
            
            Project.objects.update_or_create(
                title=p_data['title'],
                defaults={
                    'project_type': p_data['project_type'],
                    'teacher': p_data['teacher'],
                    'image': local_path,
                    'detail': p_data['detail']
                }
            )
            self.stdout.write(f"Updated Project: {p_data['title']} with image {src_img_name}")

        # 2. Exciting Videos (StudentShowcase)
        videos_data = [
            {
                'title': '人工智能课程精彩片段',
                'target_name': 'video_ai.jpg',
                'video_url': 'https://www.w3schools.com/html/mov_bbb.mp4',
                'description': '课堂实录，感受AI魅力。'
            },
            {
                'title': 'DBA学员分享',
                'target_name': 'video_dba.jpg',
                'video_url': 'https://www.w3schools.com/html/movie.mp4',
                'description': '听听学长学姐怎么说。'
            },
            {
                'title': '毕业典礼回顾',
                'target_name': 'video_grad.jpg',
                'video_url': 'https://www.w3schools.com/html/mov_bbb.mp4',
                'description': '难忘瞬间，感动常在。'
            }
        ]

        for i, v_data in enumerate(videos_data):
            src_img_name = source_showcase_images[i % len(source_showcase_images)]
            # Note: source showcases are in 'projects' folder based on LS output? 
            # Wait, LS showed showcase_1.jpg in 'projects' folder!
            local_path = self.copy_image('projects', src_img_name, 'showcases', v_data['target_name'])
            
            StudentShowcase.objects.update_or_create(
                title=v_data['title'],
                defaults={
                    'cover_image': local_path,
                    'video_url': v_data['video_url'],
                    'description': v_data['description']
                }
            )
            self.stdout.write(f"Updated Video: {v_data['title']} with image {src_img_name}")

        self.stdout.write(self.style.SUCCESS('Successfully populated business data using local images!'))

    def copy_image(self, src_folder, src_filename, dest_folder, dest_filename):
        src_path = os.path.join(self.media_root, src_folder, src_filename)
        dest_path = os.path.join(self.media_root, dest_folder, dest_filename)
        relative_path = f"/media/{dest_folder}/{dest_filename}"
        
        if not os.path.exists(src_path):
            self.stdout.write(self.style.WARNING(f"Source image not found: {src_path}"))
            return relative_path # Return path anyway, hoping it exists or will be fixed

        try:
            shutil.copy2(src_path, dest_path)
            self.stdout.write(f"Copied {src_filename} to {dest_filename}")
            return relative_path
        except Exception as e:
            self.stdout.write(self.style.ERROR(f"Error copying image: {str(e)}"))
            return relative_path
