"""Stage 1: a local, read-only study-notes API using Python's standard library.

Run: python3 stage1.py
Open: http://127.0.0.1:8001/api/ask?q=What%20is%20a%20training%20set
"""

import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlsplit


NOTES = [
    {
        "title": "Training data",
        "url": "https://developers.google.com/machine-learning/crash-course/overfitting/dividing-datasets",
        "text": "A training set is the data a model uses to learn patterns. Keep validation and test examples separate when measuring generalization.",
    },
    {
        "title": "Retrieval",
        "url": "https://docs.langchain.com/oss/python/langchain/knowledge-base",
        "text": "Retrieval finds relevant source passages for a question. A RAG system then gives those passages to a model to help ground its answer.",
    },
    {
        "title": "Evaluation",
        "url": "https://developers.openai.com/api/docs/guides/evals",
        "text": "An evaluation set contains representative questions and expected outcomes. Run it again when the system changes.",
    },
]


def answer(question):
    """Return the best matching note, or admit when the notes do not answer."""
    terms = {word.strip(".,?!").lower() for word in question.split() if len(word) > 3}
    ranked = [
        (len(terms & set((note["title"] + " " + note["text"]).lower().split())), note)
        for note in NOTES
    ]
    score, note = max(ranked, key=lambda pair: pair[0])
    if score == 0:
        return {"answer": "I don't know from these notes.", "source": None}
    return {"answer": note["text"], "source": {"title": note["title"], "url": note["url"]}}


class Handler(BaseHTTPRequestHandler):
    def send_json(self, status, payload):
        body = json.dumps(payload).encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", "application/json; charset=utf-8")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_GET(self):
        path = urlsplit(self.path)
        if path.path != "/api/ask":
            return self.send_json(404, {"error": "Route not found"})
        question = parse_qs(path.query).get("q", [""])[0].strip()
        if not question or len(question) > 500:
            return self.send_json(400, {"error": "Provide q with 1–500 characters"})
        return self.send_json(200, answer(question))


if __name__ == "__main__":
    server = ThreadingHTTPServer(("127.0.0.1", 8001), Handler)
    print("Study API: http://127.0.0.1:8001/api/ask?q=What%20is%20a%20training%20set")
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        server.server_close()
