#!/usr/bin/env python3
"""Local-model mech harness (runs next to Ollama and headless Blender).

  python3 harness.py --model qwen3-coder:30b --rounds 8 --work ./work/run_x

Each round: ask the model for one Blender script, run it headless, audit it (parts, joints, rams, loop seam, travel,
foot slide, ground, cross-body collisions, adapted from the Opus build's check.py), render a test still, feed the numbers
back as text only (no images). The model may call the tool check_collisions for the last build's full detail.
Everything is logged to <work>/<model>/results.json. Standard library only.
"""
import argparse, json, os, re, subprocess, sys, time, urllib.request

HERE = os.path.dirname(os.path.abspath(__file__))
BLENDER = os.environ.get('BLENDER', 'blender')
OLLAMA = 'http://127.0.0.1:11434/api/chat'

TOOLS = [{
    'type': 'function',
    'function': {
        'name': 'check_collisions',
        'description': 'Run the walk collision test details for the PREVIOUS build: the colliding part pairs with frame counts, the closest clearances in mm, orphan parts. Takes no arguments.',
        'parameters': {'type': 'object', 'properties': {}, 'required': []},
    },
}]


def chat(model, messages, num_ctx, num_predict, tools=True):
    body = {'model': model, 'messages': messages, 'stream': False, 'keep_alive': '20m',
            'options': {'num_ctx': num_ctx, 'temperature': 0.2, 'top_p': 0.9, 'num_predict': num_predict}}
    if tools:
        body['tools'] = TOOLS
    req = urllib.request.Request(OLLAMA, data=json.dumps(body).encode(), headers={'Content-Type': 'application/json'})
    with urllib.request.urlopen(req, timeout=3600) as r:
        return json.load(r)


def extract_code(text):
    blocks = re.findall(r'```(?:python|py)?\s*\n(.*?)```', text, re.S)
    if not blocks:
        m = re.search(r'```(?:python|py)?\s*\n(.*)', text, re.S)  # unterminated
        return m.group(1) if m else None
    return max(blocks, key=len)


def run(cmd, timeout, cwd):
    t = time.time()
    try:
        p = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, timeout=timeout)
        return p.returncode, (p.stdout or '') + (p.stderr or ''), time.time() - t
    except subprocess.TimeoutExpired as e:
        out = ((e.stdout or b'').decode(errors='replace') if isinstance(e.stdout, bytes) else (e.stdout or ''))
        return -9, out + '\nTIMEOUT after %ds' % timeout, time.time() - t


def tail_errors(out, n=35):
    lines = out.splitlines()
    idx = [i for i, l in enumerate(lines) if 'Traceback' in l or 'Error' in l or 'TIMEOUT' in l]
    if idx:
        start = max(0, idx[0] - 2)
        return '\n'.join(lines[start:start + n])
    return '\n'.join(lines[-n:])


def evaluate(rd, build_rc, build_out, audit, render_ok):
    c = {}
    blend = os.path.exists(os.path.join(rd, 'mech.blend'))
    c['script_runs'] = build_rc == 0 and blend
    a = audit or {}
    c['parts_ge_60'] = a.get('parts', 0) >= 60
    c['all_parts_parented'] = bool(a) and not a.get('orphans') and a.get('parts', 0) > 0
    c['pilot_ok'] = bool(a) and 1.0 <= a.get('pilot_height_m', 0) <= 1.95 and a.get('pilot_inside_mech', False) and 3.0 <= a.get('mech_height_m', 0) <= 8.0
    c['rams_ge_4_working'] = a.get('rams_working', 0) >= 4
    c['loop_seam_ok'] = bool(a) and a.get('seam_mm', 999) <= 5.0 and a.get('animated_bodies', 0) >= 8
    c['travel_ge_2_5m_forward'] = a.get('travel_m', 0) >= 2.5 and a.get('travel_dir_xy', [0, 0])[1] > 0
    c['zero_collisions'] = bool(a) and a.get('collisions', 1) == 0 and a.get('frames_checked', 0) > 0
    c['feet_planted_and_ground_ok'] = bool(a) and a.get('foot_slide_max_cm', 999) <= 1.0 and a.get('below_ground_frames', 99) == 0 and a.get('floating_frames', 99) == 0 and a.get('planted_min_frames', 0) >= 5
    c['render_ok'] = render_ok
    return c


def feedback_text(rd, rnd, build_rc, build_out, audit, c, render_ok, render_tail):
    L = ['ROUND %d RESULT' % rnd]
    L.append('Build: ' + ('script ran, mech.blend saved' if c['script_runs'] else 'FAILED (exit %s)' % build_rc))
    if not c['script_runs']:
        L.append('Error output (tail):\n' + tail_errors(build_out))
    elif build_out.strip():
        warn = [l for l in build_out.splitlines() if 'Warning' in l or 'warning' in l][:5]
        if warn:
            L.append('Warnings: ' + ' | '.join(warn))
    if audit:
        a = audit
        L.append('Parts: %d (target 120+), pilot parts %d, bodies %d, body empties %d, animated body empties %d, triangles %d, orphan parts (no body) %d %s' % (
            a['parts'], a['pilot_parts'], a['bodies'], a['body_empties'], a['animated_bodies'], a['ntris'], len(a['orphans']), a['orphans'][:5]))
        L.append('Pilot height %.2f m, pilot inside mech bbox %s, mech height %.2f m (want 4 to 7)' % (a['pilot_height_m'], a['pilot_inside_mech'], a['mech_height_m']))
        L.append('Rams found %d, working (stroke >= 3 cm) %d: %s' % (len(a['rams']), a['rams_working'], [(r['name'], r['stroke_cm']) for r in a['rams']]))
        L.append('Frame range %s (want [1, 48]); loop seam error %.1f mm (want <= 5); travel %.2f m dir %s (want >= 2.5 m, +Y)' % (a['frame_range'], a['seam_mm'], a['travel_m'], a['travel_dir_xy']))
        L.append('Ground: lowest point min %.0f mm, worst floating (lowest point max) %.0f mm, frames below ground %d, frames floating %d' % (a['ground_min_mm'], a['ground_max_of_lowest_mm'], a['below_ground_frames'], a['floating_frames']))
        L.append('Foot slide on planted frames (cm per frame, want <= 1): %s; min planted frames %d (want >= 5 each)' % (a['foot_slide'], a['planted_min_frames']))
        L.append('Collision test (%d frames, %d cross-body pair tests): %d hits, %d colliding pairs. Worst pairs (a, b, frames hit): %s' % (
            a['frames_checked'], a['pair_tests'], a['collisions'], a['collision_pairs'], a['collision_top'][:12]))
    L.append('Test render: ' + ('ok' if render_ok else 'FAILED ' + render_tail))
    L.append('Checks: ' + ', '.join('%s=%s' % (k, 'PASS' if v else 'fail') for k, v in c.items()))
    return '\n'.join(L)


def tool_result(prev_audit):
    if not prev_audit:
        return 'No build audit exists yet for the previous round.'
    a = prev_audit
    return json.dumps({'colliding_pairs_with_frame_counts': a['collision_top'], 'closest_clearances_mm_a_b_frame': a['closest_mm'],
                       'orphans': a['orphans'], 'foot_slide': a['foot_slide'], 'rams': a['rams']})[:6000]


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--model', required=True)
    ap.add_argument('--rounds', type=int, default=8)
    ap.add_argument('--work', required=True)
    ap.add_argument('--num-ctx', type=int, default=32768)
    ap.add_argument('--num-predict', type=int, default=14000)
    ap.add_argument('--no-tools', action='store_true')
    ap.add_argument('--final-only-best', action='store_true')
    args = ap.parse_args()
    brief = open(os.path.join(HERE, 'brief.md')).read()
    wd = os.path.join(os.path.expanduser(args.work), args.model.replace(':', '_'))
    os.makedirs(wd, exist_ok=True)
    log = {'model': args.model, 'started': time.strftime('%Y-%m-%d %H:%M:%S'), 'rounds': [], 'num_ctx': args.num_ctx}
    wall0 = time.time()
    prev_script, prev_fb, prev_audit = None, None, None
    best = None

    def save():
        json.dump(log, open(os.path.join(wd, 'results.json'), 'w'), indent=1)

    for rnd in range(1, args.rounds + 1):
        rd = os.path.join(wd, 'round_%d' % rnd)
        os.makedirs(rd, exist_ok=True)
        rt0 = time.time()
        if prev_script is None:
            user = 'Write the script now. Follow the brief exactly.'
        else:
            user = ('Here is your latest script:\n```python\n%s\n```\n\n%s\n\nFix every failing check, keep what already works, and return the COMPLETE script. '
                    'Reply with a 3 line plan and one python code block.' % (prev_script, prev_fb))
        msgs = [{'role': 'system', 'content': brief}, {'role': 'user', 'content': user}]
        tok_in = tok_out = 0
        gen_s = 0.0
        tool_calls = 0
        text = ''
        err = None
        try:
            for _ in range(3):
                r = chat(args.model, msgs, args.num_ctx, args.num_predict, tools=not args.no_tools)
                tok_in += r.get('prompt_eval_count', 0)
                tok_out += r.get('eval_count', 0)
                gen_s += r.get('eval_duration', 0) / 1e9 + r.get('prompt_eval_duration', 0) / 1e9
                m = r['message']
                if m.get('tool_calls'):
                    msgs.append(m)
                    for tc in m['tool_calls']:
                        tool_calls += 1
                        msgs.append({'role': 'tool', 'tool_name': tc['function']['name'], 'content': tool_result(prev_audit)})
                    continue
                text = m.get('content', '')
                break
        except Exception as e:
            err = 'ollama error: %r' % (e,)
        open(os.path.join(rd, 'reply.txt'), 'w').write(text)
        code = extract_code(text) if text else None
        row = {'round': rnd, 'tokens_in': tok_in, 'tokens_out': tok_out, 'gen_seconds': round(gen_s, 1), 'tool_calls': tool_calls}
        if not code:
            row.update({'ok': False, 'note': err or 'no code block in reply', 'wall_s': round(time.time() - rt0, 1)})
            prev_fb = 'ROUND %d RESULT\nYour reply had no usable python code block. Return the full script in one ```python block.' % rnd
            log['rounds'].append(row)
            save()
            continue
        open(os.path.join(rd, 'mech.py'), 'w').write(code)
        rc, out, bs = run([BLENDER, '-b', '--factory-startup', '-P', os.path.join(rd, 'mech.py'), '--', rd], 900, rd)
        open(os.path.join(rd, 'build.log'), 'w').write(out)
        audit = None
        audit_s = 0
        if os.path.exists(os.path.join(rd, 'mech.blend')):
            arc, aout, audit_s = run([BLENDER, '-b', os.path.join(rd, 'mech.blend'), '-P', os.path.join(HERE, 'audit.py'), '--', os.path.join(rd, 'audit.json'), '4'], 1100, rd)
            open(os.path.join(rd, 'audit.log'), 'w').write(aout)
            if os.path.exists(os.path.join(rd, 'audit.json')):
                audit = json.load(open(os.path.join(rd, 'audit.json')))
        render_ok, rtail, rs = False, '', 0
        if os.path.exists(os.path.join(rd, 'mech.blend')):
            rrc, rout, rs = run([BLENDER, '-b', os.path.join(rd, 'mech.blend'), '-P', os.path.join(HERE, 'render_stage.py'), '--', os.path.join(rd, 'still_test'), 'still_test'], 900, rd)
            render_ok = os.path.exists(os.path.join(rd, 'still_test.png'))
            rtail = tail_errors(rout, 12)
            open(os.path.join(rd, 'render.log'), 'w').write(rout)
        c = evaluate(rd, rc, out, audit, render_ok)
        fb = feedback_text(rd, rnd, rc, out, audit, c, render_ok, rtail)
        open(os.path.join(rd, 'feedback.txt'), 'w').write(fb)
        npass = sum(1 for v in c.values() if v)
        row.update({'ok': c['script_runs'], 'checks': c, 'checks_passed': npass, 'checks_total': len(c),
                    'parts': (audit or {}).get('parts'), 'collision_pairs': (audit or {}).get('collision_pairs'),
                    'collisions': (audit or {}).get('collisions'), 'build_s': round(bs, 1), 'audit_s': round(audit_s, 1), 'render_s': round(rs, 1),
                    'wall_s': round(time.time() - rt0, 1), 'script_lines': code.count('\n') + 1})
        log['rounds'].append(row)
        score = (c['script_runs'], npass, -(audit or {}).get('collision_pairs', 999), (audit or {}).get('parts', 0))
        if best is None or score > best[0]:
            best = (score, rnd)
        log['best_round'] = best[1]
        prev_script, prev_fb, prev_audit = code, fb, audit
        save()
        print('round', rnd, 'checks', npass, '/', len(c), 'parts', row['parts'], 'coll pairs', row['collision_pairs'], 'wall', row['wall_s'], flush=True)
        if npass == len(c):
            break

    log['rounds_used'] = len(log['rounds'])
    log['wall_total_s'] = round(time.time() - wall0, 1)
    log['tokens_in_total'] = sum(r['tokens_in'] for r in log['rounds'])
    log['tokens_out_total'] = sum(r['tokens_out'] for r in log['rounds'])
    save()
    # finals: full-frame audit, 1080p still and a short loop for the best round that builds
    if best and best[0][0]:
        bd = os.path.join(wd, 'round_%d' % best[1])
        blend = os.path.join(bd, 'mech.blend')
        fin = {'round': best[1]}
        rc, out, s = run([BLENDER, '-b', blend, '-P', os.path.join(HERE, 'audit.py'), '--', os.path.join(bd, 'audit_full.json'), '1'], 2400, bd)
        fin['full_audit_s'] = round(s, 1)
        if os.path.exists(os.path.join(bd, 'audit_full.json')):
            fa = json.load(open(os.path.join(bd, 'audit_full.json')))
            fin['full_audit'] = {k: fa[k] for k in ('parts', 'collisions', 'collision_pairs', 'frames_checked', 'pair_tests', 'seam_mm', 'travel_m', 'foot_slide_max_cm', 'rams_working')}
        rc, out, s = run([BLENDER, '-b', blend, '-P', os.path.join(HERE, 'render_stage.py'), '--', os.path.join(wd, 'final_1080p'), 'still_final'], 1800, bd)
        fin['still_s'] = round(s, 1)
        fin['still'] = os.path.exists(os.path.join(wd, 'final_1080p.png'))
        if not args.final_only_best:
            rc, out, s = run([BLENDER, '-b', blend, '-P', os.path.join(HERE, 'render_stage.py'), '--', os.path.join(wd, 'loop'), 'loop'], 2400, bd)
            fin['loop_render_s'] = round(s, 1)
            if os.path.exists(os.path.join(wd, 'loop_0001.png')):
                rc, out, s = run(['ffmpeg', '-y', '-framerate', '24', '-i', os.path.join(wd, 'loop_%04d.png'), '-c:v', 'libx264', '-pix_fmt', 'yuv420p', os.path.join(wd, 'final_loop.mp4')], 300, wd)
                fin['loop_mp4'] = os.path.exists(os.path.join(wd, 'final_loop.mp4'))
        log['final'] = fin
        save()
    log['wall_total_with_finals_s'] = round(time.time() - wall0, 1)
    save()
    print('DONE', json.dumps({k: log.get(k) for k in ('rounds_used', 'best_round', 'tokens_in_total', 'tokens_out_total', 'wall_total_s')}))


if __name__ == '__main__':
    main()
