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 professional 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:
    - is_resume (boolean, true if the text appears to be a resume/CV, false otherwise)
    - name (string)
    - email (string)
    - phone (string)
    - location (string)
    - summary (string)
    - experience (string, format as a perfect list of bullet points using '-' or '•')
    - education (string, format as a perfect list of bullet points using '-' or '•')
    - skills (string, format as a perfect list of bullet points using '-' or '•')
    - certifications (string, format as a perfect list of bullet points using '-' or '•')
    - languages (string, format as a perfect list of bullet points using '-' or '•')
    - projects (string, format as a perfect list of bullet points using '-' or '•'. Thoroughly scan for standalone 'Projects' sections, 'Academic Projects', 'Personal Projects', or key projects mentioned within 'Professional Experience'. Extract all relevant project details.)
    - others (string, format as a perfect list of bullet points. Extract ALL other information present in the resume that does not fit into the categories above, such as Awards, Hobbies, Volunteering, References, Publications, etc.)
    - linkedin_url (string)
    - github_url (string)
    
    CRITICAL: For experience, education, skills, certifications, languages, projects, and others, ensure the output is well-structured with clear, perfect bullet points. If a field is not found, set it to null.

    Resume Text:
    {text_content[:15000]} 
    """

    try:
        response = client.chat.completions.create(
            model="gpt-4o-mini", 
            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 {}

def match_resume_to_jd(resume_text: str, jd_text: str) -> dict:
    """
    Compares a resume against a JD and returns a score and pitch.
    """
    prompt = f"""
    You are an expert HR recruiter. Compare the following Resume against the Job Description (JD).
    
    Return a strictly valid JSON with:
    - score (integer, 0-100)
    - pitch (string, exactly 2 sentences explaining why they are a good fit)
    - missing_skills (list of strings)
    
    JD: {jd_text[:5000]}
    
    Resume: {resume_text[:10000]}
    """
    try:
        response = client.chat.completions.create(
            model="gpt-4o-mini",
            messages=[{"role": "user", "content": prompt}],
            response_format={"type": "json_object"}
        )
        return json.loads(response.choices[0].message.content)
    except Exception as e:
        print(f"Error matching JD: {e}")
        return {"score": 0, "pitch": "Error during matching.", "missing_skills": []}

def bulk_rank_resumes(jd_text: str, resumes_data: list) -> list:
    """
    Ranks multiple resumes against a JD in a single LLM call for efficiency.
    Returns list of dicts with: id, score, pitch, missing_skills.
    """
    # Limit batch size to avoid token limits (rudimentary check)
    # If list is huge, we'd need to chunk it. Assuming < 20 resumes for this MVP.
    
    prompt = f"""
    You are an expert technical recruiter. 
    JOB DESCRIPTION / ROLE:
    "{jd_text}"
    
    CANDIDATES:
    {json.dumps(resumes_data)}
    
    INSTRUCTIONS:
    1. Analyze each candidate against the Job Description.
    2. Assign a relevance score (0-100).
    3. Write a 'pitch' (2 sentences explaining the fit).
    4. List 'missing_skills' (key skills from JD that are absent).
    5. Return a JSON object with a key "rankings" containing a list of objects.
       Each object MUST verify the 'id' from the candidate input.
       
    Output Schema:
    {{
        "rankings": [
            {{
                "id": <id>,
                "score": <int>,
                "pitch": <string>,
                "missing_skills": [<string>]
            }}
        ]
    }}
    """
    
    try:
        response = client.chat.completions.create(
            model="gpt-4o-mini",
            messages=[
                {"role": "system", "content": "You are a precise ranking assistant. Output JSON only."},
                {"role": "user", "content": prompt}
            ],
            response_format={"type": "json_object"}
        )
        content = response.choices[0].message.content
        return json.loads(content).get("rankings", [])
    except Exception as e:
        print(f"Error in bulk ranking: {e}")
        return []
