"""Lesson 8: generating the answer.

ChatClient talks to any OpenAI-compatible /v1/chat/completions endpoint: Ollama,
LM Studio, llama.cpp's server, vLLM, or a hosted provider. extractive_answer is an
offline fallback that picks the best-matching sentences from the sources, so the
pipeline runs end to end without a model.
"""
from __future__ import annotations

import json
import os
import urllib.request

from .chunking import split_sentences
from .documents import Chunk
from .text import terms


class ChatClient:
    def __init__(self, base_url: str | None = None, model: str | None = None, api_key: str | None = None,
                 timeout: float = 120):
        self.base_url = (base_url or os.environ.get("RAG_BASE_URL", "http://localhost:11434/v1")).rstrip("/")
        self.model = model or os.environ.get("RAG_MODEL", "llama3.2")
        self.api_key = api_key if api_key is not None else os.environ.get("RAG_API_KEY", "")
        self.timeout = timeout

    def chat(self, system: str, user: str, temperature: float = 0.0) -> str:
        body = json.dumps({"model": self.model, "temperature": temperature,
                           "messages": [{"role": "system", "content": system},
                                        {"role": "user", "content": user}]}).encode()
        headers = {"Content-Type": "application/json"}
        if self.api_key:
            headers["Authorization"] = f"Bearer {self.api_key}"
        req = urllib.request.Request(f"{self.base_url}/chat/completions", data=body, headers=headers, method="POST")
        with urllib.request.urlopen(req, timeout=self.timeout) as resp:
            return json.load(resp)["choices"][0]["message"]["content"]


def extractive_answer(question: str, chunks: list[Chunk], max_sentences: int = 2,
                      min_coverage: float = 0.5) -> str:
    """Pick the sentences that share the most terms with the question, and cite their sources.

    A sentence must contain at least `min_coverage` of the question's terms; otherwise we
    answer "I don't know" instead of returning something loosely related.
    """
    q = set(terms(question))
    scored = []
    for n, chunk in enumerate(chunks, start=1):
        body = chunk.text
        section = chunk.metadata.get("section")
        if section and body.startswith(section + "\n"):
            body = body[len(section) + 1:]  # skip the heading line added by chunk_markdown
        for sentence in split_sentences(body):
            overlap = len(q & set(terms(sentence)))
            if q and overlap / len(q) >= min_coverage:
                scored.append((overlap, -n, sentence, n))
    if not scored:
        return "I don't know based on the provided documents."
    scored.sort(reverse=True)
    picked = scored[:max_sentences]
    return " ".join(f"{s} [{n}]" for _, _, s, n in picked)
