const mongoose = require('mongoose');
const NewsCategory = require('../models/NewsCategory');
const NewsSource = require('../models/NewsSource');
require('dotenv').config();

// Connect to MongoDB
const connectDB = async () => {
    try {
        await mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/recon_app');
        console.log('✅ Connected to MongoDB');
    } catch (error) {
        console.error('❌ MongoDB connection error:', error);
        process.exit(1);
    }
};

// Initialize news categories
const initCategories = async () => {
    try {
        console.log('📝 Initializing news categories...');
        
        const categories = [
            {
                name: 'Career and Skills',
                slug: 'career-and-skills',
                description: 'Career development, job opportunities, and skill enhancement',
                keywords: ['job', 'career', 'skill', 'employment', 'work', 'professional'],
                icon: '💼',
                color: '#3B82F6',
                sortOrder: 1
            },
            {
                name: 'Technology',
                slug: 'technology',
                description: 'Latest technology trends, software, and digital innovations',
                keywords: ['tech', 'software', 'programming', 'ai', 'digital', 'app'],
                icon: '💻',
                color: '#10B981',
                sortOrder: 2
            },
            {
                name: 'Startups and Innovation',
                slug: 'startups-and-innovation',
                description: 'Startup ecosystem, entrepreneurship, and business innovation',
                keywords: ['startup', 'innovation', 'entrepreneur', 'venture', 'funding'],
                icon: '🚀',
                color: '#F59E0B',
                sortOrder: 3
            },
            {
                name: 'Education',
                slug: 'education',
                description: 'Educational news, academic updates, and learning resources',
                keywords: ['education', 'school', 'university', 'student', 'learning'],
                icon: '🎓',
                color: '#8B5CF6',
                sortOrder: 4
            },
            {
                name: 'Sports',
                slug: 'sports',
                description: 'Sports news, matches, and athletic achievements',
                keywords: ['sport', 'football', 'basketball', 'cricket', 'olympic'],
                icon: '⚽',
                color: '#EF4444',
                sortOrder: 5
            },
            {
                name: 'Movies and Entertainment',
                slug: 'movies-and-entertainment',
                description: 'Entertainment industry, movies, music, and celebrity news',
                keywords: ['movie', 'film', 'entertainment', 'actor', 'music'],
                icon: '🎬',
                color: '#EC4899',
                sortOrder: 6
            },
            {
                name: 'Business and Economy',
                slug: 'business-and-economy',
                description: 'Business news, economic updates, and financial markets',
                keywords: ['business', 'economy', 'market', 'finance', 'investment'],
                icon: '📈',
                color: '#059669',
                sortOrder: 7
            },
            {
                name: 'Politics',
                slug: 'politics',
                description: 'Political news, government updates, and policy changes',
                keywords: ['politics', 'government', 'election', 'minister', 'policy'],
                icon: '🏛️',
                color: '#DC2626',
                sortOrder: 8
            },
            {
                name: 'Astrology',
                slug: 'astrology',
                description: 'Astrological insights, horoscopes, and cosmic updates',
                keywords: ['astrology', 'horoscope', 'zodiac', 'star', 'planet'],
                icon: '⭐',
                color: '#7C3AED',
                sortOrder: 9
            },
            {
                name: 'Health and Wellness',
                slug: 'health-and-wellness',
                description: 'Health news, medical updates, and wellness tips',
                keywords: ['health', 'medical', 'doctor', 'wellness', 'fitness'],
                icon: '🏥',
                color: '#10B981',
                sortOrder: 10
            },
            {
                name: 'Environment and Climate',
                slug: 'environment-and-climate',
                description: 'Environmental news, climate change, and sustainability',
                keywords: ['environment', 'climate', 'global warming', 'green', 'sustainable'],
                icon: '🌱',
                color: '#059669',
                sortOrder: 11
            },
            {
                name: 'Art and Culture',
                slug: 'art-and-culture',
                description: 'Cultural events, art exhibitions, and creative expressions',
                keywords: ['art', 'culture', 'museum', 'gallery', 'literature'],
                icon: '🎨',
                color: '#8B5CF6',
                sortOrder: 12
            },
            {
                name: 'Knowledge Bytes and Facts',
                slug: 'knowledge-bytes-and-facts',
                description: 'Interesting facts, scientific discoveries, and knowledge sharing',
                keywords: ['fact', 'knowledge', 'science', 'research', 'discovery'],
                icon: '🧠',
                color: '#6366F1',
                sortOrder: 13
            },
            {
                name: 'Jobs',
                slug: 'jobs',
                description: 'Job opportunities, recruitment news, and employment updates',
                keywords: ['job', 'career', 'employment', 'hiring', 'recruitment'],
                icon: '💼',
                color: '#3B82F6',
                sortOrder: 14
            }
        ];

        for (const categoryData of categories) {
            const existingCategory = await NewsCategory.findOne({ slug: categoryData.slug });
            if (!existingCategory) {
                const category = new NewsCategory(categoryData);
                await category.save();
                console.log(`✅ Created category: ${categoryData.name}`);
            } else {
                console.log(`⚠️ Category already exists: ${categoryData.name}`);
            }
        }

        console.log('✅ News categories initialized successfully');
    } catch (error) {
        console.error('❌ Error initializing categories:', error);
    }
};

// Initialize news sources
const initSources = async () => {
    try {
        console.log('📝 Initializing news sources...');
        
        const sources = [
            {
                name: 'NewsAPI',
                type: 'newsapi',
                baseUrl: 'https://newsapi.org/v2',
                endpoint: '/everything',
                apiKey: '4a039be72844448a9adcd837fb920bbc',
                categories: [
                    'career-and-skills',
                    'technology',
                    'startups-and-innovation',
                    'education',
                    'sports',
                    'movies-and-entertainment',
                    'business-and-economy',
                    'politics',
                    'health-and-wellness',
                    'environment-and-climate',
                    'art-and-culture',
                    'knowledge-bytes-and-facts',
                    'jobs'
                ],
                rateLimit: {
                    requestsPerMinute: 100,
                    requestsPerHour: 1000
                },
                timeout: 30000,
                retryAttempts: 3,
                retryDelay: 1000
            },
            {
                name: 'Currents API',
                type: 'currents',
                baseUrl: 'https://api.currentsapi.services/v1',
                endpoint: '/search',
                apiKey: 'OwUf8-lpvINu6cfU20IfxPNxlEO9oYYZnch-3l-k6afTJ0Xu',
                categories: [
                    'career-and-skills',
                    'technology',
                    'startups-and-innovation',
                    'education',
                    'sports',
                    'movies-and-entertainment',
                    'business-and-economy',
                    'politics',
                    'health-and-wellness',
                    'environment-and-climate',
                    'art-and-culture',
                    'knowledge-bytes-and-facts',
                    'jobs'
                ],
                rateLimit: {
                    requestsPerMinute: 60,
                    requestsPerHour: 500
                },
                timeout: 30000,
                retryAttempts: 3,
                retryDelay: 1000
            }
        ];

        for (const sourceData of sources) {
            const existingSource = await NewsSource.findOne({ name: sourceData.name });
            if (!existingSource) {
                const source = new NewsSource(sourceData);
                await source.save();
                console.log(`✅ Created source: ${sourceData.name}`);
            } else {
                console.log(`⚠️ Source already exists: ${sourceData.name}`);
            }
        }

        console.log('✅ News sources initialized successfully');
    } catch (error) {
        console.error('❌ Error initializing sources:', error);
    }
};

// Main initialization function
const initNewsData = async () => {
    try {
        await connectDB();
        await initCategories();
        await initSources();
        console.log('🎉 News data initialization completed successfully!');
        process.exit(0);
    } catch (error) {
        console.error('❌ Initialization failed:', error);
        process.exit(1);
    }
};

// Run initialization if this file is executed directly
if (require.main === module) {
    initNewsData();
}

module.exports = { initNewsData, initCategories, initSources };
