"""cine-47 (from cine-10): a real, tiny test of Contextual Retrieval, run on this PC (no API).

Four short quarterly reports (made-up companies), split into chunks. One question. Retrieval by cosine similarity of
sentence embeddings (all-MiniLM-L6-v2, Apache-2.0), first on the plain chunks, then on the same chunks with a short
context line prepended. The context lines are written by Claude Haiku (through the Claude Code CLI, run in an empty
scratch folder) from the whole document and the chunk, with the wording of Anthropic's published prompt.
Writes raw/run.json and prints the ranking before and after.

    /tmp/cine10-venv/bin/python demo/rag_demo.py
"""
import json
import os

import torch
from transformers import AutoModel, AutoModelForCausalLM, AutoTokenizer

HERE = os.path.dirname(os.path.abspath(__file__))
DOCS = {
    "Kestrel Air, Q2 2024 report": [
        "Kestrel Air quarterly report, Q2 2024. Kestrel Air is a regional airline flying 41 routes from Leeds and Bristol.",
        "The company's revenue grew by 3% over the previous quarter, to £212 million.",
        "Fuel costs fell 6%, and two new routes opened in June.",
    ],
    "Kestrel Air, Q1 2024 report": [
        "Kestrel Air quarterly report, Q1 2024. Winter demand stayed soft across the network.",
        "The company's revenue grew by 5% over the previous quarter, to £206 million.",
        "One aircraft was retired and a pilot training centre opened.",
    ],
    "Larkspur Robotics, Q2 2024 report": [
        "Larkspur Robotics quarterly report, Q2 2024. Larkspur builds warehouse robots.",
        "The company's revenue grew by 11% over the previous quarter, to $48 million.",
        "Headcount rose to 640 and a new factory site was chosen in Ohio.",
    ],
    "Brightwell Foods, Q2 2024 report": [
        "Brightwell Foods quarterly report, Q2 2024. Brightwell makes frozen meals.",
        "Revenue fell by 2% over the previous quarter, to €95 million.",
        "Two product lines were discontinued.",
    ],
}
QUESTION = "How much did Kestrel Air's revenue grow in Q2 2024?"
ANSWER = ("Kestrel Air, Q2 2024 report", 1)

PROMPT = ("<document>\n{doc}\n</document>\nHere is the chunk we want to situate within the whole document\n<chunk>\n{chunk}\n"
          "</chunk>\nPlease give a short succinct context to situate this chunk within the overall document for the purposes "
          "of improving search retrieval of the chunk. Answer only with the succinct context and nothing else.")

etok = AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
enc = AutoModel.from_pretrained("sentence-transformers/all-MiniLM-L6-v2").eval()


def embed(texts):
    b = etok(texts, padding=True, truncation=True, max_length=256, return_tensors="pt")
    with torch.no_grad():
        o = enc(**b).last_hidden_state
    m = b["attention_mask"].unsqueeze(-1)
    return torch.nn.functional.normalize((o * m).sum(1) / m.sum(1), dim=-1)


def rank(chunks):
    q = embed([QUESTION])[0]
    e = embed([c["text"] for c in chunks])
    s = (e @ q).tolist()
    order = sorted(range(len(chunks)), key=lambda i: -s[i])
    return [(chunks[i]["doc"], chunks[i]["i"], round(s[i], 3), chunks[i]["text"]) for i in order]


import subprocess
import tempfile

SCRATCH = tempfile.mkdtemp(prefix="cine47-ctx-")
MODELS = set()


def context(doc_name, doc, chunk):
    prompt = PROMPT.format(doc=doc_name + "\n" + "\n".join(doc), chunk=chunk)
    r = subprocess.run(["claude", "-p", prompt, "--model", "haiku", "--output-format", "json"], cwd=SCRATCH,
                       capture_output=True, text=True, timeout=180)
    j = json.loads(r.stdout)
    MODELS.update(j.get("modelUsage", {}).keys())
    return j["result"].strip()


plain = [{"doc": d, "i": i, "text": c} for d, cs in DOCS.items() for i, c in enumerate(cs)]
ctx = []
for d, cs in DOCS.items():
    for i, c in enumerate(cs):
        line = context(d, cs, c)
        ctx.append({"doc": d, "i": i, "context": line, "text": line + " " + c})
before, after = rank(plain), rank(ctx)


def hit(r):
    return next(k for k, x in enumerate(r) if (x[0], x[1]) == ANSWER) + 1


run = {"question": QUESTION, "answer_chunk": ANSWER, "embedder": "sentence-transformers/all-MiniLM-L6-v2",
       "context_writer": "Claude Haiku via Claude Code -p (models used: " + ", ".join(sorted(MODELS)) + ")", "prompt": PROMPT,
       "contexts": [{"doc": c["doc"], "i": c["i"], "context": c["context"]} for c in ctx],
       "before": before, "after": after, "rank_before": hit(before), "rank_after": hit(after)}
os.makedirs(os.path.join(HERE, "raw"), exist_ok=True)
json.dump(run, open(os.path.join(HERE, "raw", "run.json"), "w"), indent=1, ensure_ascii=False)
print("Q:", QUESTION)
print("plain top 3:")
for x in before[:3]:
    print("  ", x)
print("contextual top 3:")
for x in after[:3]:
    print("  ", x)
print("right chunk rank: before", run["rank_before"], "after", run["rank_after"])
for c in ctx:
    print("CTX", c["doc"], c["i"], "|", c["context"])
