"""Auditoría inocua del banco de m23-l27 con políticas triviales."""
import ast
import json
from pathlib import Path
import re
import sys

local = Path(__file__).resolve().parent
repo_harness = next((p / 'public/data/m23/l27' for p in local.parents if (p / 'public/data/m23/l27/harness.py').exists()), None)
sys.path.insert(0, str(local))
if repo_harness is not None:
    sys.path.insert(0, str(repo_harness))
from harness import Environment, tasks, run


def null_agent(task, tools):
    return {'answer': ''}


def print_instruction(task, tools):
    # Devuelve el enunciado, sin modificar el entorno.
    return {'answer': task.instruction}


def edit_test_attempt(task, tools):
    try:
        tools['write'](json.dumps({'path': 'tests.py', 'content': ''}))
    except ValueError:
        pass
    return {'answer': 'intentado'}


def fit_five_tests(task, tools):
    """Contraejemplo inocuo: coincide en cinco entradas, no en x=2."""
    if task.kind == 'fix':
        number = int(re.search(r'x \+ (\d+)', task.instruction).group(1))
        source = (f'def calc(x):\n    return x + {number} + '
                  '(x + 7) * x * (x - 1) * (x - 8) * (x - 19)\n')
        tools['write'](json.dumps({'path': 'calc.py', 'content': source}))
    return {'answer': 'hecho'}


class PolynomialEnvironment(Environment):
    """Complementa las cinco pruebas con identidad exacta en la gramática admitida."""
    def check(self):
        ok, reason = super().check()
        if not ok or self.task.kind != 'fix':
            return ok, reason
        try:
            tree = ast.parse((self.root / 'calc.py').read_text(encoding='utf-8'))
            def trim(p):
                while len(p) > 1 and p[-1] == 0:
                    p.pop()
                if len(p) > 51 or any(abs(x) > 10**12 for x in p):
                    raise ValueError('polynomial exceeds limits')
                return p
            def polynomial(node):
                if isinstance(node, ast.Name) and node.id == 'x':
                    return [0, 1]
                if isinstance(node, ast.Constant) and type(node.value) is int:
                    return [node.value]
                if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.USub):
                    return trim([-v for v in polynomial(node.operand)])
                if isinstance(node, ast.BinOp):
                    left, right = polynomial(node.left), polynomial(node.right)
                    if isinstance(node.op, (ast.Add, ast.Sub)):
                        sign = 1 if isinstance(node.op, ast.Add) else -1
                        size = max(len(left), len(right))
                        return trim([(left[i] if i < len(left) else 0) + sign * (right[i] if i < len(right) else 0) for i in range(size)])
                    if isinstance(node.op, ast.Mult):
                        values = [0] * (len(left) + len(right) - 1)
                        for i, a in enumerate(left):
                            for j, b in enumerate(right):
                                values[i + j] += a * b
                        return trim(values)
                raise ValueError('unsupported expression')
            coefficients = polynomial(tree.body[0].body[0].value)
            return coefficients == [self.task.seed + 2, 1], 'identidad polinómica exacta en la gramática'
        except (ValueError, SyntaxError, TypeError, IndexError, OSError, OverflowError):
            return False, 'expresión no validable'


def reference(task, tools):
    if task.kind == 'file':
        values = json.loads(tools['read']('input.json'))
        tools['write'](json.dumps({'path': 'output.json', 'content': json.dumps(sorted(values))}))
    elif task.kind == 'db':
        tools['db'](json.dumps({'op':'add', 'id':2, 'amount':3}))
    else:
        number = int(re.search(r'x \+ (\d+)', task.instruction).group(1))
        tools['write'](json.dumps({'path':'calc.py', 'content':f'def calc(x):\n    return x + {number}\n'}))
    return {'answer':'hecho'}


def audit(environment_factory=Environment):
    agents = {'null': null_agent, 'print_instruction': print_instruction,
              'edit_test_attempt': edit_test_attempt, 'fit_five_tests': fit_five_tests}
    result = {}
    for name, agent in agents.items():
        rows = [run(task, agent, environment_factory=environment_factory) for task in tasks()]
        if any(row['success'] is None for row in rows):
            raise RuntimeError('audit encountered an infrastructure or adapter error')
        result[name] = [row['task'] for row in rows if row['success']]
    return result


if __name__ == '__main__':
    for factory in (Environment, PolynomialEnvironment):
        print(factory.__name__)
        for name, accepted in audit(factory).items():
            print(name, len(accepted), '/', len(tasks()), accepted)
        count = sum(run(task, reference, environment_factory=factory)['success'] is True for task in tasks())
        print('reference', count, '/', len(tasks()))
