import os
from django.core.management.base import BaseCommand
from courses.models import Course, HostelFee
from colleges.models import College

class Command(BaseCommand):
    help = 'Updates hostel fees for all courses in Roorkee College of Business Studies'

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('Starting to update hostel fees for Business Studies courses'))
        
        # Get the Business Studies college by ID
        try:
            business_college = College.objects.get(id=3)
            self.stdout.write(self.style.SUCCESS(f'Found college: {business_college.name} (ID: {business_college.id})'))
        except College.DoesNotExist:
            self.stdout.write(self.style.ERROR('Business Studies college with ID 3 not found.'))
            return
        
        # Get all programs for this college
        programs = business_college.programs_section.programs.all()
        
        self.stdout.write(self.style.SUCCESS(f'Found {programs.count()} programs for this college'))
        
        if not programs.exists():
            self.stdout.write(self.style.WARNING('No programs found for this college.'))
            return
        
        # Extract course slugs from program links
        course_slugs = []
        for program in programs:
            self.stdout.write(f'Program: {program.name} -> Link: {program.link}')
            # Extract slug from link like "/academics/programs/courses/bcom/"
            if '/courses/' in program.link:
                slug = program.link.split('/courses/')[-1].rstrip('/')
                course_slugs.append(slug)
                self.stdout.write(f'  Extracted slug: {slug}')
        
        self.stdout.write(self.style.SUCCESS(f'Found {len(course_slugs)} course slugs: {course_slugs}'))
        
        if not course_slugs:
            self.stdout.write(self.style.WARNING('No valid course links found in programs.'))
            return
        
        # Get courses that match these slugs
        courses = Course.objects.filter(slug__in=course_slugs)
        
        self.stdout.write(self.style.SUCCESS(f'Found {courses.count()} matching courses in database'))
        
        if not courses.exists():
            self.stdout.write(self.style.WARNING('No courses found for this college.'))
            return
        
        self.stdout.write(self.style.SUCCESS(f'Found {courses.count()} courses to update'))
        
        # Update hostel fees for each course
        updated_count = 0
        created_count = 0
        
        for course in courses:
            hostel_fee, created = HostelFee.objects.update_or_create(
                course=course,
                defaults={
                    'fee_per_year': '₹80,000',
                    'ac_room_additional': '₹20,000',
                    'security_deposit': '₹15,000',
                    'notes': 'Hostel fees include accommodation, meals, laundry, and basic amenities. AC rooms are available with additional charges. Security deposit is refundable at the time of leaving the hostel.'
                }
            )
            
            if created:
                created_count += 1
                self.stdout.write(self.style.SUCCESS(f"Created hostel fee for: {course.title}"))
            else:
                updated_count += 1
                self.stdout.write(self.style.SUCCESS(f"Updated hostel fee for: {course.title}"))
        
        self.stdout.write(self.style.SUCCESS(f'Hostel fee update complete!'))
        self.stdout.write(self.style.SUCCESS(f'Created: {created_count} hostel fees'))
        self.stdout.write(self.style.SUCCESS(f'Updated: {updated_count} hostel fees'))
        self.stdout.write(self.style.SUCCESS(f'Total processed: {created_count + updated_count} courses'))
