"""2.1: a chat 'remembers' only because the whole history is re-sent every turn.

Part A: an 8-turn conversation about a transcript. We record what the user typed each turn
and the input tokens the API actually billed for that turn.
Part B: the last question asked again with no history: the model no longer knows the answer.
Part C: the input tokens of a bare "hi" per model: what the platform puts in the window that you never typed.
"""
import json, pathlib, sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from common import chat, dump

MODEL = sys.argv[1] if len(sys.argv) > 1 else 'gemini-3.8-flash'
HERE = pathlib.Path(__file__).resolve().parent
memos = {m['id']: m['text'] for m in json.load(open(HERE.parent / 'corpus/memos.json', encoding='utf-8'))['memos']}
transcript = ' '.join(memos[i] for i in ['W01', 'W07', 'W10', 'W12', 'W16', 'W17'])
turns = [
    '下面是我这周几条语音备忘录的转写，人名可能有错。我的同事里负责部署的叫蔺思远，后端叫韩昱。请先记住。\n\n' + transcript,
    '一共提到了几个人？', '谁负责部署？', '账单为什么涨了？', '祁骁在做什么？', '下个月谁要来？', '要准备什么？', '负责部署的同事叫什么名字？',
]
msgs, rows = [{'role': 'system', 'content': '你是一个简洁的助手，用中文回答。'}], []
for i, q in enumerate(turns, 1):
    msgs.append({'role': 'user', 'content': q})
    a, u, s = chat(msgs, MODEL, temperature=0)
    msgs.append({'role': 'assistant', 'content': a})
    rows.append({'turn': i, 'typed_chars': len(q), 'prompt_tokens': u.get('prompt_tokens'), 'completion_tokens': u.get('completion_tokens'), 'answer': a})
    print(i, len(q), u.get('prompt_tokens'), a[:40].replace('\n', ' '))
fresh, u, _ = chat([msgs[0], {'role': 'user', 'content': turns[-1]}], MODEL, temperature=0)
print('fresh:', u.get('prompt_tokens'), fresh[:80])
dump({'model': MODEL, 'turns': rows, 'fresh_call': {'question': turns[-1], 'prompt_tokens': u.get('prompt_tokens'), 'answer': fresh}}, HERE / f'results_{MODEL}.json')

if len(sys.argv) > 2 and sys.argv[2] == 'baseline':
    base = json.load(open(HERE / 'baseline_hi.json', encoding='utf-8')) if (HERE / 'baseline_hi.json').exists() else {}
    for m in ['gemini-3.8-flash', 'deepseek-v4.1-flash', 'grok-4-fast', 'gpt-5']:
        _, u, _ = chat([{'role': 'user', 'content': 'hi'}], m)
        base[m] = u.get('prompt_tokens'); print('hi', m, base[m])
    dump(base, HERE / 'baseline_hi.json')
