"""Deterministic classroom example. Run with Python 3.10+ without a network."""

from copy import deepcopy
from dataclasses import dataclass
import hashlib
import json
from pathlib import Path


PARSER_VERSION = "json-pages-v1"
SPLITTER_VERSION = "nonempty-lines-v1"
FIXTURE = Path(__file__).with_name("栖松图书馆_合成语料_V0.1.json")


@dataclass(frozen=True)
class Span:
    doc_id: str
    version: int
    page: int
    start: int
    end: int

    def key(self):
        return f"{self.doc_id}@{self.version}:p{self.page}[{self.start},{self.end})"


@dataclass(frozen=True)
class Chunk:
    chunk_id: str
    source: Span
    lexical_text: str


@dataclass(frozen=True)
class Snapshot:
    version: int
    chunks: tuple[Chunk, ...]


def source_hash(document):
    canonical = json.dumps(document, sort_keys=True, ensure_ascii=False)
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def ingest(document):
    chunks = []
    for page in document["pages"]:
        start = 0
        for line in page["text"].splitlines(keepends=True):
            content = line.rstrip("\r\n")
            if content.strip():
                span = Span(document["doc_id"], document["doc_version"], page["page"], start, start + len(content))
                chunk_id = f"{span.key()}/{PARSER_VERSION}/{SPLITTER_VERSION}"
                chunks.append(Chunk(chunk_id, span, " ".join(content.casefold().split())))
            start += len(line)
    return tuple(chunks)


class Library:
    def __init__(self, documents):
        self.raw = {(doc["doc_id"], doc["doc_version"]): deepcopy(doc) for doc in documents}
        self.current = {doc["doc_id"]: doc["doc_version"] for doc in documents}
        self.active = Snapshot(1, tuple(chunk for doc in documents for chunk in ingest(doc)))

    def publish(self, document):
        doc_id = document["doc_id"]
        revision = document["doc_version"]
        latest = self.current.get(doc_id, 0)
        if revision == latest:
            if source_hash(document) != source_hash(self.raw[doc_id, revision]):
                raise ValueError("content changed under an existing document revision")
            return self.active
        if revision < latest:
            raise ValueError("stale document revision")
        replacements = ingest(document)
        other = tuple(chunk for chunk in self.active.chunks if chunk.source.doc_id != doc_id)
        candidate = Snapshot(self.active.version + 1, other + replacements)
        self.raw[doc_id, revision] = deepcopy(document)
        self.current[doc_id] = revision
        self.active = candidate
        return candidate

    def readable(self, span, role):
        source_roles = self.raw[span.doc_id, span.version]["roles"]
        current_roles = self.raw[span.doc_id, self.current[span.doc_id]]["roles"]
        return role in source_roles and role in current_roles

    def source_text(self, span, role):
        if not self.readable(span, role):
            raise PermissionError(span.doc_id)
        doc = self.raw[span.doc_id, span.version]
        page = next(page for page in doc["pages"] if page["page"] == span.page)
        assert 0 <= span.start < span.end <= len(page["text"])
        return page["text"][span.start:span.end]


def retrieve(library, snapshot, role, terms, k):
    candidates = []
    for chunk in snapshot.chunks:
        if library.readable(chunk.source, role):
            matches = sum(term.casefold() in chunk.lexical_text for term in terms)
            if matches:
                candidates.append((chunk, matches))
    candidates.sort(key=lambda result: (-result[1], result[0].chunk_id))
    return candidates[:k]


def rerank(candidates, anchors):
    def score(result):
        chunk, matches = result
        eligible = chunk.lexical_text.startswith("规则：") or " | " in chunk.lexical_text
        exact_anchor = any(anchor.casefold() in chunk.lexical_text for anchor in anchors)
        return (-int(eligible and exact_anchor), -matches, chunk.chunk_id)

    return [chunk for chunk, _ in sorted(candidates, key=score)]


def quoted_answer_mock(context, anchors):
    evidence = []
    for anchor in anchors:
        for item in context:
            text = item["source_text"]
            applicable = text.startswith("规则：") or " | " in text
            if applicable and anchor.casefold() in text.casefold():
                evidence.append(item)
                break
        else:
            return {"status": "abstain", "evidence": []}
    return {"status": "quoted_mock", "evidence": evidence}


def ask(library, question, terms, anchors, role="visitor", k=3, budget=1):
    snapshot = library.active
    candidates = retrieve(library, snapshot, role, terms, k)
    context = [
        {"citation": chunk.source.key(), "source_text": library.source_text(chunk.source, role)}
        for chunk in rerank(candidates, anchors)[:budget]
    ]
    return {
        "question": question,
        "index_version": snapshot.version,
        "candidate_limit": k,
        "context_limit": budget,
        "retrieved": [{"citation": c.source.key(), "term_matches": score} for c, score in candidates],
        "context": context,
        "answer_mock": quoted_answer_mock(context, anchors),
    }


def main():
    corpus = json.loads(FIXTURE.read_text(encoding="utf-8"))
    library = Library(corpus["initial"])
    query = ("研讨室取消预约时限？", ("研讨室", "取消预约", "时限"), ("研讨室取消预约",))
    before = ask(library, *query)
    shallow = ask(library, *query, k=1)
    unknown = ask(library, "研讨室预约上限？", ("研讨室", "预约", "上限"), ("预约上限",))
    lookup = ask(library, "Locker B 的保留期？", ("locker b",), ("locker b |",))
    combined = (
        "取消研讨室预约须提前多久，编号要交给谁？", ("研讨室", "取消预约", "预约编号"),
        ("研讨室取消预约", "研讨室预约编号"),
    )
    short_context = ask(library, *combined, k=4, budget=1)
    sufficient_context = ask(library, *combined, k=4, budget=2)
    private = next(c.source for c in library.active.chunks if c.source.doc_id == "00-staff-draft")
    try:
        library.source_text(private, "visitor")
    except PermissionError:
        pass
    else:
        raise AssertionError("private source exposed to visitor")

    old = library.active
    previous_span = rerank(retrieve(library, old, "visitor", query[1], 3), query[2])[0].source
    updated = library.publish(corpus["update"])
    assert library.publish(corpus["update"]) is updated
    changed_under_same_revision = dict(corpus["update"], title="same revision with different bytes")
    try:
        library.publish(changed_under_same_revision)
    except ValueError:
        pass
    else:
        raise AssertionError("changed source reused a published revision")
    try:
        library.publish(corpus["initial"][0])
    except ValueError:
        pass
    else:
        raise AssertionError("old update overwrote current revision")
    after = ask(library, *query)
    assert library.active is updated
    preserved = [c for c in old.chunks if c.source.doc_id != "room-policy"]
    assert all(any(c is new for new in updated.chunks) for c in preserved)
    assert not any(c.source.doc_id == "room-policy" and c.source.version == 1 for c in updated.chunks)
    assert before["retrieved"][0]["citation"].startswith("00-room-notice")
    assert before["answer_mock"]["evidence"] == [
        {"citation": previous_span.key(), "source_text": "规则：研讨室取消预约须提前 24 小时。"},
    ]
    assert after["answer_mock"]["evidence"][0]["source_text"] == "规则：研讨室取消预约须提前 12 小时。"
    assert all("00-staff-draft" not in c["citation"] for c in before["retrieved"])
    assert shallow["answer_mock"]["status"] == unknown["answer_mock"]["status"] == "abstain"
    assert lookup["answer_mock"]["evidence"][0]["source_text"] == "Locker B | 12 days"
    assert short_context["answer_mock"]["status"] == "abstain"
    assert len(sufficient_context["answer_mock"]["evidence"]) == 2
    assert library.source_text(previous_span, "visitor") == before["answer_mock"]["evidence"][0]["source_text"]

    def source_hit(case, key):
        return any(result["citation"] == key for result in case["retrieved"])

    # Gold spans were read from the original fixture, independently of the rank output.
    gold_cancellation = "room-policy@1:p1[20,40)"
    assert previous_span.key() == gold_cancellation
    print(json.dumps({
        "corpus_sha256": hashlib.sha256(FIXTURE.read_bytes()).hexdigest(),
        "document_hashes": {
            f'{doc["doc_id"]}@{doc["doc_version"]}': source_hash(doc)
            for doc in [*corpus["initial"], corpus["update"]]
        },
        "before": before, "shallow": shallow, "unknown": unknown, "table": lookup,
        "short_context": short_context, "sufficient_context": sufficient_context, "after": after,
        "offline_example": {
            "cancellation_hit_at_1": int(source_hit(shallow, gold_cancellation)),
            "cancellation_hit_at_3": int(source_hit(before, gold_cancellation)),
            "cancellation_reciprocal_rank_at_3": 1 / (1 + next(
                rank for rank, item in enumerate(before["retrieved"]) if item["citation"] == gold_cancellation
            )),
        },
        "update": {
            "index_before": old.version, "index_after": updated.version,
            "reused_chunks": len(preserved), "rebuilt_chunks": len(updated.chunks) - len(preserved),
            "historical_reopen": library.source_text(previous_span, "visitor"),
        },
        "assertions": "passed",
    }, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
