#!/usr/bin/env python3
"""Run one coding agent on one ticket, then grade it. Run as root.

  run_agent.py <agent> <ticket> [--run N] [--timeout 900]
  agents: claude | codex | gemini | cursor

Safety: each agent runs as its own unprivileged user (lab-<agent>) that owns only
sandbox/<agent>/. It cannot read hidden/, reference/, the site secrets or another agent's folder.
Grading also runs as that user, after the agent has exited, in a throwaway copy that is deleted
straight after, so agent-written code never runs as root and a later run cannot read the tests.

Every agent gets the same prompt: the ticket text plus one paragraph of instructions.
Output: results/run<N>/<agent>/<ticket>.json and the agent's console log beside it.
"""
import argparse, json, os, re, shutil, subprocess, sys, time, xml.etree.ElementTree as ET
from pathlib import Path

BASE = Path(__file__).resolve().parent
TOOLS = Path('/mnt/moredata-volume/labs/tools')
PY = str(BASE / 'venv/bin/python')
IGNORE = shutil.ignore_patterns('__pycache__', '.pytest_cache', '.git', '*.pyc', 'venv', '.venv', '*.egg-info')

PROMPT = """You are working in a Python repository in the current directory. Do the ticket below.

Read README.md first: it documents the billing rules this code implements. Make the change in the code, keep the existing tests passing, and add or update tests where it makes sense. Run the test suite with `{py} -m pytest -q` before you finish. Nobody is available to answer questions, so make reasonable decisions, write down anything important in the files the ticket or README asks for, and finish the work.

----- TICKET -----
{ticket}
"""

def env_file(path):
    out = {}
    for line in open(path):
        m = re.match(r"^([A-Z_0-9]+)=(.*)$", line.strip())
        if m: out[m.group(1)] = m.group(2).strip().strip("'\"")
    return out

def command(agent, home, prompt, secrets):
    env = {'HOME': str(home), 'PATH': '/usr/local/bin:/usr/bin:/bin', 'LANG': 'C.UTF-8', 'TERM': 'dumb'}
    if agent == 'claude':
        env['ANTHROPIC_API_KEY'] = secrets['ANTHROPIC_API_KEY']
        return env, ['/usr/local/lib/labtools/claude', '-p', prompt, '--dangerously-skip-permissions', '--output-format', 'json']
    if agent == 'codex':
        env['CODEX_HOME'] = str(home / '.codex')
        return env, [str(TOOLS / 'node_modules/.bin/codex'), 'exec', '--skip-git-repo-check', '--dangerously-bypass-approvals-and-sandbox', prompt]  # Codex's own bubblewrap sandbox cannot start on this host; isolation comes from the lab-codex user
    if agent == 'gemini':
        env['GEMINI_API_KEY'] = secrets['GEMINI_API_KEY']; env['GEMINI_CLI_TRUST_WORKSPACE'] = 'true'
        return env, [str(TOOLS / 'node_modules/.bin/gemini'), '-p', prompt, '--yolo', '-o', 'json']
    if agent == 'cursor':
        return env, [str(home / '.local/bin/cursor-agent'), '--trust', '-f', '-p', prompt, '--output-format', 'json']
    sys.exit('unknown agent ' + agent)

def as_user(user, argv, cwd, env, timeout, log=None):
    full = ['runuser', '-u', user, '--', 'env', '-i'] + [f'{k}={v}' for k, v in env.items()] + argv
    t = time.time()
    try:
        p = subprocess.run(full, cwd=cwd, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=timeout, errors='replace')
        out, code, timed_out = p.stdout, p.returncode, False
    except subprocess.TimeoutExpired as ex:
        out = (ex.stdout or b'').decode('utf-8', 'replace') if isinstance(ex.stdout, bytes) else (ex.stdout or ''); code, timed_out = -1, True
        subprocess.run(['pkill', '-KILL', '-u', user], check=False)
    if log: Path(log).write_text(out)
    return out, code, timed_out, round(time.time() - t, 1)

def chown(path, user): subprocess.run(['chown', '-R', f'{user}:{user}', str(path)], check=True)

def pytest_as(user, root, target, home):
    report = root / '_junit.xml'
    env = {'HOME': str(home), 'PATH': '/usr/local/bin:/usr/bin:/bin', 'PYTHONPATH': str(root), 'PYTHONDONTWRITEBYTECODE': '1', 'PYTHONHASHSEED': '0'}
    out, code, timed_out, secs = as_user(user, [PY, '-m', 'pytest', target, '-q', '-p', 'no:cacheprovider', '--rootdir', str(root), f'--junitxml={report}'], root, env, 180)
    passed = failed = 0
    if report.exists():
        for case in ET.parse(report).getroot().iter('testcase'):
            tags = {c.tag for c in case}
            if tags & {'failure', 'error'}: failed += 1
            elif 'skipped' not in tags: passed += 1
        report.unlink()
    elif code != 0: failed = 1
    return dict(passed=passed, failed=failed, timed_out=timed_out, tail=out[-1500:])

def usage_from(agent, out):
    """Best-effort token and cost figures from each CLI's own output."""
    u = {}
    try:
        if agent in ('claude', 'gemini', 'cursor'):
            m = re.search(r'\{.*\}\s*$', out, re.S); j = json.loads(m.group(0)) if m else {}
            if agent == 'claude':
                u = dict(cost_usd=j.get('total_cost_usd'), turns=j.get('num_turns'), input_tokens=(j.get('usage') or {}).get('input_tokens'), output_tokens=(j.get('usage') or {}).get('output_tokens'),
                         cache_read=(j.get('usage') or {}).get('cache_read_input_tokens'), cache_write=(j.get('usage') or {}).get('cache_creation_input_tokens'), models=list((j.get('modelUsage') or {}).keys()))
            elif agent == 'gemini':
                models = (j.get('stats') or {}).get('models') or {}
                u = dict(models=list(models), input_tokens=sum((v.get('tokens') or {}).get('prompt', 0) for v in models.values()), output_tokens=sum((v.get('tokens') or {}).get('candidates', 0) + (v.get('tokens') or {}).get('thoughts', 0) for v in models.values()),
                         cached=sum((v.get('tokens') or {}).get('cached', 0) for v in models.values()))
            else:
                u = {k: j.get(k) for k in ('duration_ms', 'usage', 'model', 'request_id') if k in j}
        else:
            m = re.search(r'tokens used\s*\n?\s*([\d,]+)', out); u = dict(total_tokens=int(m.group(1).replace(',', '')) if m else None)
            m = re.search(r'^model:\s*(\S+)', out, re.M); u['models'] = [m.group(1)] if m else []
    except Exception as ex: u['parse_error'] = str(ex)[:120]
    return u

def main():
    ap = argparse.ArgumentParser(); ap.add_argument('agent'); ap.add_argument('ticket'); ap.add_argument('--run', default='1'); ap.add_argument('--timeout', type=int, default=900)
    a = ap.parse_args(); agent, ticket, user = a.agent, a.ticket.upper(), 'lab-' + a.agent
    sandbox = BASE / 'sandbox' / agent; home = sandbox / 'home'
    work = sandbox / 'runs' / f'run{a.run}-{ticket}'
    resdir = BASE / 'results' / f'run{a.run}' / agent; resdir.mkdir(parents=True, exist_ok=True)
    resfile = resdir / f'{ticket}.json'
    if resfile.exists() and not json.loads(resfile.read_text()).get('harness_error'): print(agent, ticket, 'already done'); return
    if work.exists(): shutil.rmtree(work)
    shutil.copytree(BASE / 'repo', work, ignore=IGNORE); chown(work, user)
    secrets = {**env_file('/opt/pondero.ai/ops/.env')}
    prompt = PROMPT.format(py=PY, ticket=(BASE / 'tickets' / f'{ticket}.md').read_text())
    env, argv = command(agent, home, prompt, secrets)
    out, code, timed_out, secs = as_user(user, argv, work, env, a.timeout, log=resdir / f'{ticket}.log')
    # grade in a throwaway copy: agent's code + pristine visible tests + the acceptance test
    g = sandbox / 'grading' / ticket
    if g.exists(): shutil.rmtree(g)
    shutil.copytree(work, g, ignore=shutil.ignore_patterns('__pycache__', '.pytest_cache', '.git', '*.pyc', 'tests'))
    shutil.copytree(BASE / 'repo' / 'tests', g / 'tests', ignore=IGNORE)
    (g / 'acceptance').mkdir(); shutil.copy(BASE / 'hidden' / f'test_{ticket}.py', g / 'acceptance' / f'test_{ticket}.py'); chown(sandbox / 'grading', user)
    hidden = pytest_as(user, g, 'acceptance', home); visible = pytest_as(user, g, 'tests', home)
    shutil.rmtree(sandbox / 'grading')
    d = subprocess.run(['diff', '-ruN', '-x', '__pycache__', '-x', '.pytest_cache', '-x', '.git', '-x', '*.pyc', str(BASE / 'repo'), str(work)], capture_output=True, text=True, errors='replace').stdout
    (resdir / f'{ticket}.diff').write_text(d)
    total = len(re.findall(r'^\s*def test_\w+\s*\(', (BASE / 'hidden' / f'test_{ticket}.py').read_text(), re.M))
    rec = dict(agent=agent, ticket=ticket, run=a.run, seconds=secs, exit_code=code, timed_out=timed_out,
               hidden_passed=hidden['passed'], hidden_total=max(total, hidden['passed'] + hidden['failed']), hidden_all_pass=hidden['failed'] == 0 and hidden['passed'] > 0 and not hidden['timed_out'],
               visible_passed=visible['passed'], visible_failed=visible['failed'],
               files_changed=len(re.findall(r'^diff -ruN', d, re.M)), lines_added=len(re.findall(r'^\+(?!\+\+)', d, re.M)), lines_removed=len(re.findall(r'^-(?!--)', d, re.M)),
               notes_md=(work / 'NOTES.md').exists(), usage=usage_from(agent, out), hidden_tail=hidden['tail'][-600:] if hidden['failed'] else '')
    resfile.write_text(json.dumps(rec, indent=1))
    print(json.dumps({k: rec[k] for k in ('agent', 'ticket', 'seconds', 'timed_out', 'hidden_passed', 'hidden_total', 'hidden_all_pass', 'visible_failed', 'files_changed', 'usage')}))

if __name__ == '__main__':
    main()
