#!/usr/bin/env python3
import os
import re
import sys
from io import StringIO
from contextlib import redirect_stdout, redirect_stderr

if len(sys.argv) < 2:
    print('usage: hermes_gemma4_ollama_once.py <prompt> [resume_session_id]', file=sys.stderr)
    sys.exit(2)

prompt = sys.argv[1]
resume = sys.argv[2] if len(sys.argv) > 2 and sys.argv[2] != '-' else None

HERMES_ROOT = os.path.expanduser('/Users/apayne/.hermes/hermes-agent')
sys.path.insert(0, HERMES_ROOT)
os.chdir(HERMES_ROOT)

out = StringIO()
err = StringIO()
exit_code = 0
with redirect_stdout(out), redirect_stderr(err):
    try:
        from cli import main as hermes_main
        hermes_main(
            query=prompt,
            model='gemma4:latest',
            provider='ollama',
            base_url='http://localhost:11434/v1',
            api_key='ollama',
            quiet=True,
            toolsets='none',
            max_turns=8,
            pass_session_id=True,
            resume=resume,
        )
    except SystemExit as e:
        exit_code = 0 if e.code is None else int(e.code)
    except Exception as e:
        print(f'ERROR: {type(e).__name__}: {e}')
        exit_code = 1

raw = out.getvalue().splitlines()
session_id = None
cleaned = []
for line in raw:
    if line.startswith('session_id:'):
        session_id = line.split(':', 1)[1].strip()
        continue
    if line.startswith('Warning: Unknown toolsets:'):
        continue
    if line.startswith('__EXIT__='):
        continue
    cleaned.append(line)

print('SESSION_ID=' + (session_id or ''))
print('EXIT_CODE=' + str(exit_code))
print('---RESPONSE---')
print('\n'.join(cleaned).strip())
