import httpx
import json
import re
from sqlalchemy.orm import Session

from models.api_modal import LLMSettings

GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"

def get_groq_settings(db: Session):
    settings = db.query(LLMSettings).first()
    if not settings:
        raise Exception("Groq API key and model not set in DB")
    return settings.api_key, settings.model

def parse_resume_with_groq(resume_text: str, db: Session) -> dict:
    api_key, model = get_groq_settings(db)
    prompt = f"""
Extract the following fields from this resume text as JSON:
first_name, last_name, email, contact, address, education (list of objects with level, institution_name, percentage_or_cgpa, address, is_pursuing), experience (list of objects with job_title, company_name, duration_from, duration_to, description), skills (list of strings).

Resume text:
\"\"\"
{resume_text}
\"\"\"
"""
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }
    data = {
        "model": model,
        "messages": [
            {"role": "system", "content": "You are a helpful assistant that extracts structured data from resumes."},
            {"role": "user", "content": prompt}
        ],
        "temperature": 0.2,
        "max_tokens": 1024
    }
    with httpx.Client(timeout=60) as client:
        response = client.post(GROQ_API_URL, headers=headers, json=data)
        response.raise_for_status()
        result = response.json()
        content = result["choices"][0]["message"]["content"]
        try:
            parsed = json.loads(content)
        except Exception:
            match = re.search(r"\{.*\}", content, re.DOTALL)
            parsed = json.loads(match.group(0)) if match else {}
        return parsed