"""Reparación por etapas en diez funciones sintéticas del banco l27."""
from collections import Counter
import json
from pathlib import Path
import re
import sys
from localize import rank

here=Path(__file__).resolve().parent
root=next((p for p in here.parents if (p/'public/data/m23/l27/harness.py').exists()),None)
if root is not None:
    sys.path.insert(0,str(root/'public/data/m23/l27'))
    sys.path.insert(0,str(root/'src/widgets/m23/l28'))
from audit import PolynomialEnvironment

def extract_code(text):
    match=re.search(r'```(?:python)?\s*\n(.*?)```',text,re.S|re.I)
    code=(match.group(1) if match else text).strip()
    if not code or len(code)>8000:raise ValueError('invalid patch')
    return code

def repair(task,generate,check_tests,proposals=3):
    """check_tests(code, visible test list) ejecuta código solamente en sandbox."""
    if task.kind!='fix' or proposals<1:raise ValueError('expected fix task')
    env=PolynomialEnvironment(task)
    try:
        original=env.read('calc.py')
        documents={'calc.py':original,'display.py':'def display(x): return str(x)',
                   'stats.py':'def total(xs): return sum(xs)'}
        ranked=rank(task.instruction,documents)
        selection_raw,selection_usage=generate('Select the single file to change for this issue. Reply exactly the file name.\n'
            +task.instruction+'\nCandidates ranked by BM25: '+', '.join(ranked),0)
        selected=selection_raw.strip().strip('`')
        visible_regression=f'assert calc(-1)=={-1+task.seed+2}'
        reproduction=f'assert calc(1)=={1+task.seed+2}'
        candidates=[]
        if selected in documents:
            for i in range(proposals):
                prompt=('Fix the function for this issue. Output only Python code.\n'+task.instruction+
                        '\nSelected file '+selected+':\n'+documents[selected])
                raw,usage=generate(prompt,i+1)
                try:
                    code=extract_code(raw)
                    regression=check_tests(code,[visible_regression])
                    reproduction_pass=check_tests(code,[reproduction])
                except ValueError:
                    code='';regression=False;reproduction_pass=False
                candidates.append({'raw':raw,'code':code,'usage':usage,'regression':regression,
                                   'reproduction':reproduction_pass})
        passing=[x['code'] for x in candidates if x['regression'] and x['reproduction']]
        choice=None
        if passing:
            counts=Counter(passing);choice=next(code for code in passing if counts[code]==max(counts.values()))
        if choice is not None and selected=='calc.py':env.write(json.dumps({'path':'calc.py','content':choice}))
        correct,detail=env.check()
        return {'task':task.id,'bm25_ranking':ranked,'selection_raw':selection_raw,
                'selection_usage':selection_usage,'selected':selected,'candidates':candidates,
                'chosen':choice,'success':bool(correct),'checker':detail,
                'caveat':'decoy files synthetic; only calc.py is writable in benchmark environment'}
    finally:env.close()
