const fs = require('fs');
const path = require('path');
const dotenv = require('dotenv');

// Load env vars
dotenv.config();

// Connect to DB
const db = require('../src/db');

const EXPORT_FILE = path.join(__dirname, '../blog_posts_export.txt');
const START_LINE = 3411; // 0-indexed, so 3412 is index 3411

async function importBlogs() {
    try {
        console.log('Reading export file...');
        const fileContent = fs.readFileSync(EXPORT_FILE, 'utf-8');
        const lines = fileContent.split('\n');
        
        console.log(`Total lines: ${lines.length}`);
        
        // Slice from the start line
        const content_toProcess = lines.slice(START_LINE).join('\n');
        
        // Split into posts
        // The separator is ============================================================
        const chunks = content_toProcess.split('============================================================');
        
        console.log(`Found ${chunks.length} potential chunks.`);
        
        let importedCount = 0;
        
        for (const chunk of chunks) {
            if (!chunk.trim()) continue;
            
            // Extract fields
            const titleMatch = chunk.match(/TITLE:\s*(.*)/);
            const slugMatch = chunk.match(/SLUG:\s*(.*)/);
            const dateMatch = chunk.match(/DATE:\s*(.*)/);
            const categoryMatch = chunk.match(/CATEGORY:\s*(.*)/);
            
            // Content starts after "--- CONTENT (HTML) ---"
            const contentParts = chunk.split('--- CONTENT (HTML) ---');
            
            if (!titleMatch || !slugMatch || contentParts.length < 2) {
                // Not a valid post chunk or empty
                continue;
            }
            
            const title = titleMatch[1].trim();
            const slug = slugMatch[1].trim();
            const dateStr = dateMatch ? dateMatch[1].trim() : new Date().toISOString();
            const category = categoryMatch ? categoryMatch[1].trim() : 'General';
            const content = contentParts[1].trim();
            
            // Post ID check (optional, but good for logs)
            const postNumMatch = chunk.match(/POST #(\d+)/);
            const postNum = postNumMatch ? postNumMatch[1] : 'Unknown';
            
            console.log(`Processing Post #${postNum}: ${title}`);
            
            // Formatting Date
            let created_at = new Date(dateStr);
            if (isNaN(created_at.getTime())) {
                console.log(`  Invalid date "${dateStr}", using NOW.`);
                created_at = new Date();
            }
            
            // Check for duplicate slug
            const check = await db.query("SELECT id FROM blog_posts WHERE slug = ?", [slug]);
            if (check.rows.length > 0) {
                console.log(`  Skipping: Slug "${slug}" already exists.`);
                continue;
            }
            
            // Insert
            await db.query(
                `INSERT INTO blog_posts 
                (title, slug, content, excerpt, author_id, status, category, created_at, seo_title, seo_description) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
                [
                    title,
                    slug,
                    content,
                    '', // Excerpt empty for now
                    1, // Default Admin ID
                    'draft', // Always draft
                    category,
                    created_at,
                    title, // Default SEO title
                    '' // Default SEO Desc
                ]
            );
            
            importedCount++;
            console.log(`  Imported successfully.`);
        }
        
        console.log(`\nImport Complete! Imported ${importedCount} posts.`);
        process.exit(0);
        
    } catch (error) {
        console.error('Fatal Error:', error);
        process.exit(1);
    }
}

importBlogs();
