"""Change a fact in the handbook and ask again. Nothing is trained.

    python change_a_fact.py

It copies handbook.txt into a folder of its own, so the page's handbook is never
touched, and runs the page's own ask.py in that folder four times:

    a price question, with the handbook as it is
    the same question, after one line was edited: khao soi costs 70 baht, not 60
    a question the handbook cannot answer
    the same question, after one new passage was added to the end

It also times what a change costs: turning every passage into numbers again.
"""
import shutil
import subprocess
import sys
import tempfile
import time
from pathlib import Path

from sentence_transformers import SentenceTransformer

PAGE_FILES = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(PAGE_FILES))
import ask  # noqa: E402  (the page's own file)

OLD_LINE = "Khao soi costs 60 baht."
NEW_LINE = "Khao soi costs 70 baht."
PRICE_QUESTION = "How much is a bowl of khao soi?"
NEW_PASSAGE = ("STUDENTS\n"
               "A student who shows a student card gets 10 baht off any dish."
               " The discount is for weekdays before 5 pm.")
NEW_QUESTION = "Is there a discount for students?"


def asked(folder, question_text):
    """What "python ask.py" prints for one question, run in that folder."""
    done = subprocess.run([sys.executable, str(PAGE_FILES / "ask.py"), question_text],
                          cwd=folder, capture_output=True, text=True, encoding="utf-8")
    if done.returncode != 0:
        sys.exit(done.stderr[-2000:])
    return done.stdout.rstrip()


def show(title, printed):
    print(title)
    for line in printed.splitlines():
        print("    " + line)
    print()


def main():
    with tempfile.TemporaryDirectory() as folder:
        handbook = Path(folder) / "handbook.txt"
        shutil.copy(PAGE_FILES / "handbook.txt", handbook)
        text = handbook.read_text(encoding="utf-8")
        if text.count(OLD_LINE) != 1:
            sys.exit(f"the handbook should have the line {OLD_LINE!r} exactly once")

        show("1. The handbook as it is", asked(folder, PRICE_QUESTION))

        text = text.replace(OLD_LINE, NEW_LINE)
        handbook.write_text(text, encoding="utf-8", newline="\n")
        print(f"   edited one line: {OLD_LINE}  ->  {NEW_LINE}")
        print()
        show("2. After the edit", asked(folder, PRICE_QUESTION))

        show("3. A question the handbook cannot answer", asked(folder, NEW_QUESTION))

        text = text.rstrip("\n") + "\n\n" + NEW_PASSAGE + "\n"
        handbook.write_text(text, encoding="utf-8", newline="\n")
        print("   added one passage to the end of the handbook:")
        for line in NEW_PASSAGE.splitlines():
            print("       " + line)
        print()
        show("4. After the new passage", asked(folder, NEW_QUESTION))

        passages = ask.read_passages(handbook)
        embedder = SentenceTransformer(ask.EMBEDDER)
        embedder.encode(passages[:1], normalize_embeddings=True)    # the first call is slow
        started = time.perf_counter()
        embedder.encode(passages, normalize_embeddings=True)
        seconds = time.perf_counter() - started
        print(f"Turning all {len(passages)} passages into numbers again:"
              f" {seconds:.2f} seconds. No training.")


if __name__ == "__main__":
    main()
