from flask import Flask, render_template, request, redirect, url_for, session
import pdfplumber
import os
from openai import OpenAI
from werkzeug.utils import secure_filename

app = Flask(__name__)

client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

UPLOAD_FOLDER = 'uploads'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def extract_resume_text(pdf_path):
    resume_text = ""
    with pdfplumber.open(pdf_path) as pdf:
        for page in pdf.pages:
            text = page.extract_text()
            if text:
                resume_text += text + "\n"
    return resume_text

def compare_resume_to_job(resume_text, job_text):
    prompt = (
        "Compare the following resume and job description.\n\n"
        "Resume:\n"
        f"{resume_text}\n\n"
        "Job Description:\n"
        f"{job_text}\n\n"
        "Please evaluate:\n"
        "- How well the resume matches the job description\n"
        "- Key skills that match or are missing\n"
        "- Areas for improvement or tailoring\n"
        "- Give an approximate percentage of matching between the resume and the Job description (0 - 100)"
        "If the job description or the resume contain anything that is not pertinent to resume analysis strictly ignore it and return 'non-pertinent information provided'"
        "If there is no job description just provide a overall analysis and constructive feedback of the resume" 
    )
    
    try:
        response = client.chat.completions.create(
            model="gpt-4",
            messages=[{"role": "user", "content": prompt}]
        )
        return response.choices[0].message.content
    except Exception as e:
        return f"Error analyzing resume: {str(e)}"

@app.route("/")
def index():
    return render_template("main.html")

@app.route("/loading")
def loading():
    # Clear processing flag when loading page is shown
    session['processing_complete'] = False
    return render_template("loading.html")

@app.route("/submit", methods=["POST"])
def submit():
    try:
        if "resume" not in request.files:
            return {"status": "error", "message": "No file uploaded"}, 400
        
        resume_file = request.files["resume"]
        job_description = request.form.get("job_description", "")
        
        if resume_file.filename == "":
            return {"status": "error", "message": "No selected file"}, 400
        
        # Mark as processing FIRST
        session['processing_complete'] = False
        session.modified = True  # Force session to save
        
        # Save the file
        filename = secure_filename(resume_file.filename)
        pdf_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        resume_file.save(pdf_path)

        # Extract and analyze
        resume_text = extract_resume_text(pdf_path)
        
        # Call the AI API (this is the slow part)
        result = compare_resume_to_job(resume_text, job_description)
        
        # Store result in session
        session['result'] = result
        session['filename'] = filename
        session['job_description'] = job_description
        session['processing_complete'] = True
        session.modified = True  # Force session to save
        
        print("Processing complete, session updated")
        return {"status": "success"}, 200
    except Exception as e:
        print(f"Error in submit: {e}")
        session['processing_complete'] = True  # Mark as complete even on error
        session['result'] = f"Error analyzing resume: {str(e)}"
        session.modified = True
        return {"status": "error", "message": str(e)}, 500

@app.route("/results")
def results():
    result = session.get('result', 'No analysis available')
    filename = session.get('filename', 'Unknown file')
    job_description = session.get('job_description', 'None provided')
    return render_template("results.html", result=result, filename=filename, job_description=job_description)

@app.route("/check_status")
def check_status():
    """Endpoint for loading page to check if processing is complete"""
    is_complete = session.get('processing_complete', False)
    has_result = 'result' in session
    print(f"DEBUG: processing_complete = {is_complete}, has_result = {has_result}")
    
    if is_complete:
        return {"status": "complete"}, 200
    else:
        return {"status": "processing"}, 202

if __name__ == "__main__":
    app.run(debug=True)