import os

def answer_with_llm(question, context):
    """
    - Jika OPENAI_API_KEY tersedia → gunakan OpenAI GPT
    - Jika tidak → fallback pakai context mentah
    """

    key = os.environ.get("OPENAI_API_KEY")

    # Jika ada OpenAI API → gunakan
    if key:
        try:
            import openai
            openai.api_key = key

            prompt = (
                "Jawab singkat berdasarkan konteks berikut:\n\n"
                f"{context}\n\n"
                f"Pertanyaan: {question}\n\n"
                "Berikan jawaban padat dan jelaskan pasal jika tersedia."
            )

            resp = openai.ChatCompletion.create(
                model="gpt-3.5-turbo",
                messages=[{"role": "user", "content": prompt}],
                max_tokens=300,
                temperature=0.0
            )

            return resp.choices[0].message.content.strip()

        except Exception as e:
            # Tidak ADA escape karakter bermasalah di sini
            return f"[LLM OpenAI error: {str(e)}]\n\nContext:\n{context[:1000]}"

    # Tanpa API Key → fallback
    return "" + context[:1500]
