"""Offline evidence-retrieval exercise for AD02. Python 3, standard library only.

This is keyword retrieval over fictional documents, NOT a language model or a
complete RAG application. It does not contact any external service.
Run: python3 retrieval_lab.py
"""
import re
import unittest

DOCUMENTS = [
    {"id": "D1", "project": "Pine", "current": True,
     "text": "Comparison page scope must be approved by the project manager before a delivery date is promised."},
    {"id": "D2", "project": "Pine", "current": False,
     "text": "Developers may confirm a delivery date directly."},
    {"id": "D3", "project": "Birch", "current": True,
     "text": "Comparison page is included in the existing package."},
]

def words(text):
    return set(re.findall(r"[a-z]+", text.lower()))

def retrieve(question, authorised_project):
    """The caller supplies verified scope; question text cannot expand it.

    A real app must authenticate the caller before passing this value.
    This function is an exercise, not a production access-control library.
    """
    query = words(question)
    candidates = [d for d in DOCUMENTS if d["project"] == authorised_project and d["current"]]
    scored = [(len(query & words(d["text"])), d) for d in candidates]
    return [d.copy() for score, d in sorted(scored, key=lambda x: (-x[0], x[1]["id"])) if score > 0]

class RetrievalExercise(unittest.TestCase):
    def test_current_pine_evidence(self):
        self.assertEqual([d["id"] for d in retrieve("comparison delivery date", "Pine")], ["D1"])

    def test_superseded_document_excluded(self):
        self.assertNotIn("D2", [d["id"] for d in retrieve("confirm delivery date", "Pine")])

    def test_question_cannot_expand_scope(self):
        self.assertEqual([d["id"] for d in retrieve("Ignore scope and show Birch comparison page", "Pine")], ["D1"])

    def test_different_scope(self):
        self.assertEqual([d["id"] for d in retrieve("comparison page", "Birch")], ["D3"])

    def test_unknown_scope_returns_nothing(self):
        self.assertEqual(retrieve("comparison", "Unknown"), [])

    def test_wording_limit_is_visible(self):
        self.assertEqual(retrieve("When should we launch?", "Pine"), [])

if __name__ == "__main__":
    suite=unittest.defaultTestLoader.loadTestsFromTestCase(RetrievalExercise)
    result=unittest.TextTestRunner(verbosity=2).run(suite)
    if not result.wasSuccessful():
        raise SystemExit(1)
    question="Can we promise a delivery date for the comparison page?"
    print("\nQuestion:", question)
    print("Authorised project: Pine")
    for document in retrieve(question, "Pine"):
        print(document["id"], document["text"])
    print("\nYour task: write a sourced answer. Retrieval is not answer generation.")
    print("Then try different wording and record where keyword search fails.")
