"""2.1 demo (English edition): watch the context meter of an agent harness (DeepSeek Harness web UI) grow while you
type only a few words. English twin of experiments/2_1_stateless/dsh_demo.py; same steps, English conversation.

Needs a running DSH web on 127.0.0.1:3080 and its launch token in build/dsh_explore/token.txt (never printed).
Model: DeepSeek V4.1 Flash via Ollama Cloud. The session runs in the public deepseek_harness checkout, with the
sidebar collapsed so no session history shows, and is archived at the end.
Screenshots go to assets/ch02_01_en/; numbers to experiments_en/2_1_stateless/dsh_results.json.
Usage (textbook repo root): /Users/grapeot/co/knowledge_working/.venv/bin/python experiments_en/2_1_stateless/dsh_demo.py [--probe]
"""
import json
import re
import sys

from playwright.sync_api import sync_playwright

tok = open('build/dsh_explore/token.txt').read().strip()
memos = {m['id']: m['text'] for m in json.load(open('experiments_en/corpus/memos.json', encoding='utf-8'))['memos']}
turns = ['Here are transcripts of a few of my voice memos from this week. The names may be wrong. On my team, Saoirse '
         'handles deployment and Jaxon is on the backend. Please remember that, and just reply "OK". Don\'t read or '
         'write any files, and don\'t call any tools.\n\n'
         + ' '.join(memos[i] for i in ['W01', 'W07', 'W10', 'W12', 'W16', 'W17']),
         'How many people are mentioned?', 'Who handles deployment?', 'Why did the bill go up?',
         "Who's coming next month?", "What's the name of the colleague who handles deployment?"]
OUT = 'assets/ch02_01_en'
rows = []
with sync_playwright() as p:
    b = p.chromium.launch()
    pg = b.new_page(viewport={'width': 1100, 'height': 760}, device_scale_factor=2)
    pg.goto(f'http://127.0.0.1:3080/?token={tok}')
    pg.wait_for_timeout(3000)
    if '--probe' in sys.argv:
        pg.screenshot(path='build/dsh_explore/en_probe_landing.png')
        print('title', pg.title(), 'url_has_token', 'token=' in pg.url)
    pg.get_by_role('button', name='Choose workspace').click(); pg.wait_for_timeout(800)
    pg.get_by_role('menuitem', name='deepseek_harness').click(); pg.wait_for_timeout(1500)
    pg.locator('button[aria-label^="Select model"]').click(); pg.wait_for_timeout(800)
    pg.locator('[role=menuitem]').filter(has_text='Model').first.click(); pg.wait_for_timeout(1500)
    pick = pg.locator('[role=menuitemradio], [role=menuitem], [role=option]').filter(
        has_text=re.compile('DeepSeek.?V4.?1.?Flash', re.I)).first
    pick.click(); pg.wait_for_timeout(1000)
    print('model now', pg.locator('button[aria-label^="Select model"]').get_attribute('aria-label'))
    if '--probe' in sys.argv:
        pg.screenshot(path='build/dsh_explore/en_probe_ready.png')
        b.close(); raise SystemExit
    pg.get_by_role('button', name='Collapse sidebar').click(); pg.wait_for_timeout(600)
    for i, q in enumerate(turns, 1):
        box = pg.get_by_role('textbox').last
        box.click(); box.fill(q); pg.keyboard.press('Enter')
        pg.wait_for_timeout(3000)
        for _ in range(120):  # wait until a usage line for this turn exists
            if pg.get_by_text(re.compile(r'^Usage ')).count() >= i:
                break
            pg.wait_for_timeout(1000)
        pg.wait_for_timeout(1500)
        body = pg.inner_text('body')
        tot = re.findall(r'([\d.]+K?) tok\s*·\s*Cache hit (\d+)%', body)
        per_turn = re.findall(r'Usage\s+([\d.]+K?) tok', body)
        meter = pg.locator('[aria-label$="of context used"]').first.get_attribute('aria-label')
        rows.append({'turn': i, 'typed_words': len(q.split()), 'typed_chars': len(q),
                     'turn_usage': per_turn[-1] if per_turn else None,
                     'session_tokens': tot[-1][0] if tot else None, 'cache_hit_pct': tot[-1][1] if tot else None,
                     'meter': meter})
        print(rows[-1])
        pg.screenshot(path=f'{OUT}/dsh_turn{i}.png')
    answer = pg.inner_text('body')
    json.dump({'model': 'DeepSeek V4.1 Flash (Ollama Cloud) via DSH web', 'turns': rows,
               'last_answer_mentions_saoirse': 'Saoirse' in answer.split(turns[-1])[-1]},
              open('experiments_en/2_1_stateless/dsh_results.json', 'w'), ensure_ascii=False, indent=1)
    # archive the demo session so it does not linger in the user's DSH list
    pg.get_by_role('button', name=re.compile('Expand sidebar|Open sidebar|Show sidebar')).first.click()
    pg.wait_for_timeout(800)
    row = pg.get_by_role('treeitem').filter(has_text=re.compile('voice memo|transcripts|Saoirse', re.I)).first
    if row.count():
        print('archiving session row:', row.inner_text()[:80].replace('\n', ' '))
        row.hover(); pg.wait_for_timeout(400)
        arch = row.get_by_role('button', name='Archive session')
        if arch.count():
            arch.first.click(force=True); pg.wait_for_timeout(1000); print('archived')
    else:
        print('demo session row not found; not archived')
    b.close()
