"""
Django management command to seed News and Events data for Haridwar University

This creates 5 categories and 10 news items with sample content.
"""

import os
from django.core.management.base import BaseCommand
from django.utils import timezone
from django.utils.text import slugify
from datetime import timedelta
import random

from news.models import Category, News


class Command(BaseCommand):
    help = 'Seeds the database with sample categories and news items for Haridwar University'

    def handle(self, *args, **kwargs):
        self.stdout.write(self.style.SUCCESS('🌱 Starting data seeding for News and Events...'))
        
        # Create Categories
        categories_data = [
            {
                'name': 'Announcements',
                'description': 'Official announcements and notices from Haridwar University'
            },
            {
                'name': 'Events',
                'description': 'Upcoming and past events, seminars, and workshops'
            },
            {
                'name': 'Achievements',
                'description': 'Student and faculty achievements, awards, and recognitions'
            },
            {
                'name': 'Admissions',
                'description': 'Admission-related news and important dates'
            },
            {
                'name': 'Campus Life',
                'description': 'News about campus activities, clubs, and student life'
            }
        ]

        categories = {}
        self.stdout.write('\n📁 Creating Categories...')
        for cat_data in categories_data:
            category, created = Category.objects.get_or_create(
                name=cat_data['name'],
                defaults={
                    'slug': slugify(cat_data['name']),
                    'description': cat_data['description']
                }
            )
            categories[cat_data['name']] = category
            status = '✅ Created' if created else '⚠️  Already exists'
            self.stdout.write(f'   {status}: {category.name}')

        # Create News Items
        news_data = [
            {
                'title': 'Haridwar University Announces Admission Open for Academic Year 2025-26',
                'short_description': 'Applications are now open for UG and PG programs across all faculties. Apply online and secure your future at Haridwar University.',
                'description': '''Haridwar University is pleased to announce that admissions are now open for the Academic Year 2025-26. 

We invite applications for various Undergraduate (UG) and Postgraduate (PG) programs across diverse disciplines including Engineering, Management, Computer Applications, Pharmacy, and more.

**Key Highlights:**
- Wide range of industry-relevant programs
- Experienced faculty with academic and industry expertise
- State-of-the-art infrastructure and laboratories
- Strong placement support and career guidance
- Scholarships available for meritorious students

**Important Dates:**
- Application Start Date: November 1, 2025
- Application Deadline: March 31, 2026
- Entrance Test: April 15, 2026

For more information and online application, visit our admissions portal or contact the admissions office.

Join us in shaping your future with quality education and holistic development!''',
                'category': 'Admissions',
                'days_ago': 2
            },
            {
                'title': 'National Seminar on Artificial Intelligence and Machine Learning',
                'short_description': 'Join us for a two-day national seminar on AI/ML trends, applications, and future scope. Industry experts and academicians will share insights.',
                'description': '''Haridwar University is organizing a National Seminar on "Artificial Intelligence and Machine Learning: Trends and Future Prospects" on December 5-6, 2025.

This two-day event will bring together leading academicians, industry experts, and researchers to discuss the latest trends, research, and applications in AI/ML.

**Event Details:**
- Date: December 5-6, 2025
- Venue: University Auditorium, Haridwar University Campus
- Timing: 9:00 AM - 5:00 PM

**Topics to be Covered:**
- Deep Learning and Neural Networks
- Natural Language Processing
- Computer Vision Applications
- AI in Healthcare and Education
- Ethics and Future of AI

**Speakers:**
- Dr. Rajesh Kumar, IIT Delhi
- Ms. Priya Sharma, Google AI Research
- Prof. Amit Singh, Haridwar University
- Industry leaders from TCS, Infosys, and Microsoft

**Registration:**
Faculty Members: ₹500
Research Scholars: ₹300
Students: ₹200

Register now to be part of this knowledge-sharing platform!''',
                'category': 'Events',
                'days_ago': 5
            },
            {
                'title': 'Students Win Gold Medal at National Robotics Championship 2025',
                'short_description': 'Haridwar University robotics team secures first place at the National Robotics Championship held in Bangalore, competing against 50+ teams.',
                'description': '''We are proud to announce that the Haridwar University Robotics Team has won the Gold Medal at the National Robotics Championship 2025 held in Bangalore from November 8-10, 2025.

**Team Members:**
- Rahul Verma (B.Tech CSE, 3rd Year) - Team Lead
- Anjali Gupta (B.Tech ECE, 3rd Year)
- Vikram Singh (B.Tech ME, 4th Year)
- Neha Sharma (B.Tech IT, 3rd Year)

**Faculty Mentor:**
Dr. Suresh Yadav, Professor, Department of Computer Science

**About the Competition:**
The National Robotics Championship is India's premier robotics competition that challenges students to design, build, and program robots to complete complex tasks. This year, over 50 teams from prestigious institutions across India participated.

**Our Achievement:**
Our team's robot, "Innovator-1", impressed the judges with its innovative design, efficient programming, and excellent performance in all three rounds - obstacle navigation, object manipulation, and autonomous decision-making.

The university congratulates the team and wishes them continued success in their future endeavors!''',
                'category': 'Achievements',
                'days_ago': 8
            },
            {
                'title': 'New Central Library Building Inaugurated with 50,000+ Books',
                'short_description': 'The state-of-the-art Central Library with modern facilities, digital resources, and spacious reading areas was inaugurated by Hon. Vice Chancellor.',
                'description': '''Haridwar University inaugurated its new Central Library building on November 10, 2025, marking a significant milestone in enhancing academic resources for students and faculty.

**Library Features:**
- Collection of over 50,000 books across various disciplines
- Digital library with access to international journals and e-books
- Spacious reading halls with 500+ seating capacity
- Individual study cabins for focused learning
- Computer lab with high-speed internet
- Audio-visual room for multimedia resources
- 24/7 access for research scholars

**Infrastructure Highlights:**
- Built on 15,000 sq. ft. area across 3 floors
- Air-conditioned and well-lit spaces
- Modern furniture and ergonomic seating
- RFID-based book management system
- Automated issue and return system

**Digital Resources:**
The library provides access to leading databases including:
- IEEE Xplore Digital Library
- Springer Nature Journals
- JSTOR Archive
- ScienceDirect
- ProQuest Database

The Vice Chancellor, Prof. Dr. R.K. Sharma, inaugurated the facility and emphasized the importance of reading and research in academic excellence.

Students and faculty are encouraged to make full use of these world-class facilities.''',
                'category': 'Campus Life',
                'days_ago': 6
            },
            {
                'title': 'Winter Break Schedule and Important Dates Announced',
                'short_description': 'University administration announces winter break schedule, examination dates, and important academic deadlines for December-January.',
                'description': '''The university administration has announced the winter break schedule and important academic dates for December 2025 - January 2026.

**Winter Break:**
- Start Date: December 24, 2025
- Resume Date: January 6, 2026
- Duration: 14 days

**End Semester Examinations:**
- Theory Exams: December 10-20, 2025
- Practical Exams: December 16-21, 2025
- Result Declaration: January 15, 2026

**Important Deadlines:**
- Last date for course withdrawal: November 30, 2025
- Internal assessment completion: December 5, 2025
- Examination form submission: November 25, 2025
- Re-evaluation application: January 20, 2026

**Next Semester:**
- Registration for new semester: January 7-10, 2026
- Classes begin: January 13, 2026
- Add/Drop period: January 13-20, 2026

**Notes:**
- Library will remain open during winter break (10 AM - 5 PM)
- Administrative offices will be closed on December 25 and January 1
- Hostels will remain open for students who wish to stay

Students are advised to plan accordingly and complete all pending academic requirements before the break.

For any queries, contact the academic section or visit the university website.''',
                'category': 'Announcements',
                'days_ago': 3
            },
            {
                'title': 'Faculty Development Program on Modern Teaching Pedagogies',
                'short_description': 'One-week FDP organized to enhance teaching skills using technology, innovative methods, and student-centric approaches.',
                'description': '''Haridwar University is conducting a Faculty Development Program (FDP) on "Modern Teaching Pedagogies and Educational Technology" from November 20-26, 2025.

**Program Objectives:**
- Enhance teaching effectiveness using modern pedagogies
- Integrate technology in classroom teaching
- Learn outcome-based education (OBE) practices
- Develop interactive and engaging course content
- Understand student psychology and motivation techniques

**Program Schedule:**
- Duration: 7 days (November 20-26, 2025)
- Timing: 9:30 AM - 4:30 PM
- Venue: Faculty Training Center, Academic Block-2

**Topics Covered:**
1. Flipped Classroom and Blended Learning
2. Using Learning Management Systems (LMS)
3. Creating Engaging Presentations and Videos
4. Assessment and Evaluation Techniques
5. Case Study and Problem-Based Learning
6. Research Methodology and Paper Writing

**Resource Persons:**
- Prof. Dr. Meera Verma, Educational Psychologist
- Dr. Anil Kumar, IIT Roorkee
- Mr. Sanjay Gupta, EdTech Specialist
- Internal faculty experts

**Participants:**
All teaching faculty members from various departments are participating. The program includes hands-on sessions, group activities, and practical demonstrations.

**Certificate:**
Participants will receive a certificate of completion from Haridwar University.

This initiative reflects the university's commitment to quality education and continuous faculty development.''',
                'category': 'Events',
                'days_ago': 1
            },
            {
                'title': 'Placement Drive: Leading IT Companies to Visit Campus',
                'short_description': 'Top IT companies including TCS, Infosys, Wipro, and Tech Mahindra scheduled for campus recruitment in December 2025.',
                'description': '''The Training and Placement Cell is pleased to announce campus placement drives by leading IT companies for the academic year 2025-26.

**Participating Companies:**
1. Tata Consultancy Services (TCS)
2. Infosys Limited
3. Wipro Technologies
4. Tech Mahindra
5. HCL Technologies
6. Cognizant Technology Solutions

**Schedule:**
- TCS: December 5-6, 2025
- Infosys: December 10-11, 2025
- Wipro: December 15-16, 2025
- Tech Mahindra: December 18-19, 2025
- Others: December 20-22, 2025

**Eligible Programs:**
- B.Tech (CSE, IT, ECE)
- MCA
- M.Tech (Computer Science)

**Job Profiles:**
- Software Engineer
- System Engineer
- Associate Consultant
- Business Analyst
- Quality Analyst

**Package Range:**
₹3.5 LPA to ₹7.0 LPA

**Selection Process:**
- Online Aptitude Test
- Technical Interview
- HR Interview

**Preparation Support:**
The placement cell is conducting daily preparation sessions covering:
- Aptitude and Reasoning
- Programming and Data Structures
- Database and Operating Systems
- Interview Skills and Resume Building

**Registration:**
Students must register through the placement portal by November 30, 2025.

**Requirements:**
- Minimum 60% aggregate (No active backlogs)
- Updated resume
- Professional attire for interviews

For more information, contact the Training and Placement Office.

Best wishes to all students!''',
                'category': 'Campus Life',
                'days_ago': 4
            },
            {
                'title': 'Research Scholar Publishes Paper in International Journal',
                'short_description': 'Ph.D. scholar from Department of Computer Science publishes research paper in prestigious SCI-indexed international journal.',
                'description': '''Haridwar University is proud to announce that Ms. Pooja Sharma, a Ph.D. scholar from the Department of Computer Science and Engineering, has published her research paper in a prestigious SCI-indexed international journal.

**Publication Details:**
- Title: "Deep Learning Based Intrusion Detection System for IoT Networks"
- Journal: IEEE Transactions on Network and Service Management
- Impact Factor: 4.758
- Publication Date: November 2025

**Research Supervisor:**
Prof. Dr. Ramesh Kumar Sharma
Professor & Head, Department of Computer Science and Engineering

**Research Abstract:**
The paper proposes a novel deep learning-based approach to detect cyber intrusions in Internet of Things (IoT) networks. The research addresses the growing security concerns in IoT ecosystems by developing an intelligent detection system that can identify various types of network attacks with high accuracy.

**Key Contributions:**
- Novel neural network architecture for IoT security
- Real-time intrusion detection with 98.5% accuracy
- Lightweight model suitable for resource-constrained IoT devices
- Comprehensive evaluation on standard datasets

**Recognition:**
This publication highlights the quality of research being conducted at Haridwar University and demonstrates our commitment to contributing to global knowledge in cutting-edge technologies.

**About the Scholar:**
Ms. Pooja Sharma is in the third year of her Ph.D. program. She has previously presented papers at several international conferences and has received the Best Paper Award at the International Conference on Cybersecurity 2024.

The university congratulates Ms. Sharma and her supervisor for this outstanding achievement and wishes them continued success in their research endeavors.''',
                'category': 'Achievements',
                'days_ago': 7
            },
            {
                'title': 'Sports Week 2025: Inter-College Championship Begins',
                'short_description': 'Annual Sports Week kicks off with participation from 500+ students across various indoor and outdoor sports categories.',
                'description': '''Haridwar University's Annual Sports Week 2025 commenced on November 13, 2025, with great enthusiasm and participation from students across all colleges.

**Event Duration:**
November 13-18, 2025

**Participating Students:**
Over 500 students from various colleges are competing in multiple sports categories.

**Sports Categories:**

**Outdoor Sports:**
- Cricket (Men & Women)
- Football
- Basketball
- Volleyball
- Athletics (Track & Field)
- Badminton

**Indoor Sports:**
- Table Tennis
- Chess
- Carrom
- Badminton (Indoor courts)

**Teams:**
- College of Engineering
- College of Management
- College of Pharmacy
- College of Computer Applications
- College of Agriculture

**Inaugural Ceremony:**
The Sports Week was inaugurated by Chief Guest Mr. Vijay Kumar, Former Indian Cricket Team Player, who motivated students to maintain a balance between academics and sports.

**Venue:**
University Sports Complex and Ground

**Daily Schedule:**
- Morning Session: 8:00 AM - 12:00 PM (Outdoor Sports)
- Evening Session: 3:00 PM - 6:00 PM (Indoor Sports & Finals)

**Prize Distribution:**
The closing ceremony on November 18, 2025, will include:
- Trophy for Overall Champion College
- Gold, Silver, Bronze medals for individual winners
- Certificates for all participants
- Best Athlete Awards (Male & Female)

**Current Standings:**
(To be updated daily on university website and notice boards)

The Sports Week aims to promote physical fitness, team spirit, and healthy competition among students. The entire university community is invited to support and cheer for their college teams.

Let the games begin! May the best team win!''',
                'category': 'Events',
                'days_ago': 3
            },
            {
                'title': 'New Scholarship Program Launched for Meritorious Students',
                'short_description': 'University announces merit-based scholarships worth ₹50 lakhs for deserving students. Applications open now.',
                'description': '''Haridwar University is delighted to announce the launch of a comprehensive Scholarship Program for meritorious and deserving students for the Academic Year 2025-26.

**Total Scholarship Amount:**
₹50,00,000 (Fifty Lakhs)

**Scholarship Categories:**

**1. Merit-Based Scholarships:**
- 90% and above: 100% tuition fee waiver
- 85-89%: 75% tuition fee waiver
- 80-84%: 50% tuition fee waiver
- 75-79%: 25% tuition fee waiver

**2. Sports Excellence Scholarship:**
- National Level: ₹1,00,000 per year
- State Level: ₹50,000 per year
- University Level: ₹25,000 per year

**3. Need-Based Scholarship:**
- For economically disadvantaged students
- Up to 100% fee waiver based on family income
- Annual income criteria: Below ₹3,00,000

**4. Research Scholarship:**
- For M.Tech and Ph.D. students
- ₹12,000 per month for Ph.D.
- ₹8,000 per month for M.Tech (Research)

**5. Girl Child Education Scholarship:**
- Special scholarship for female students
- 20% additional concession on tuition fees

**Eligibility Criteria:**
- Admission to any UG/PG program at Haridwar University
- Minimum attendance of 75% in previous academic year
- No disciplinary actions
- Good academic standing

**Application Process:**
1. Download application form from university website
2. Fill complete details with supporting documents
3. Submit to Scholarship Cell before December 31, 2025
4. Selection results will be announced by January 15, 2026

**Required Documents:**
- Previous academic marksheets
- Income certificate (for need-based)
- Sports achievement certificates (if applicable)
- Aadhar card and photographs
- Bank account details

**Renewal:**
Scholarships will be renewed annually based on academic performance (minimum CGPA 7.0) and attendance.

**Contact:**
Scholarship Cell
Email: scholarships@haridwaruniversity.edu.in
Phone: +91-1334-XXXXXX

This initiative reflects our commitment to making quality education accessible to all deserving students regardless of their financial background.

Apply now and pursue your dreams with Haridwar University!''',
                'category': 'Announcements',
                'days_ago': 1
            }
        ]

        self.stdout.write('\n📰 Creating News Items...')
        news_created = 0
        news_exists = 0
        
        for news_item in news_data:
            # Calculate publish date
            publish_date = timezone.now() - timedelta(days=news_item['days_ago'])
            
            news, created = News.objects.get_or_create(
                title=news_item['title'],
                defaults={
                    'slug': slugify(news_item['title']),
                    'short_description': news_item['short_description'],
                    'description': news_item['description'],
                    'category': categories[news_item['category']],
                    'publish_date': publish_date,
                    'is_active': True
                }
            )
            
            if created:
                news_created += 1
                self.stdout.write(f'   ✅ Created: {news.title[:60]}...')
            else:
                news_exists += 1
                self.stdout.write(f'   ⚠️  Exists: {news.title[:60]}...')

        # Summary
        self.stdout.write('\n' + '='*70)
        self.stdout.write(self.style.SUCCESS('✅ Data Seeding Complete!'))
        self.stdout.write(f'\n📊 Summary:')
        self.stdout.write(f'   Categories: {len(categories_data)} total')
        self.stdout.write(f'   News Items: {news_created} created, {news_exists} already existed')
        self.stdout.write(f'\n📝 Next Steps:')
        self.stdout.write(f'   1. Upload featured images through Django Admin')
        self.stdout.write(f'   2. Add gallery images to news items')
        self.stdout.write(f'   3. Access admin at: /admin/news/')
        self.stdout.write(f'   4. Test API at: /api/news/')
        self.stdout.write('='*70 + '\n')
