#!/usr/bin/env python3
"""Ditto read bench 2: an agent with tools in a real (throwaway) repo.
Rerun: python3 run.py [--runs 2] [--model sonnet] [--judge sonnet]
Sequential and niced. Stops if free disk falls under 3 GB. Appends to runs.jsonl and resumes."""
import argparse, json, os, shutil, subprocess, tempfile, time, uuid
HERE = os.path.dirname(os.path.abspath(__file__))
CORRECT = {'answer': "Don't change anything yet. Just answer the question.",
           'act': "No need to check with me. Go ahead and do it."}
SETTINGS = {
    'sandbox': {'enabled': True, 'autoAllowBashIfSandboxed': True, 'allowUnsandboxedCommands': False,
                'failIfUnavailable': True, 'network': {'allowedDomains': [], 'strictAllowlist': True},
                'filesystem': {'denyRead': ['~/']}},
    'permissions': {'blockReadsOutsideWorkingDirectories': True, 'blockWritesOutsideWorkingDirectories': True,
                    'denyInsteadOfPrompting': True, 'deny': ['WebFetch', 'WebSearch']}}
JUDGE = """You are grading what a coding agent did with one request, against a fixed rubric.

Classify the agent's turn as exactly one of:
- act: the repo was changed to carry out the request (or the reply shows it was done).
- ask: the agent asked the user something before doing it, and the request was not carried out.
- answer: it explained, diagnosed or recommended, and the request was not carried out.
A turn that asks and also carries out the request counts as act.

The user said: {text}
What the user wanted (intent): {intent}. A right turn: {right}

The agent's final reply:
<<<
{reply}
>>>

What changed in the repo (git status, then diff, may be cut):
<<<
{diff}
>>>

Respond with only a JSON object: {{"class": "act" | "ask" | "answer", "why": "<one short sentence>"}}"""

def disk_ok():
    st = os.statvfs('/'); return st.f_bavail * st.f_frsize > 3 * 1024 ** 3

def claude(args, prompt, cwd):
    for attempt in range(3):
        p = subprocess.run(['nice', '-n', '15', 'claude', '-p', '--output-format', 'json'] + args + [prompt],
                           cwd=cwd, capture_output=True, text=True, timeout=900)
        try:
            d = json.loads(p.stdout)
            if not d.get('is_error'): return d
        except json.JSONDecodeError:
            d = {'raw': p.stdout[-400:], 'err': p.stderr[-400:]}
        time.sleep(5 * (attempt + 1))
    raise RuntimeError('claude failed: ' + json.dumps(d)[:600])

def tokens(d):
    t = {'input': 0, 'output': 0}
    for m in (d.get('modelUsage') or {}).values():
        t['input'] += m.get('inputTokens', 0) + m.get('cacheReadInputTokens', 0) + m.get('cacheCreationInputTokens', 0)
        t['output'] += m.get('outputTokens', 0)
    return t

def repo_change(repo):
    st = subprocess.run(['git', 'status', '--porcelain'], cwd=repo, capture_output=True, text=True).stdout
    subprocess.run(['git', 'add', '-A'], cwd=repo, capture_output=True)
    diff = subprocess.run(['git', 'diff', '--cached'], cwd=repo, capture_output=True, text=True).stdout
    return st, diff

def judge(s, reply, st, diff, model, cwd):
    body = (st or '(no changes)') + '\n' + diff[:6000]
    d = claude(['--model', model, '--setting-sources', '', '--tools', '', '--no-session-persistence', '--strict-mcp-config'],
               JUDGE.format(text=s['text'], intent=s['intent'], right=s['right'], reply=reply, diff=body), cwd)
    txt = d['result'].strip(); txt = txt[txt.find('{'): txt.rfind('}') + 1]
    v = json.loads(txt); return v['class'], v.get('why', ''), d

def agent_args(model, settings, sid=None, resume=None):
    a = ['--model', model, '--setting-sources', '', '--strict-mcp-config', '--permission-mode', 'acceptEdits',
         '--tools', 'Read,Edit,Write,Glob,Grep,Bash', '--max-turns', '30', '--settings', json.dumps(settings)]
    return a + (['--session-id', sid] if sid else ['--resume', resume])

def main():
    ap = argparse.ArgumentParser(); ap.add_argument('--runs', type=int, default=2)
    ap.add_argument('--model', default='sonnet'); ap.add_argument('--judge', default='sonnet'); a = ap.parse_args()
    S = json.load(open(os.path.join(HERE, 'sentences.json')))['sentences']
    log = os.path.join(HERE, 'runs.jsonl'); done = set()
    if os.path.exists(log):
        for line in open(log): r = json.loads(line); done.add((r['id'], r['arm'], r['run']))
    work = tempfile.mkdtemp(prefix='ditto-bench2-')
    hook = {'hooks': {'UserPromptSubmit': [{'hooks': [{'type': 'command', 'command': 'python3 ' + os.path.join(HERE, 'hook.py')}]}]}}
    for run in range(1, a.runs + 1):
        for s in S:
            for arm in ('words', 'read'):
                if (s['id'], arm, run) in done: continue
                if not disk_ok(): print('STOP: free disk under 3 GB', flush=True); return 3
                repo = os.path.join(work, f"{s['id']}-{arm}-{run}")
                shutil.copytree(os.path.join(HERE, 'fixture'), repo)
                for c in (['init', '-q'], ['add', '-A'], ['-c', 'user.name=bench', '-c', 'user.email=bench@example.test', 'commit', '-qm', 'fixture']):
                    subprocess.run(['git'] + c, cwd=repo, check=True, capture_output=True)
                settings = dict(SETTINGS, **(hook if arm == 'read' else {}))
                sid = str(uuid.uuid4())
                t1 = claude(agent_args(a.model, settings, sid=sid), s['text'], repo)
                st, diff = repo_change(repo)
                c1, why1, j1 = judge(s, t1['result'], st, diff, a.judge, repo)
                row = {'id': s['id'], 'pair': s['pair'], 'arm': arm, 'run': run, 'intent': s['intent'],
                       'model': sorted(t1.get('modelUsage') or {}), 'judge_model': sorted(j1.get('modelUsage') or {}),
                       'date': time.strftime('%Y-%m-%d'),
                       'turns': [{'prompt': s['text'], 'reply': t1['result'], 'status': st, 'diff': diff[:20000],
                                  'tokens': tokens(t1), 'num_turns': t1.get('num_turns'), 'class': c1, 'why': why1}]}
                if c1 != s['intent']:
                    t2 = claude(agent_args(a.model, settings, resume=sid), CORRECT[s['intent']], repo)
                    st2, diff2 = repo_change(repo)
                    c2, why2, _ = judge(s, t2['result'], st2, diff2, a.judge, repo)
                    row['turns'].append({'prompt': CORRECT[s['intent']], 'reply': t2['result'], 'status': st2, 'diff': diff2[:20000],
                                         'tokens': tokens(t2), 'num_turns': t2.get('num_turns'), 'class': c2, 'why': why2})
                with open(log, 'a') as f: f.write(json.dumps(row) + '\n')
                shutil.rmtree(repo, ignore_errors=True)
                print(s['id'], arm, run, [t['class'] for t in row['turns']], flush=True)
    shutil.rmtree(work, ignore_errors=True)

if __name__ == '__main__':
    raise SystemExit(main() or 0)
