"""Forced-tool paper extraction. Code: MIT. Used unchanged in both arms."""
import json
import os

FIELDS = ['design', 'population', 'country', 'randomized_total', 'intervention_n', 'control_n', 'intervention', 'comparator', 'duration_weeks', 'primary_outcome', 'analysis', 'blinding', 'intervention_change', 'control_change', 'funding']
MODEL = os.environ.get('MODEL', 'pareto')
BASE_URL = os.environ.get('BASE_URL', 'https://api.unbiased.ai/v1')


def request(item, config):
    field = {'type': 'object', 'properties': {'value': {'type': ['string', 'null']}, 'quote': {'type': 'string'}}, 'required': ['value', 'quote'], 'additionalProperties': False}
    schema = {'type': 'object', 'properties': {name: field for name in FIELDS}, 'required': FIELDS, 'additionalProperties': False}
    return {'messages': [{'role': 'system', 'content': config['prompt']}, {'role': 'user', 'content': item['text']}],
            'tools': [{'type': 'function', 'function': {'name': 'extract_paper', 'description': 'Record reported trial fields and verbatim supporting quotes.', 'parameters': schema}}],
            'tool_choice': config['tool_choice'], 'max_tokens': config['max_tokens'], 'reasoning_effort': config['reasoning_effort'], 'parallel_tool_calls': False}


if __name__ == '__main__':
    # The scored runner supplies the same payload through its guarded transport.
    from pathlib import Path
    from openai import OpenAI
    here = Path(__file__).resolve().parent
    config = json.loads((here / 'eval.json').read_text())
    item = next(json.loads(line) for line in (here / 'fixture.jsonl').read_text().splitlines() if json.loads(line)['split'] == 'dev')
    key_name = 'UNBIASED_API_KEY' if MODEL == 'pareto' else 'OPENAI_API_KEY'
    client = OpenAI(base_url=BASE_URL, api_key=os.environ[key_name], max_retries=0, timeout=120)
    response = client.chat.completions.create(model=MODEL, **request(item, config))
    calls = response.choices[0].message.tool_calls or []
    if len(calls) != 1 or calls[0].function.name != 'extract_paper':
        raise ValueError('Expected exactly one extract_paper call; extra calls rejected')
    print(calls[0].function.arguments)
