import google.generativeai as genai
import json
import os

genai.configure(api_key=os.environ.get("GEMINI_API_KEY"))

ROAST_SYSTEM_PROMPT = """You are "RoastBot 3000", a witty but supportive career coach who gives resume feedback in a comedy roast style.

RULES:
1. Be funny and playful — NEVER mean, discouraging, or offensive.
2. Every roast line must end with a concrete, actionable suggestion.
3. Tone: like a supportive senior engineer poking fun but genuinely rooting for you.
4. Generate exactly 6 lines. The last line MUST be a genuine compliment.
5. Never mention age, gender, race, appearance, or anything personal.
6. Each line should be 1–3 sentences max.
7. Return ONLY a valid JSON array of 6 strings, no preamble, no markdown backticks, no explanation."""

_model = None

def get_model():
    global _model
    if _model is None:
        _model = genai.GenerativeModel(
            model_name="gemini-2.5-flash",
            system_instruction=ROAST_SYSTEM_PROMPT,
            generation_config={"response_mime_type": "application/json"},
        )
    return _model

def generate_roast(parsed: dict, ats_score: int) -> dict:
    skills = ", ".join(parsed.get("skills", [])[:8]) or "none found"
    project_count = len(parsed.get("projects", []))
    exp_count = len(parsed.get("experience", []))
    cert_count = len(parsed.get("certifications", []))

    user_prompt = f"""Roast this resume:
Name: {parsed.get("name", "Unknown")}
ATS Score: {ats_score}/100
Skills listed: {skills}
Number of projects: {project_count}
Work experience entries: {exp_count}
Certifications: {cert_count}
Education: {parsed.get("education", [{}])[0].get("institution", "Not found") if parsed.get("education") else "Not found"}

Generate 6 roast lines as a JSON array of strings."""

    model = get_model()
    response = model.generate_content(user_prompt)

    raw = response.text.strip()
    raw = raw.replace("```json", "").replace("```", "").strip()
    lines = json.loads(raw)

    return {"lines": lines}