// frontend/src/services/fileParser.js
import * as pdfjsLib from 'pdfjs-dist';
import mammoth from 'mammoth';

pdfjsLib.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjsLib.version}/pdf.worker.min.js`;

export const parseFile = async (file) => {
    const text = await extractTextFromFile(file);
    return extractResumeData(text);
};

const extractTextFromFile = async (file) => {
    const fileType = file.type;
    
    if (fileType === 'application/pdf') {
        return await extractFromPDF(file);
    } else if (fileType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
        return await extractFromDOCX(file);
    } else {
        throw new Error('Unsupported file type. Please upload PDF or DOCX.');
    }
};

const extractFromPDF = async (file) => {
    const arrayBuffer = await file.arrayBuffer();
    const pdf = await pdfjsLib.getDocument({ data: arrayBuffer }).promise;
    let fullText = '';
    
    for (let i = 1; i <= pdf.numPages; i++) {
        const page = await pdf.getPage(i);
        const textContent = await page.getTextContent();
        const pageText = textContent.items.map(item => item.str).join(' ');
        fullText += pageText + '\n';
    }
    return fullText;
};

const extractFromDOCX = async (file) => {
    const arrayBuffer = await file.arrayBuffer();
    const result = await mammoth.extractRawText({ arrayBuffer });
    return result.value;
};

const extractResumeData = (text) => {
    const data = {};
    
    // Extract email
    const emailRegex = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/;
    const emailMatch = text.match(emailRegex);
    data.email = emailMatch ? emailMatch[0] : '';
    
    // Extract name (first non-empty line that's not an email)
    const lines = text.split('\n').filter(line => line.trim().length > 0);
    for (let line of lines) {
        if (!line.includes('@') && line.length < 50 && !line.match(/[0-9]/g)) {
            data.fullName = line.trim();
            break;
        }
    }
    
    // Extract skills (common tech skills)
    const commonSkills = ['JavaScript', 'Python', 'Java', 'React', 'Node.js', 'SQL', 'HTML', 'CSS', 'AWS', 'Docker', 'Kubernetes', 'TypeScript', 'PHP', 'Laravel', 'Vue', 'Angular', 'MongoDB', 'PostgreSQL', 'Git', 'REST API', 'GraphQL'];
    const foundSkills = [];
    commonSkills.forEach(skill => {
        if (text.toLowerCase().includes(skill.toLowerCase())) {
            foundSkills.push(skill);
        }
    });
    data.skills = foundSkills.join(', ');
    
    // Extract job title (look for common patterns)
    const jobTitlePatterns = /(?:as a|position of|role:|title:)\s+([A-Za-z\s]+(?:Developer|Engineer|Manager|Director|Analyst|Architect|Consultant|Specialist))/i;
    const titleMatch = text.match(jobTitlePatterns);
    data.jobTitle = titleMatch ? titleMatch[1].trim() : '';
    
    // Extract years of experience
    const yearPattern = /(\d+)\+?\s*(?:years?|yrs?)\s+of\s+experience/i;
    const yearMatch = text.match(yearPattern);
    data.yearsOfExperience = yearMatch ? yearMatch[1] : '';
    
    // Extract summary (first paragraph after name/contact)
    const paragraphs = text.split(/\n\s*\n/);
    for (let para of paragraphs) {
        if (para.length > 100 && para.length < 500 && !para.includes('@')) {
            data.summary = para.trim().substring(0, 300);
            break;
        }
    }
    
    return data;
};