import json
import requests
from django.core.management.base import BaseCommand
from django.conf import settings

MCA_COURSE_DATA = {
    "title": "MCA",
    "slug": "mca",
    "short_description": "Master of Computer Applications (MCA) - Advanced program in computer applications and software development.",
    "overview": """Master of Computer Application (MCA)\n\nRoorkee College of Smart Computing offers a comprehensive 2-year regular Master’s degree in Computer Applications (MCA), designed to provide students with advanced knowledge and skills in modern computing. This program stands out due to its unique approach, allowing students to specialize in emerging areas of computing over the course of their studies. Specializations available include System Programming, Database Management, Networking, Web-Designing, and Artificial Intelligence.\nThe primary goal of the MCA program at Roorkee College of Smart Computing, recognized as the best MCA college in Uttarakhand and North India, is to prepare students for successful careers in the IT industry. The curriculum is meticulously crafted to ensure students achieve global competence in cutting-edge technologies. This includes proficiency in areas such as Cloud Computing, Android Applications, JAVA, Oracle, .NET, PHP, and CISCO technologies, among others.\nBy pursuing an MCA degree from Roorkee College of Smart Computing, students benefit from a program ranked among the best university institutes of computing in India. The program not only provides theoretical knowledge but also emphasizes practical skills and real-world applications, which are essential for career advancement. Students engage in hands-on projects, internships, and industry collaborations that enhance their learning experience and prepare them for the demands of the global IT industry.\nThe MCA program at Roorkee College of Smart Computing is designed to equip students with the expertise needed to thrive in the rapidly evolving field of computer science and information technology. It offers a blend of specialized knowledge, practical experience, and exposure to the latest technological advancements, ensuring graduates are well-prepared to excel in their careers and contribute to the industry’s growth.""",
    "duration": "2 Years (4 Semesters)",
    "category": "Computer Applications",
    "banner_image": None,
    "college_id": 2,
    "eligibility": {
        "academic_qualification": "Bachelor’s Degree in Computer Science, Computer Applications (BCA), Information Technology, or related field.",
        "minimum_marks": "As per university norms.",
        "entrance_exam": "As per university/AICTE guidelines."
    },
    "fees": {
        "details": [
            {"fee_head": "1st Year", "amount": "92000/-"},
            {"fee_head": "2nd Year", "amount": "75000/-"}
        ]
    },
    "hostel_fee": {
        "normal_room": "85000/-",
        "semi_deluxe_room": "95000/-",
        "deluxe_room": "105000/-",
        "notes": "The Hostel fee includes lodging, mess & laundry charges. Student can give maximum of 50 clothes in a month for washing & ironing. The balance of previous month cannot be carried to the next month. Electricity prepaid meters are installed in each room."
    },
    "semesters": [
        {"name": "Semester I", "subjects": [
            {"code": "24MCA101P", "name": "Data Structures Using C/C++ Lab", "category": "Major Course", "credit": 1},
            {"code": "24MCA101T", "name": "Data Structures Using C/C++", "category": "Major Course", "credit": 3},
            {"code": "24MCA102P", "name": "Data Base Management Systems Lab", "category": "Major Course", "credit": 1},
            {"code": "24MCA102T", "name": "Data Base Management Systems", "category": "Major Course", "credit": 3},
            {"code": "24MCA103P", "name": "Computer Organisation & Architecture Lab", "category": "Major Course", "credit": 1},
            {"code": "24MCA103T", "name": "Computer Organisation & Architecture", "category": "Major Course", "credit": 3},
            {"code": "24MCA104T", "name": "Discrete Structures", "category": "Major Course", "credit": 4},
            {"code": "24MCA105T", "name": "Software Engineering", "category": "Major Course", "credit": 4},
            {"code": "24AEC001T", "name": "Soft Skills And Verbal Communication-I", "category": "AEC", "credit": 3}
        ]},
        {"name": "Semester II", "subjects": [
            {"code": "24MCA201P", "name": "Python Programming Lab", "category": "Major Course", "credit": 1},
            {"code": "24MCA201T", "name": "Python Programming", "category": "Major Course", "credit": 3},
            {"code": "24MCA202P", "name": "Operating Systems Lab", "category": "Major Course", "credit": 1},
            {"code": "24MCA202T", "name": "Operating Systems", "category": "Major Course", "credit": 4},
            {"code": "24MCA203P", "name": "Computer Networks Lab", "category": "Major Course", "credit": 1},
            {"code": "24MCA203T", "name": "Computer Networks", "category": "Major Course", "credit": 3},
            {"code": "24MCA204T", "name": "Fundamentals of AI & ML", "category": "Major Course", "credit": 4},
            {"code": "24SEC003T", "name": "Quntitative, Aptitude And Logical Reasoning-I", "category": "Skill Enhancement Course", "credit": 2}
        ]},
        {"name": "Semester III", "subjects": [
            {"code": "24MCA301P", "name": "Computer Graphics And Multimedia Lab", "category": "Major Course", "credit": 1},
            {"code": "24MCA301T", "name": "Computer Graphics And Multimedia", "category": "Major Course", "credit": 4},
            {"code": "24MCA302T", "name": "Compiler Design", "category": "Major Course", "credit": 4},
            {"code": "24MCA303T", "name": "Big Data Analytics", "category": "Major Course", "credit": 4},
            {"code": "24MCA304P", "name": "Java Programming Lab", "category": "Major Course", "credit": 1},
            {"code": "24MCA304T", "name": "Java Programming", "category": "Major Course", "credit": 4},
            {"code": "24EMC305T", "name": "Data Visualization Using Power Bi And Tableau", "category": "Discipline Elective-I", "credit": 3},
            {"code": "24EMC306T", "name": "Cloud Computing", "category": "Discipline Elective-I", "credit": 3},
            {"code": "24EMC307T", "name": "Business Intelligence", "category": "Discipline Elective-I", "credit": 3},
            {"code": "24AEC002T", "name": "Soft Skills And Verbal Communication-II", "category": "AEC", "credit": 3},
            {"code": "24SIP001P", "name": "Summer Internship-I", "category": "Summer Internship", "credit": 2}
        ]},
        {"name": "Semester IV", "subjects": [
            {"code": "24MCA401P", "name": "Dissertation", "category": "Project", "credit": 12},
            {"code": "24VAC003P", "name": "MOOC/Swayam Online Course(As Decided By Department) Or Value Added Course Run By University-I", "category": "Value Added Course", "credit": 2},
            {"code": "24VAC004P", "name": "MOOC/Swayam Online Course(As Decided By Department) Or Value Added Course Run By University-II", "category": "Value Added Course", "credit": 2}
        ]}
    ],
    "career_prospects": [
        {"title": "Software Developer"},
        {"title": "Software Tester"},
        {"title": "Hardware Engineer"},
        {"title": "Database Engineer"},
        {"title": "Cloud Architect"},
        {"title": "Data Scientist"},
        {"title": "Business Analyst"},
        {"title": "Technical Writer"},
        {"title": "Web Designer/Developer"},
        {"title": "IT Architect"},
        {"title": "Software Consultant"},
        {"title": "Network Engineer"},
        {"title": "Quality Assurance Analyst"},
        {"title": "Project Manager"}
    ]
    ,
    "highlights": [
        "Specializations in System Programming, Database Management, Networking, Web-Designing, and Artificial Intelligence.",
        "Industry-oriented curriculum with focus on Cloud Computing, Android Applications, JAVA, Oracle, .NET, PHP, and CISCO technologies.",
        "Hands-on projects, internships, and industry collaborations.",
        "Recognized as one of the best MCA colleges in Uttarakhand and North India.",
        "Emphasis on both theoretical knowledge and practical skills."
    ],
    "testimonials": [
        {
            "name": "Amit Sharma",
            "designation": "Software Engineer, Infosys",
            "message": "The MCA program at Roorkee College of Smart Computing gave me the technical foundation and confidence to excel in my career. The practical exposure and industry projects were invaluable."
        },
        {
            "name": "Priya Verma",
            "designation": "Data Analyst, TCS",
            "message": "The faculty and curriculum are top-notch. The focus on emerging technologies and real-world applications made all the difference in my professional journey."
        }
    ],
    "recruiters": [
        "Infosys",
        "TCS",
        "Wipro",
        "HCL",
        "IBM",
        "Capgemini",
        "Accenture",
        "Tech Mahindra"
    ],
    "why_choose": [
        "Globally recognized curriculum aligned with industry needs.",
        "Experienced faculty with strong academic and industry backgrounds.",
        "Excellent placement record with top IT companies.",
        "Modern labs and infrastructure.",
        "Opportunities for research, innovation, and entrepreneurship."
    ]
}

class Command(BaseCommand):
    help = 'Insert or update course data using the API. Default: inserts MCA course.'

    def add_arguments(self, parser):
        parser.add_argument('--slug', type=str, default='mca', help='Course slug to insert or update')
        parser.add_argument('--api_base', type=str, default='https://api-cmshu.surl.co.in', help='Base URL for the API')
        parser.add_argument('--data_file', type=str, help='Path to JSON file with course data (overrides default)')

    def handle(self, *args, **options):
        slug = options['slug']
        api_base = options['api_base']
        data_file = options.get('data_file')
        if data_file:
            with open(data_file, 'r') as f:
                course_data = json.load(f)
        else:
            course_data = MCA_COURSE_DATA

        # Check if course exists
        detail_url = f"{api_base}/api/courses/{slug}/"
        create_url = f"{api_base}/api/courses/create/"
        update_url = f"{api_base}/api/courses/{slug}/update/"  # Use dedicated update endpoint
        try:
            resp = requests.get(detail_url)
            if resp.status_code == 200:
                self.stdout.write(self.style.WARNING(f"Course with slug '{slug}' already exists. Updating..."))
                # Update the course
                update_resp = requests.put(update_url, json=course_data)
                if update_resp.status_code in (200, 201):
                    self.stdout.write(self.style.SUCCESS(f"Course '{slug}' updated successfully."))
                else:
                    self.stdout.write(self.style.ERROR(f"Failed to update course: {update_resp.status_code} {update_resp.text}"))
                return
        except Exception as e:
            self.stdout.write(self.style.WARNING(f"Could not check course existence: {e}"))

        # Create course
        try:
            resp = requests.post(create_url, json=course_data)
            if resp.status_code in (200, 201):
                self.stdout.write(self.style.SUCCESS(f"Course '{slug}' created successfully."))
            else:
                self.stdout.write(self.style.ERROR(f"Failed to create course: {resp.status_code} {resp.text}"))
        except Exception as e:
            self.stdout.write(self.style.ERROR(f"Error creating course: {e}"))
