from openai import OpenAI
import json

from database import settings

client = OpenAI(api_key=settings.OPENAI_API_KEY)

def parse_resume_content(text_content: str) -> dict:
    """
    Sends the resume text content to OpenAI to extract structured data.
    """
    prompt = f"""
    You are a resume parser. Extract the following information from the resume text provided below.
    Return the output in a strictly valid JSON format with the following keys:
    - name (string)
    - email (string)
    - phone (string)
    - skills (string, comma-separated)
    - experience_summary (string, brief summary of work experience)
    
    If a field is not found, set it to null.

    Resume Text:
    {text_content[:4000]}  # Truncate to avoid token limits if necessary
    """

    try:
        response = client.chat.completions.create(
            model="gpt-3.5-turbo", # Or gpt-4o if available/preferred
            messages=[
                {"role": "system", "content": "You are a helpful assistant that extracts data from resumes."},
                {"role": "user", "content": prompt}
            ],
            response_format={"type": "json_object"}
        )
        
        content = response.choices[0].message.content
        return json.loads(content)
    except Exception as e:
        print(f"Error parsing resume with OpenAI: {e}")
        return {}
