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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
"""
Execute and evaluate generated Gurobi code
"""

import argparse
import json
import os
import re
import subprocess
import sys
from collections import defaultdict
from pathlib import Path
from typing import Dict, List
from concurrent.futures import ProcessPoolExecutor, as_completed
from tqdm import tqdm

from .debug_utils import sanitize_code, save_debug_metadata, write_debug_suggestions

SCRIPT_DIR = Path(__file__).resolve().parent
PROJECT_ROOT = SCRIPT_DIR.parent.parent
DEFAULT_MEMORY_DIR = PROJECT_ROOT / "memory_storage"
DEFAULT_GUIDELINES = DEFAULT_MEMORY_DIR / "category_guidelines.jsonl"
DEFAULT_DEBUG_MEMORY = DEFAULT_MEMORY_DIR / "debug_memory.jsonl"


def extract_objective_value(output: str) -> float:
    """
    Extract objective value from Gurobi output
    
    Args:
        output: stdout from Gurobi code execution
    
    Returns:
        Objective value as float, or None if not found
    """
    if not output or output.strip() == "":
        return None
    
    # Common patterns in Gurobi output
    patterns = [
        r'Optimal\s+[Oo]bjective[:\s]+([+-]?\d+\.?\d*(?:[eE][+-]?\d+)?)',
        r'Obj:\s*([+-]?\d+\.?\d*(?:[eE][+-]?\d+)?)',
        r'Best\s+objective\s+([+-]?\d+\.?\d*(?:[eE][+-]?\d+)?)',
        r'Objective\s+value:\s*([+-]?\d+\.?\d*(?:[eE][+-]?\d+)?)',
        r'OBJECTIVE_VALUE:\s*([+-]?\d+\.?\d*(?:[eE][+-]?\d+)?)',  # Our auto-added pattern
    ]

    for pattern in patterns:
        match = re.search(pattern, output, re.IGNORECASE)
        if match:
            try:
                return float(match.group(1))
            except ValueError:
                continue

    # Fallback: check common custom labels printed by prompts
    fallback_patterns = [
        r'Total\s+Cost[:\s]+([+-]?\d+\.?\d*(?:[eE][+-]?\d+)?)',
        r'Total\s+Profit[:\s]+([+-]?\d+\.?\d*(?:[eE][+-]?\d+)?)',
        r'Total\s+Net\s+Profit[:\s]+([+-]?\d+\.?\d*(?:[eE][+-]?\d+)?)',
        r'Total\s+Revenue[:\s]+([+-]?\d+\.?\d*(?:[eE][+-]?\d+)?)',
    ]

    for pattern in fallback_patterns:
        match = re.search(pattern, output, re.IGNORECASE)
        if match:
            try:
                return float(match.group(1))
            except ValueError:
                continue

    return None


def enhance_code_with_objective_print(code: str) -> str:
    """
    Add objective value printing to code if not already present
    
    This helps ensure we can extract the objective value even if
    the generated code doesn't print it explicitly.
    
    Note: Always adds a fallback print to handle cases where existing
    prints are conditional (e.g., inside if status == OPTIMAL blocks)
    """
    # Add code to print objective value (always add as a safety measure)
    enhancement_code = """
# Auto-added: Print objective value for evaluation (fallback)
try:
    # Try common variable names for Gurobi model
    if 'model' in dir():
        mdl = model
    elif 'm' in dir():
        mdl = m
    elif 'Model' in dir():
        mdl = Model
    else:
        mdl = None
    
    # Fallback: scan globals for a likely Gurobi model instance.
    # This helps when the generated code uses a non-standard variable name.
    if mdl is None:
        try:
            for _name, _val in list(globals().items()):
                try:
                    if hasattr(_val, 'objVal') and hasattr(_val, 'optimize'):
                        mdl = _val
                        break
                except Exception:
                    continue
        except Exception:
            pass

    if mdl is not None and hasattr(mdl, 'objVal'):
        try:
            obj_value = mdl.objVal
            print(f"OBJECTIVE_VALUE: {obj_value}")
        except:
            # Model might not have been solved yet
            pass
except:
    pass
"""
    
    return code + "\n" + enhancement_code


def execute_code(code: str, problem_id: int, output_dir: str, timeout: int = 60) -> Dict:
    """
    Execute Gurobi code and capture results
    
    Args:
        code: Python code to execute
        problem_id: Problem ID
        output_dir: Directory to save code files
        timeout: Execution timeout in seconds
    
    Returns:
        Dictionary with execution results
    """
    # Create output directory
    code_dir = os.path.join(output_dir, 'code')
    os.makedirs(code_dir, exist_ok=True)

    sanitized_code, debug_meta = sanitize_code(code, problem_id)
    code_enhanced = enhance_code_with_objective_print(sanitized_code)
    
    # Save code to file
    code_file = os.path.join(code_dir, f'problem_{problem_id}.py')
    with open(code_file, 'w', encoding='utf-8') as f:
        f.write(code_enhanced)

    # Persist debug metadata if anything noteworthy was detected
    save_debug_metadata(debug_meta, output_dir)
    
    # Execute code
    try:
        result = subprocess.run(
            [sys.executable, f'problem_{problem_id}.py'],
            capture_output=True,
            text=True,
            timeout=timeout,
            cwd=code_dir
        )
        
        stdout = result.stdout
        stderr = result.stderr
        returncode = result.returncode
        
        if returncode == 0:
            obj_value = extract_objective_value(stdout)
            if obj_value is not None:
                return {
                    'status': 'success',
                    'objective_value': obj_value,
                    'stdout': stdout,
                    'stderr': stderr
                }
            else:
                return {
                    'status': 'success_no_objective',
                    'objective_value': None,
                    'stdout': stdout,
                    'stderr': stderr
                }
        else:
            return {
                'status': 'execution_error',
                'objective_value': None,
                'stdout': stdout,
                'stderr': stderr,
                'returncode': returncode
            }
            
    except subprocess.TimeoutExpired:
        return {
            'status': 'timeout',
            'objective_value': None,
            'stdout': '',
            'stderr': f'Execution timeout after {timeout} seconds'
        }
    except Exception as e:
        return {
            'status': 'error',
            'objective_value': None,
            'stdout': '',
            'stderr': str(e)
        }


def check_correctness(pred_obj: float, gt_obj: float, tolerance: float = 0.05, 
                     use_relative: bool = True) -> bool:
    """
    Check if predicted objective matches ground truth
    
    Args:
        pred_obj: Predicted objective value
        gt_obj: Ground truth objective value
        tolerance: Tolerance for comparison
        use_relative: Use relative tolerance if True, absolute if False
    
    Returns:
        True if values match within tolerance
    """
    if pred_obj is None or gt_obj is None:
        return False
    
    try:
        pred_obj = float(pred_obj)
        gt_obj = float(gt_obj)
        
        if gt_obj == 0:
            return abs(pred_obj) <= tolerance
        
        if use_relative:
            return abs((pred_obj - gt_obj) / gt_obj) <= tolerance
        else:
            return abs(pred_obj - gt_obj) <= tolerance
    except (ValueError, TypeError):
        return False


def evaluate_results(results: List[Dict], args) -> Dict:
    """
    Evaluate execution results
    
    Args:
        results: List of result dictionaries
        args: Command line arguments
    
    Returns:
        Evaluation report dictionary
    """
    total = len(results)
    correct = 0
    
    status_counts = defaultdict(int)
    correct_ids = []
    incorrect_details = []
    
    for result in results:
        status = result['execution_status']
        status_counts[status] += 1
        
        if status == 'success' and result['is_correct']:
            correct += 1
            correct_ids.append(result['id'])
        elif status == 'success' and not result['is_correct']:
            incorrect_details.append({
                'id': result['id'],
                'predicted': result['predicted_objective'],
                'ground_truth': result['ground_truth']
            })
    
    accuracy = correct / total if total > 0 else 0.0
    
    report = {
        'total_problems': total,
        'correct': correct,
        'accuracy': accuracy,
        'status_counts': dict(status_counts),
        'correct_ids': correct_ids,
        'incorrect_details': incorrect_details[:10],  # Save first 10 for reference
        'settings': {
            'tolerance': args.tolerance,
            'use_relative_tolerance': args.use_relative_tolerance,
            'timeout': args.timeout
        }
    }
    
    return report


def process_single_problem(gen_result, args):
    """Process a single problem (for parallel execution)"""
    problem_id = gen_result['id']
    code = gen_result['generated_code']
    gt_answer = gen_result.get('answer')
    
    if not code:
        result = {
            'id': problem_id,
            'execution_status': 'no_code',
            'predicted_objective': None,
            'ground_truth': gt_answer,
            'is_correct': False
        }
    else:
        exec_result = execute_code(code, problem_id, args.output_dir, args.timeout)
        
        pred_obj = exec_result['objective_value']
        is_correct = False
        
        if pred_obj is not None and gt_answer is not None:
            try:
                gt_obj = float(gt_answer)
                is_correct = check_correctness(
                    pred_obj, gt_obj, 
                    args.tolerance, 
                    args.use_relative_tolerance
                )
            except (ValueError, TypeError):
                is_correct = False
        
        result = {
            'id': problem_id,
            'execution_status': exec_result['status'],
            'predicted_objective': pred_obj,
            'ground_truth': gt_answer,
            'is_correct': is_correct,
            'stdout': exec_result['stdout'][:500] if args.save_output else '',
            'stderr': exec_result['stderr'][:500] if args.save_output else ''
        }
    
    return result


def main(args):
    # Load generated results
    if not os.path.exists(args.input_file):
        raise FileNotFoundError(f"Input file not found: {args.input_file}")
    
    with open(args.input_file, 'r', encoding='utf-8') as f:
        generated_results = [json.loads(line) for line in f if line.strip()]
    
    print(f"Loaded {len(generated_results)} generated results")
    
    # Create output directory
    os.makedirs(args.output_dir, exist_ok=True)
    id_to_problem = {record['id']: record for record in generated_results}

    debug_store = None
    memory_helper = None
    memory_bank = None
    if not args.disable_debug_memory:
        try:
            from .debug_memory import DebugMemoryStore
            from .memory_bank import MemoryBank
            from .memory_intelligence import MemoryIntelligence
        except ModuleNotFoundError as exc:
            print(
                f"⚠️  Debug-memory dependencies missing ({exc}). "
                "Continuing with --disable_debug_memory behavior."
            )
            args.disable_debug_memory = True
        else:
            debug_store = DebugMemoryStore(args.debug_memory_path)
            if args.category_guidelines_path:
                try:
                    memory_helper = MemoryIntelligence(args.category_guidelines_path)
                except Exception as exc:  # noqa: BLE001
                    print(f"Warning: failed to load category guidelines ({exc})")
            if args.memory_dir:
                try:
                    if args.embedding_model:
                        memory_bank = MemoryBank(args.memory_dir, embedding_model=args.embedding_model)
                    else:
                        memory_bank = MemoryBank(args.memory_dir)
                except Exception as exc:  # noqa: BLE001
                    print(f"Warning: failed to load memory bank from {args.memory_dir} ({exc})")
    
    # Execute and evaluate each result
    evaluation_results = []
    
    if args.num_workers > 1:
        # Parallel execution
        print(f"Using {args.num_workers} workers for parallel execution")
        with ProcessPoolExecutor(max_workers=args.num_workers) as executor:
            # Submit all tasks
            future_to_problem = {
                executor.submit(process_single_problem, gen_result, args): gen_result
                for gen_result in generated_results
            }
            
            # Collect results with progress bar
            with tqdm(total=len(generated_results), desc="Executing") as pbar:
                for future in as_completed(future_to_problem):
                    try:
                        result = future.result()
                        evaluation_results.append(result)
                        status_symbol = '✓' if result['is_correct'] else '✗'
                        pbar.set_postfix_str(f"Problem {result['id']}: {status_symbol}")
                        pbar.update(1)
                    except Exception as e:
                        gen_result = future_to_problem[future]
                        print(f"\nError processing problem {gen_result['id']}: {e}")
                        evaluation_results.append({
                            'id': gen_result['id'],
                            'execution_status': 'error',
                            'predicted_objective': None,
                            'ground_truth': gen_result.get('answer'),
                            'is_correct': False,
                            'stdout': '',
                            'stderr': str(e)
                        })
                        pbar.update(1)
        
        # Sort results by ID to maintain order
        evaluation_results.sort(key=lambda x: x['id'])
    else:
        # Sequential execution (original behavior)
        for gen_result in generated_results:
            problem_id = gen_result['id']
            print(f"Processing problem {problem_id}...", end=' ')
            
            result = process_single_problem(gen_result, args)
            evaluation_results.append(result)
            
            status_symbol = '✓' if result['is_correct'] else '✗'
            print(f"{status_symbol} [{result['execution_status']}]")
    
    # Provide memory-aided suggestions for failures
    if not args.disable_debug_memory:
        for result in evaluation_results:
            status = result['execution_status']
            if status in ('execution_error', 'success_no_objective', 'timeout', 'no_code'):
                gen_result = id_to_problem.get(result['id'], {})
                description = gen_result.get('description', '')
                error_message = result.get('stderr') or result.get('stdout') or ''
                if not error_message:
                    if status == 'timeout':
                        error_message = 'Execution timeout'
                    elif status == 'no_code':
                        error_message = 'No code was generated for execution.'
                    elif status == 'success_no_objective':
                        error_message = 'Execution succeeded but no objective value was captured.'
                write_debug_suggestions(
                    problem_id=result['id'],
                    description=description,
                    error_message=error_message,
                    memory_helper=memory_helper,
                    memory_bank=memory_bank,
                    output_dir=args.output_dir,
                    status=status,
                    debug_store=debug_store,
                )

    # Generate evaluation report
    report = evaluate_results(evaluation_results, args)
    
    # Save detailed results
    results_file = os.path.join(args.output_dir, 'evaluation_results.jsonl')
    with open(results_file, 'w', encoding='utf-8') as f:
        for result in evaluation_results:
            f.write(json.dumps(result, ensure_ascii=False) + '\n')
    
    # Save evaluation report
    report_file = os.path.join(args.output_dir, 'evaluation_report.json')
    with open(report_file, 'w', encoding='utf-8') as f:
        json.dump(report, f, indent=2, ensure_ascii=False)
    
    # Print summary
    print(f"\n{'='*60}")
    print("EVALUATION SUMMARY")
    print(f"{'='*60}")
    print(f"Total problems:  {report['total_problems']}")
    print(f"Correct:         {report['correct']}")
    print(f"Accuracy:        {report['accuracy']:.2%}")
    print(f"\nStatus breakdown:")
    for status, count in sorted(report['status_counts'].items()):
        print(f"  {status:20s}: {count:3d} ({count/report['total_problems']:.1%})")
    print(f"{'='*60}")
    print(f"\nResults saved to:")
    print(f"  {results_file}")
    print(f"  {report_file}")


def parse_args():
    parser = argparse.ArgumentParser(description="Execute and evaluate generated Gurobi code")
    
    parser.add_argument("--input_file", type=str, required=True,
                        help="Path to generated results JSONL file")
    parser.add_argument("--output_dir", type=str, required=True,
                        help="Directory to save execution results")
    parser.add_argument("--timeout", type=int, default=60,
                        help="Timeout for code execution (seconds)")
    parser.add_argument("--tolerance", type=float, default=0.05,
                        help="Tolerance for answer comparison")
    parser.add_argument("--use_relative_tolerance", action="store_true",
                        help="Use relative tolerance (default: absolute)")
    parser.add_argument("--save_output", action="store_true",
                        help="Save stdout/stderr in results")
    parser.add_argument("--num_workers", type=int, default=100,
                        help="Number of parallel workers for execution")
    parser.add_argument("--memory_dir", type=str, default=str(DEFAULT_MEMORY_DIR),
                        help="Path to episodic memory directory (used for debug suggestions)")
    parser.add_argument("--embedding_model", type=str, default=None,
                        help="Optional embedding model name or local path for debug-memory retrieval")
    parser.add_argument("--category_guidelines_path", type=str,
                        default=str(DEFAULT_GUIDELINES),
                        help="Path to category guideline JSONL file")
    parser.add_argument("--debug_memory_path", type=str,
                        default=str(DEFAULT_DEBUG_MEMORY),
                        help="Path to persistent debug memory JSONL file")
    parser.add_argument("--disable_debug_memory", action="store_true",
                        help="Disable memory-based debug suggestions")
    
    return parser.parse_args()


if __name__ == "__main__":
    args = parse_args()
    main(args)