#!/usr/bin/env python3
"""Fixed local pure-function exercises. Trusted learner code, not a hostile-code sandbox."""
import argparse
import copy
import hashlib
import importlib.util
import json
import math
from pathlib import Path
import re
import subprocess
import sys

ROOT = Path(__file__).resolve().parent
VERSION = 'extended-agent-practice-v1'

def digest(path):
    return hashlib.sha256(Path(path).read_bytes()).hexdigest()

def json_value(value):
    if type(value) is dict:
        return all(type(k) is str and json_value(v) for k, v in value.items())
    if type(value) is list:
        return all(json_value(v) for v in value)
    if type(value) is float:
        return math.isfinite(value)
    return type(value) in (str, int, bool, type(None))

def exact(a, b):
    if type(a) is not type(b):
        return False
    if type(a) is dict:
        return a.keys() == b.keys() and all(exact(a[k], b[k]) for k in a)
    if type(a) is list:
        return len(a) == len(b) and all(exact(x, y) for x, y in zip(a, b))
    return a == b

def read_contract(course):
    if not re.fullmatch(r'[a-z][a-z0-9-]*', course):
        raise ValueError('course_id')
    path = ROOT / 'cases' / (course + '.json')
    contract = json.loads(path.read_text(encoding='utf-8'))
    if type(contract) is not dict or set(contract) != {'schemaVersion', 'id', 'function', 'starter', 'checks'}:
        raise ValueError('contract_shape')
    if type(contract['schemaVersion']) is not int or contract['schemaVersion'] != 1 or contract['id'] != course:
        raise ValueError('contract_identity')
    if type(contract['function']) is not str or not re.fullmatch(r'[a-z][a-z0-9_]*', contract['function']):
        raise ValueError('contract_function')
    if type(contract['starter']) is not str:
        raise ValueError('contract_starter')
    if type(contract['checks']) is not list or len(contract['checks']) < 8:
        raise ValueError('contract_cases')
    seen = set()
    for case in contract['checks']:
        if type(case) is not dict or set(case) != {'id', 'input', 'expected', 'error'}:
            raise ValueError('case_shape')
        if type(case['id']) is not str or not case['id'] or case['id'] in seen:
            raise ValueError('case_identity')
        seen.add(case['id'])
        if not json_value(case['input']) or not json_value(case['expected']):
            raise ValueError('case_json')
        if case['error'] is not None and (type(case['error']) is not str or ':' not in case['error'] or case['expected'] is not None):
            raise ValueError('case_error')
    return contract, path

def load_module(path):
    # Register before execution: future annotations and dataclasses remain valid.
    sys.path.insert(0, str(Path(path).resolve().parent))
    name = '_extended_learner'
    spec = importlib.util.spec_from_file_location(name, path)
    if spec is None or spec.loader is None:
        raise ValueError('module_path')
    module = importlib.util.module_from_spec(spec)
    sys.modules[name] = module
    spec.loader.exec_module(module)
    return module

def container_ids(value):
    found = set()
    if type(value) in (dict, list):
        found.add(id(value))
        for child in (value.values() if type(value) is dict else value):
            found.update(container_ids(child))
    return found

def passed_result(case, row):
    if row['controlled_failure'] or not row['input_unchanged'] or not row['return_json_valid'] or not row['result_alias_free']:
        return False
    if case['error'] is not None:
        return row['actual'] is None and row['error'] == case['error']
    return row['error'] is None and exact(row['actual'], case['expected'])

def case_fields(course, function, case):
    return {'course':course, 'function':function, 'case_id':case['id'],
            'input':case['input'], 'expected':case['expected'], 'expected_error':case['error']}

def run_case(path, course, function, case):
    payload = copy.deepcopy(case['input'])
    before = copy.deepcopy(payload)
    actual, error, controlled_failure = None, None, False
    loaded = False
    try:
        module = load_module(path)
        loaded = True
        actual = getattr(module, function)(payload)
    except BaseException as exc:
        error = type(exc).__name__ + ':' + str(exc)
        controlled_failure = not loaded or not isinstance(exc, Exception)
    try:
        unchanged = exact(payload, before)
        alias_free = not bool(container_ids(actual) & container_ids(payload))
    except RecursionError:
        unchanged, alias_free = False, False
    try:
        valid = json_value(actual)
        json.dumps(actual, allow_nan=False)
    except (RecursionError, ValueError, TypeError):
        valid = False
    if not valid:
        actual = {'invalid_return_type':type(actual).__name__}
    row = case_fields(course, function, case)
    row.update(actual=actual, error=error, controlled_failure=controlled_failure,
               input_unchanged=unchanged, result_alias_free=alias_free, return_json_valid=valid)
    row['passed'] = passed_result(case, row)
    return row

def validate_packet(course, function, case, row, returncode):
    fields = case_fields(course, function, case)
    flags = {'passed', 'controlled_failure', 'input_unchanged', 'result_alias_free', 'return_json_valid'}
    if type(row) is not dict or set(row) != set(fields) | flags | {'actual', 'error'}:
        raise ValueError('worker_packet_shape')
    if any(not exact(row[k], v) for k, v in fields.items()):
        raise ValueError('worker_packet_case')
    if any(type(row[k]) is not bool for k in flags):
        raise ValueError('worker_packet_flags')
    if row['error'] is not None and type(row['error']) is not str:
        raise ValueError('worker_packet_error')
    if not json_value(row):
        raise ValueError('worker_packet_json')
    passed = passed_result(case, row)
    if row['passed'] != passed or returncode != (0 if passed else 1):
        raise ValueError('worker_packet_claim_or_exit')
    return passed

def grade(path, course):
    contract, case_path = read_contract(course)
    rows = []
    for index, case in enumerate(contract['checks']):
        process = None
        try:
            process = subprocess.run([sys.executable, '-B', str(ROOT / 'lab_runner.py'), '_case',
                '--course', course, '--module', str(Path(path).resolve()), '--index', str(index)],
                text=True, capture_output=True, timeout=5)
            row = json.loads(process.stdout.splitlines()[-1])
            validate_packet(course, contract['function'], case, row, process.returncode)
        except (ValueError, TypeError, IndexError, KeyError, OSError, subprocess.TimeoutExpired) as exc:
            row = case_fields(course, contract['function'], case)
            row.update(actual=None, error=None, controlled_failure=True, input_unchanged=False,
                result_alias_free=False, return_json_valid=False, passed=False,
                worker_error=type(exc).__name__ + ':' + str(exc),
                worker_stderr=process.stderr[-1000:] if process else '',
                worker_returncode=process.returncode if process else None)
        rows.append(row)
    return {'version':VERSION, 'course':course, 'function':contract['function'],
            'passed':bool(rows) and all(row['passed'] for row in rows),
            'passed_checks':sum(row['passed'] for row in rows), 'total_checks':len(rows), 'checks':rows,
            'runner_sha256':digest(ROOT / 'lab_runner.py'), 'cases_sha256':digest(case_path),
            'student_sha256':digest(path), 'python':sys.version,
            'scope':'Public fixed local pure-function cases; author calibration is not learner mastery, production integration, security isolation or a job-level certificate; 5s is a hang guard, not a performance threshold.'}

def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('command', choices=['scaffold','grade','_case'])
    parser.add_argument('--course', required=True)
    parser.add_argument('--module')
    parser.add_argument('--out')
    parser.add_argument('--index', type=int)
    args = parser.parse_args()
    try:
        contract, _ = read_contract(args.course)
    except (ValueError, OSError) as exc:
        parser.error(str(exc))
    if args.command == 'scaffold':
        if not args.out:
            parser.error('scaffold requires --out')
        try:
            with Path(args.out).open('x', encoding='utf-8') as handle:
                handle.write(contract['starter'])
        except FileExistsError:
            parser.error('refusing to overwrite learner module')
        print(json.dumps({'created':args.out, 'course':args.course})); return 0
    if not args.module:
        parser.error('requires --module')
    if args.command == '_case':
        if args.index is None or not 0 <= args.index < len(contract['checks']):
            parser.error('case index')
        row = run_case(args.module, args.course, contract['function'], contract['checks'][args.index])
        print(json.dumps(row, sort_keys=True, allow_nan=False)); return 0 if row['passed'] else 1
    if not args.out:
        parser.error('grade requires --out')
    report = grade(args.module, args.course)
    Path(args.out).write_text(json.dumps(report, sort_keys=True, indent=2, allow_nan=False) + '\n', encoding='utf-8')
    print(json.dumps({k:v for k,v in report.items() if k != 'checks'}, sort_keys=True))
    return 0 if report['passed'] else 1

if __name__ == '__main__':
    sys.exit(main())
