from __future__ import annotations

from google.genai import types

from app.config import get_settings
from app.vertex import get_client

GROUNDING_SYSTEM_PROMPT = (
    "You are an internal legal AI for MLT Aikins. "
    "Answer the user's question based strictly on the provided document chunks. "
    "If the context does not contain the answer, say "
    "'This is not covered in the provided document.'"
)


def synthesize_answer(question: str, chunks: list[str]) -> str:
    numbered = "\n\n".join(
        f"[Chunk {i}]\n{chunk.strip()}" for i, chunk in enumerate(chunks, start=1)
    )
    user_prompt = (
        "Use only the document chunks below. Do not rely on general legal knowledge. "
        "Do not invent facts, parties, dates, or citations. "
        "If the chunks are insufficient, reply with the required fallback sentence and nothing else.\n\n"
        f"DOCUMENT CHUNKS:\n{numbered}\n\n"
        f"QUESTION:\n{question.strip()}\n\n"
        "ANSWER:"
    )
    settings = get_settings()
    response = get_client().models.generate_content(
        model=settings.vertex_generation_model,
        contents=user_prompt,
        config=types.GenerateContentConfig(
            system_instruction=GROUNDING_SYSTEM_PROMPT,
            temperature=0.1,
            max_output_tokens=1024,
        ),
    )
    text = (response.text or "").strip()
    if not text:
        return "This is not covered in the provided document."
    return text
