"""Synthetic, side-effect-free tool-call fixtures and validation."""
from __future__ import annotations
import copy,math,re
from collections import Counter
from jsonschema import Draft202012Validator


def _schema(properties, required):
    return {'type':'object','properties':properties,'required':required,'additionalProperties':False}


NUM={'type':'integer','minimum':-1000,'maximum':1000}
TEXT={'type':'string','maxLength':200}
TOOLS=[
    {'name':'add','description':'Add two integer numbers and return their sum.','parameters':_schema({'a':NUM,'b':NUM},['a','b'])},
    {'name':'subtract','description':'Subtract the second integer from the first integer.','parameters':_schema({'a':NUM,'b':NUM},['a','b'])},
    {'name':'multiply','description':'Multiply two integer numbers and return their product.','parameters':_schema({'a':NUM,'b':NUM},['a','b'])},
    {'name':'divide','description':'Divide numerator by a nonzero denominator.','parameters':_schema({'numerator':NUM,'denominator':{'type':'integer','minimum':1,'maximum':1000}},['numerator','denominator'])},
    {'name':'uppercase','description':'Convert supplied text to uppercase letters.','parameters':_schema({'text':TEXT},['text'])},
    {'name':'count_words','description':'Count whitespace-separated words in supplied text.','parameters':_schema({'text':TEXT},['text'])},
    {'name':'reverse_text','description':'Reverse characters in supplied text.','parameters':_schema({'text':TEXT},['text'])},
    {'name':'is_even','description':'Check whether an integer is even.','parameters':_schema({'number':NUM},['number'])},
]


def tool_bank(size=8):
    if size not in (8,60):raise ValueError('supported bank sizes are 8 and 60')
    extras=[{'name':f'echo_{i:02d}','description':f'Return the given text unchanged for synthetic channel {i:02d}.',
             'parameters':_schema({'text':TEXT},['text'])} for i in range(52)]
    return copy.deepcopy(TOOLS)+(extras if size==60 else [])


def make_cases(n=150):
    if n<1 or n>1000:raise ValueError('case count must be between 1 and 1000')
    rows=[]
    for i in range(n):
        kind=i%8;a=i%41+1;b=i%13+1;text=f'blue item {i}'
        variants=[
            (f'Add {a} and {b}.','add',{'a':a,'b':b}),
            (f'Subtract {b} from {a}.','subtract',{'a':a,'b':b}),
            (f'Multiply {a} by {b}.','multiply',{'a':a,'b':b}),
            (f'Divide {a} by {b}.','divide',{'numerator':a,'denominator':b}),
            (f'Convert this text to uppercase: {text}','uppercase',{'text':text}),
            (f'Count the words in this text: {text}','count_words',{'text':text}),
            (f'Reverse the characters in this text: {text}','reverse_text',{'text':text}),
            (f'Is the integer {a} even?','is_even',{'number':a}),
        ]
        question,name,args=variants[kind]
        rows.append({'id':i,'question':question,'expected':{'name':name,'arguments':args},'family':name})
    return rows


def validate_call(call,tools):
    if not isinstance(call,dict) or set(call)!={'name','arguments'}:
        return False,'call must contain exactly name and arguments'
    if not isinstance(call['name'],str) or not isinstance(call['arguments'],dict):
        return False,'name must be a string and arguments must be an object'
    tool=next((t for t in tools if t['name']==call['name']),None)
    if tool is None:return False,'unknown tool: '+call['name']
    errors=sorted(Draft202012Validator(tool['parameters']).iter_errors(call['arguments']),key=lambda e:list(map(str,e.path)))
    if errors:
        first=errors[0];path='.'.join(map(str,first.path)) or '$'
        return False,f'{path}: {first.message}'
    return True,'ok'


def dispatch(call,tools):
    ok,error=validate_call(call,tools)
    if not ok:raise ValueError(error)
    name=call['name'];a=call['arguments']
    if name=='add':return a['a']+a['b']
    if name=='subtract':return a['a']-a['b']
    if name=='multiply':return a['a']*a['b']
    if name=='divide':return a['numerator']/a['denominator']
    if name=='uppercase':return a['text'].upper()
    if name=='count_words':return len(a['text'].split())
    if name=='reverse_text':return a['text'][::-1]
    if name=='is_even':return a['number']%2==0
    if name.startswith('echo_'):return a['text']
    raise ValueError('unsupported tool')


def retrieve_tools(query,tools,k):
    if not 1<=k<=len(tools):raise ValueError('k outside tool count')
    tokenize=lambda s:re.findall(r'[a-z0-9]+',s.lower())
    query_words=tokenize(query)
    docs=[tokenize(t['name'].replace('_',' ')+' '+t['description']) for t in tools]
    avg=sum(map(len,docs))/len(docs);df=Counter(word for doc in docs for word in set(doc))
    def score(doc):
        counts=Counter(doc);total=0.0
        for word in query_words:
            f=counts[word]
            if f:
                idf=math.log(1+(len(docs)-df[word]+.5)/(df[word]+.5))
                total+=idf*f*2.2/(f+1.2*(.25+.75*len(doc)/avg))
        return total
    order=sorted(range(len(tools)),key=lambda i:(-score(docs[i]),i))
    return [tools[i] for i in order[:k]]
