#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
# Stileex measured requirements bench (method 1.4): the simulated language model of the AI agents
# measured on the bench. An OpenAI-compatible server (GET /v1/models, POST /v1/chat/completions,
# streamed or not), run on the load generator, so that an agent can be measured under load without a
# real model: no token is paid, and the model's own time is fixed and known.
#
# How it answers, the same way every time:
#   - to a task (a user message with a marker, see below) that no tool result follows yet, when the
#     request offers tools: one call of the agent's shell tool (`exec`, or the first of `bash`,
#     `shell`, `terminal`), the command `ls -la`, after 0.5 s; the agent runs it, sends the result back;
#   - to a task a tool result follows, or to any other request: an answer of 150 words,
#     the first after 0.5 s, then 50 words per second (3 s), streamed when asked;
# so that a typical task (a request, one tool call, its result, the answer) spends 4.0 s in the model.
#
# A task is named by a marker in the user's message, "[task <id>]"; GET /stats/task/<id> answers the
# time the server spent on it, {"model_s": ...}, a check only: it includes the time the agent takes to
# read the streamed answer, so the load script subtracts the fixed 4.0 s instead.
#
#   modele-simule.py --ecoute <address> --port <port> [--journal <file>]
#
# --journal writes, for each request, the roles of its messages and the start of its last user message:
# to check a protocol, never during a measurement.
import argparse
import json
import re
import threading
import time
import uuid
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

DELAI_S = 0.5
MOTS = 150
MOTS_PAR_S = 50.0
OUTILS = ('exec', 'bash', 'shell', 'terminal')
PHRASE = ('The workspace holds the files the agent works on; here is what the listing shows and what '
          'it means for the task at hand, step by step, with the next actions to take.').split()
MARQUE = re.compile(r'\[task ([\w.-]+)\]')

temps = {}
verrou = threading.Lock()
JOURNAL = None


def texte_de(contenu):
    if isinstance(contenu, str):
        return contenu
    if isinstance(contenu, list):
        return ' '.join(p.get('text', '') for p in contenu if isinstance(p, dict))
    return ''


class Modele(BaseHTTPRequestHandler):
    protocol_version = 'HTTP/1.1'

    def log_message(self, *args):
        pass

    def json(self, code, corps):
        data = json.dumps(corps).encode()
        self.send_response(code)
        self.send_header('Content-Type', 'application/json')
        self.send_header('Content-Length', str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def do_GET(self):
        if self.path.rstrip('/') in ('/v1/models', '/models'):
            return self.json(200, {'object': 'list', 'data': [{'id': 'bench-model', 'object': 'model', 'owned_by': 'bench'}]})
        m = re.match(r'^/stats/task/([\w.-]+)$', self.path)
        if m:
            with verrou:
                return self.json(200, {'model_s': round(temps.get(m.group(1), 0.0), 3)})
        return self.json(404, {'error': {'message': 'not found'}})

    def do_POST(self):
        debut = time.monotonic()
        corps = json.loads(self.rfile.read(int(self.headers.get('Content-Length') or 0)) or b'{}')
        if not self.path.rstrip('/').endswith('/chat/completions'):
            return self.json(404, {'error': {'message': 'not found'}})
        messages = corps.get('messages') or []
        # The task: the latest user message that carries a marker (an agent may add its own context
        # after it, as a further user message). The tool is called until a tool result follows it.
        tache, i_tache = None, -1
        for i in range(len(messages) - 1, -1, -1):
            if messages[i].get('role') == 'user':
                m = MARQUE.search(texte_de(messages[i].get('content')))
                if m:
                    tache, i_tache = m.group(1), i
                    break
        i_outil = max((i for i, msg in enumerate(messages) if msg.get('role') == 'tool'), default=-1)
        noms = [((t.get('function') or {}).get('name')) for t in corps.get('tools') or []]
        if JOURNAL:
            dernier_user = next((texte_de(m.get('content')) for m in reversed(messages) if m.get('role') == 'user'), '')
            with verrou, open(JOURNAL, 'a') as j:
                j.write(json.dumps({'roles': [m.get('role') for m in messages], 'outils': noms[:12], 'tache': tache,
                                    'user': dernier_user[:300], 'stream': corps.get('stream')}) + '\n')
        outil = next((o for o in OUTILS if o in noms), None)
        appel = outil is not None and tache is not None and i_outil < i_tache
        ident = f'chatcmpl-{uuid.uuid4().hex[:24]}'
        modele = corps.get('model') or 'bench-model'
        cree = int(time.time())
        flux = bool(corps.get('stream'))
        time.sleep(DELAI_S)
        if appel:
            args = json.dumps({'command': 'ls -la'})
            tc = {'index': 0, 'id': f'call_{uuid.uuid4().hex[:24]}', 'type': 'function', 'function': {'name': outil, 'arguments': args}}
            if flux:
                self.ouvrir_flux()
                self.morceau({'id': ident, 'object': 'chat.completion.chunk', 'created': cree, 'model': modele,
                              'choices': [{'index': 0, 'delta': {'role': 'assistant', 'content': None, 'tool_calls': [tc]}, 'finish_reason': None}]})
                self.morceau({'id': ident, 'object': 'chat.completion.chunk', 'created': cree, 'model': modele,
                              'choices': [{'index': 0, 'delta': {}, 'finish_reason': 'tool_calls'}],
                              'usage': {'prompt_tokens': 1000, 'completion_tokens': 20, 'total_tokens': 1020}})
                self.fermer_flux()
            else:
                tc.pop('index')
                self.json(200, {'id': ident, 'object': 'chat.completion', 'created': cree, 'model': modele,
                                'choices': [{'index': 0, 'message': {'role': 'assistant', 'content': None, 'tool_calls': [tc]}, 'finish_reason': 'tool_calls'}],
                                'usage': {'prompt_tokens': 1000, 'completion_tokens': 20, 'total_tokens': 1020}})
        else:
            mots = [PHRASE[i % len(PHRASE)] for i in range(MOTS)]
            if flux:
                self.ouvrir_flux()
                self.morceau({'id': ident, 'object': 'chat.completion.chunk', 'created': cree, 'model': modele,
                              'choices': [{'index': 0, 'delta': {'role': 'assistant', 'content': ''}, 'finish_reason': None}]})
                for i, mot in enumerate(mots):
                    self.morceau({'id': ident, 'object': 'chat.completion.chunk', 'created': cree, 'model': modele,
                                  'choices': [{'index': 0, 'delta': {'content': ('' if i == 0 else ' ') + mot}, 'finish_reason': None}]})
                    time.sleep(1 / MOTS_PAR_S)
                self.morceau({'id': ident, 'object': 'chat.completion.chunk', 'created': cree, 'model': modele,
                              'choices': [{'index': 0, 'delta': {}, 'finish_reason': 'stop'}],
                              'usage': {'prompt_tokens': 1000, 'completion_tokens': MOTS, 'total_tokens': 1000 + MOTS}})
                self.fermer_flux()
            else:
                time.sleep(MOTS / MOTS_PAR_S)
                self.json(200, {'id': ident, 'object': 'chat.completion', 'created': cree, 'model': modele,
                                'choices': [{'index': 0, 'message': {'role': 'assistant', 'content': ' '.join(mots)}, 'finish_reason': 'stop'}],
                                'usage': {'prompt_tokens': 1000, 'completion_tokens': MOTS, 'total_tokens': 1000 + MOTS}})
        if tache:
            with verrou:
                temps[tache] = temps.get(tache, 0.0) + (time.monotonic() - debut)

    def ouvrir_flux(self):
        self.send_response(200)
        self.send_header('Content-Type', 'text/event-stream')
        self.send_header('Cache-Control', 'no-cache')
        self.send_header('Transfer-Encoding', 'chunked')
        self.end_headers()

    def ecrire(self, data):
        self.wfile.write(f'{len(data):x}\r\n'.encode() + data + b'\r\n')
        self.wfile.flush()

    def morceau(self, objet):
        self.ecrire(f'data: {json.dumps(objet)}\n\n'.encode())

    def fermer_flux(self):
        self.ecrire(b'data: [DONE]\n\n')
        self.wfile.write(b'0\r\n\r\n')
        self.wfile.flush()


def main():
    p = argparse.ArgumentParser(description='simulated language model of the bench')
    p.add_argument('--ecoute', required=True)
    p.add_argument('--port', type=int, default=8401)
    p.add_argument('--journal')
    a = p.parse_args()
    global JOURNAL
    JOURNAL = a.journal
    ThreadingHTTPServer.daemon_threads = True
    ThreadingHTTPServer((a.ecoute, a.port), Modele).serve_forever()


if __name__ == '__main__':
    main()
