"""MIT. Forced-tool request shared by both arms; transport is in run_eval.py."""
import json
import os
from pathlib import Path

MODEL = os.environ.get('MODEL', 'pareto')
BASE_URL = os.environ.get('BASE_URL', 'https://api.unbiased.ai/v1')


def request(item, config):
    schema = {'type': 'object', 'properties': {
        'claim_id': {'type': 'string'},
        'label': {'type': 'string', 'enum': ['supported', 'contradicted', 'not_in_sources']},
        'quote': {'type': 'string', 'description': 'Exact source substring, or empty when no source supports or contradicts the claim.'},
        'reason': {'type': 'string', 'description': 'Brief explanation of how the supplied source relates to the claim.'},
    }, 'required': ['claim_id', 'label', 'quote', 'reason'], 'additionalProperties': False}
    return {'messages': [{'role': 'system', 'content': config['prompt']},
                         {'role': 'user', 'content': item['text']}],
            'tools': [{'type': 'function', 'function': {'name': 'record_claim', 'description': 'Record the source-grounded assessment of the requested claim.', 'parameters': schema}}],
            'tool_choice': config['tool_choice'], 'parallel_tool_calls': False,
            'max_tokens': config['max_tokens'], 'reasoning_effort': config['reasoning_effort']}


if __name__ == '__main__':
    # Optional single-item SDK reproduction; scored batch transport is the bundled runner.
    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(api_key=os.environ[key_name], base_url=BASE_URL, 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 != 'record_claim':
        raise ValueError('Expected exactly one record_claim call; reject extras')
    print(calls[0].function.arguments)
