"""Resume tools — extract structured data from PDF/DOCX resumes."""
import os
import re

from docx import Document
from pdfminer.high_level import extract_text as extract_pdf_text

KNOWN_SKILLS = [
    "python", "django", "fastapi", "react", "next.js", "javascript", "typescript",
    "sql", "postgresql", "mysql", "aws", "docker", "kubernetes", "node", "redis",
    "celery", "git", "linux",
]


def extract_resume_data(file_path: str) -> dict:
    """Extract skills, experience years and a bio summary from a PDF or DOCX resume."""
    ext = os.path.splitext(file_path)[1].lower()
    try:
        if ext == ".pdf":
            text = extract_pdf_text(file_path)
        elif ext == ".docx":
            doc = Document(file_path)
            text = "\n".join(para.text for para in doc.paragraphs)
        else:
            return {"success": False, "error": "Unsupported file format. Use PDF or DOCX."}

        text_lower = text.lower()
        found_skills = [s.capitalize() for s in KNOWN_SKILLS if s in text_lower]

        experience_years = 0.0
        match = re.search(r"(\d+(?:\.\d+)?)\s*\+?\s*year", text_lower)
        if match:
            experience_years = float(match.group(1))

        return {
            "success": True,
            "data": {
                "skills": ", ".join(found_skills),
                "experience_years": experience_years,
                "bio_summary": text[:300].strip() + "...",
            },
            "message": "Resume parsed successfully",
        }
    except Exception as e:
        return {"success": False, "error": str(e)}
