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
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
"""
Test the /schedule endpoint with properly generated data.
Saves both input and output to JSON files.
Tests with both 25 and 30 trainsets.
Uses 3 data generation methods:
1. API's /generate-synthetic endpoint
2. DataService.enhanced_generator (our synthetic generator)
3. Local inline generator
"""
import requests
import json
from datetime import datetime, timedelta
import os
import random
import sys

# Add parent path for imports
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from DataService.enhanced_generator import EnhancedMetroDataGenerator

BASE_URL = "http://localhost:7860"


def generate_synthetic_data_local(num_trainsets: int) -> dict:
    """Generate synthetic data locally without using API."""
    
    trainset_status = []
    fitness_certificates = []
    component_health = []
    
    # Status distribution: 80% available (IN_SERVICE/STANDBY), 20% other
    available_count = int(num_trainsets * 0.80)
    
    departments = ["ROLLING_STOCK", "ELECTRICAL", "MECHANICAL", "SAFETY", "OPERATIONS"]
    components = ["Traction_Motor", "Brake_System", "HVAC", "Door_System", "Pantograph", 
                  "Bogie", "Coupler", "Battery"]
    
    for i in range(1, num_trainsets + 1):
        ts_id = f"TS-{i:03d}"
        
        # Determine operational status
        if i <= available_count:
            if i % 3 == 0:
                status = "STANDBY"
            else:
                status = "IN_SERVICE"
        else:
            status = random.choice(["MAINTENANCE", "OUT_OF_SERVICE"])
        
        # Trainset status
        trainset_status.append({
            "trainset_id": ts_id,
            "operational_status": status,
            "last_maintenance_date": (datetime.now() - timedelta(days=random.randint(10, 90))).strftime("%Y-%m-%d"),
            "total_mileage_km": round(random.uniform(50000, 200000), 2),
            "age_years": random.randint(1, 8)
        })
        
        # Fitness certificates - one per department
        for dept in departments:
            issue_date = datetime.now() - timedelta(days=random.randint(30, 180))
            expiry_date = issue_date + timedelta(days=365)
            
            # 90% valid, 10% expired or other
            if random.random() < 0.90:
                cert_status = "ISSUED"
            else:
                cert_status = random.choice(["EXPIRED", "PENDING", "SUSPENDED"])
            
            fitness_certificates.append({
                "trainset_id": ts_id,
                "department": dept,
                "status": cert_status,
                "issue_date": issue_date.strftime("%Y-%m-%d"),
                "expiry_date": expiry_date.strftime("%Y-%m-%d")
            })
        
        # Component health - one per component
        for comp in components:
            # 85% healthy, 15% with issues
            if random.random() < 0.85:
                comp_status = random.choice(["EXCELLENT", "GOOD"])
                wear = round(random.uniform(10, 50), 1)
            else:
                comp_status = random.choice(["FAIR", "POOR", "CRITICAL"])
                wear = round(random.uniform(60, 95), 1)
            
            component_health.append({
                "trainset_id": ts_id,
                "component": comp,
                "status": comp_status,
                "wear_level": wear,
                "last_inspection": (datetime.now() - timedelta(days=random.randint(1, 30))).strftime("%Y-%m-%d")
            })
    
    return {
        "trainset_status": trainset_status,
        "fitness_certificates": fitness_certificates,
        "component_health": component_health
    }


def test_with_api_generator(num_trainsets: int, output_dir: str):
    """Test using API's /generate-synthetic endpoint."""
    
    print(f"\n{'='*70}")
    print(f"Test with API Generator - {num_trainsets} trainsets")
    print(f"{'='*70}")
    
    # Step 1: Generate synthetic data via API
    print("\nStep 1: Generating synthetic data via /generate-synthetic...")
    
    gen_response = requests.post(
        f"{BASE_URL}/generate-synthetic",
        json={"num_trainsets": num_trainsets}
    )
    
    if gen_response.status_code != 200:
        print(f"❌ Failed to generate synthetic data: {gen_response.status_code}")
        print(gen_response.text)
        return False
    
    gen_result = gen_response.json()
    synthetic_data = gen_result["data"]
    
    # Remove job_cards
    synthetic_data.pop("job_cards", None)
    
    print(f"βœ“ Generated: {len(synthetic_data['trainset_status'])} trainsets, "
          f"{len(synthetic_data['fitness_certificates'])} certificates, "
          f"{len(synthetic_data['component_health'])} component records")
    
    # Count by status
    status_counts = {}
    for ts in synthetic_data['trainset_status']:
        status = ts['operational_status']
        status_counts[status] = status_counts.get(status, 0) + 1
    print(f"  Status breakdown: {status_counts}")
    
    # Step 2: Prepare schedule request
    schedule_request = {
        "trainset_status": synthetic_data["trainset_status"],
        "fitness_certificates": synthetic_data["fitness_certificates"],
        "component_health": synthetic_data["component_health"],
        "date": datetime.now().strftime("%Y-%m-%d"),
        "method": "ga",
        "config": {
            "required_service_trains": 15,
            "min_standby": 2,
            "population_size": 50,
            "generations": 100
        }
    }
    
    # Save input
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    input_file = f"{output_dir}/api_gen_{num_trainsets}_input_{timestamp}.json"
    output_file = f"{output_dir}/api_gen_{num_trainsets}_output_{timestamp}.json"
    
    with open(input_file, 'w') as f:
        json.dump(schedule_request, f, indent=2)
    print(f"βœ“ Input saved: {input_file}")
    
    # Step 3: Call /schedule endpoint
    print("\nStep 2: Calling /schedule endpoint...")
    
    schedule_response = requests.post(
        f"{BASE_URL}/schedule",
        json=schedule_request
    )
    
    if schedule_response.status_code != 200:
        print(f"❌ Schedule endpoint failed: {schedule_response.status_code}")
        error_file = f"{output_dir}/api_gen_{num_trainsets}_error_{timestamp}.json"
        with open(error_file, 'w') as f:
            json.dump({"status_code": schedule_response.status_code, "error": schedule_response.text}, f, indent=2)
        print(f"Error saved: {error_file}")
        return False
    
    schedule_result = schedule_response.json()
    
    with open(output_file, 'w') as f:
        json.dump(schedule_result, f, indent=2)
    print(f"βœ“ Output saved: {output_file}")
    
    # Print summary
    print_schedule_summary(schedule_result)
    
    return True


def test_with_local_generator(num_trainsets: int, output_dir: str):
    """Test using locally generated data."""
    
    print(f"\n{'='*70}")
    print(f"Test with Local Generator - {num_trainsets} trainsets")
    print(f"{'='*70}")
    
    # Step 1: Generate synthetic data locally
    print("\nStep 1: Generating synthetic data locally...")
    
    synthetic_data = generate_synthetic_data_local(num_trainsets)
    
    print(f"βœ“ Generated: {len(synthetic_data['trainset_status'])} trainsets, "
          f"{len(synthetic_data['fitness_certificates'])} certificates, "
          f"{len(synthetic_data['component_health'])} component records")
    
    # Count by status
    status_counts = {}
    for ts in synthetic_data['trainset_status']:
        status = ts['operational_status']
        status_counts[status] = status_counts.get(status, 0) + 1
    print(f"  Status breakdown: {status_counts}")
    
    # Step 2: Prepare schedule request
    schedule_request = {
        "trainset_status": synthetic_data["trainset_status"],
        "fitness_certificates": synthetic_data["fitness_certificates"],
        "component_health": synthetic_data["component_health"],
        "date": datetime.now().strftime("%Y-%m-%d"),
        "method": "ga",
        "config": {
            "required_service_trains": 15,
            "min_standby": 2,
            "population_size": 50,
            "generations": 100
        }
    }
    
    # Save input
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    input_file = f"{output_dir}/local_gen_{num_trainsets}_input_{timestamp}.json"
    output_file = f"{output_dir}/local_gen_{num_trainsets}_output_{timestamp}.json"
    
    with open(input_file, 'w') as f:
        json.dump(schedule_request, f, indent=2)
    print(f"βœ“ Input saved: {input_file}")
    
    # Step 3: Call /schedule endpoint
    print("\nStep 2: Calling /schedule endpoint...")
    
    schedule_response = requests.post(
        f"{BASE_URL}/schedule",
        json=schedule_request
    )
    
    if schedule_response.status_code != 200:
        print(f"❌ Schedule endpoint failed: {schedule_response.status_code}")
        error_file = f"{output_dir}/local_gen_{num_trainsets}_error_{timestamp}.json"
        with open(error_file, 'w') as f:
            json.dump({"status_code": schedule_response.status_code, "error": schedule_response.text}, f, indent=2)
        print(f"Error saved: {error_file}")
        return False
    
    schedule_result = schedule_response.json()
    
    with open(output_file, 'w') as f:
        json.dump(schedule_result, f, indent=2)
    print(f"βœ“ Output saved: {output_file}")
    
    # Print summary
    print_schedule_summary(schedule_result)
    
    return True


def print_schedule_summary(schedule_result: dict):
    """Print a summary of the schedule result."""
    
    print(f"\n--- Schedule Summary ---")
    print(f"Schedule ID: {schedule_result.get('schedule_id')}")
    print(f"Generated At: {schedule_result.get('generated_at')}")
    print(f"Valid: {schedule_result.get('valid_from')} to {schedule_result.get('valid_until')}")
    print(f"Depot: {schedule_result.get('depot')}")
    
    # Fleet summary
    fleet = schedule_result.get('fleet_summary', {})
    print(f"\nFleet Summary:")
    print(f"  Total: {fleet.get('total_trainsets')}")
    print(f"  Revenue Service: {fleet.get('revenue_service')}")
    print(f"  Standby: {fleet.get('standby')}")
    print(f"  Maintenance: {fleet.get('maintenance')}")
    print(f"  Availability: {fleet.get('availability_percent', 0):.1f}%")
    
    # Optimization metrics
    metrics = schedule_result.get('optimization_metrics', {})
    print(f"\nOptimization:")
    print(f"  Fitness: {metrics.get('fitness_score', 0):.4f}")
    print(f"  Method: {metrics.get('method')}")
    print(f"  Total Planned KM: {metrics.get('total_planned_km', 0):.1f}")
    print(f"  Runtime: {metrics.get('optimization_runtime_ms', 0)} ms")
    
    # Trainset details
    trainsets = schedule_result.get('trainsets', [])
    print(f"\nTrainsets ({len(trainsets)}):")
    
    # Group by status
    by_status = {}
    for ts in trainsets:
        status = ts.get('status', 'UNKNOWN')
        if status not in by_status:
            by_status[status] = []
        by_status[status].append(ts)
    
    for status in ['REVENUE_SERVICE', 'STANDBY', 'MAINTENANCE']:
        if status in by_status:
            count = len(by_status[status])
            print(f"\n  {status} ({count}):")
            for ts in by_status[status][:3]:
                blocks = ts.get('service_blocks', [])
                block_info = f", {len(blocks)} blocks" if blocks else ""
                print(f"    {ts['trainset_id']}: km={ts.get('daily_km_allocation', 0):.1f}{block_info}")
            if count > 3:
                print(f"    ... and {count - 3} more")
    
    # Alerts
    alerts = schedule_result.get('alerts', [])
    if alerts:
        print(f"\nAlerts ({len(alerts)}):")
        for alert in alerts[:3]:
            print(f"  [{alert.get('severity')}] {alert.get('trainset_id')}: {alert.get('message')[:50]}")
        if len(alerts) > 3:
            print(f"  ... and {len(alerts) - 3} more")


def test_with_dataservice_generator(num_trainsets: int, output_dir: str):
    """Test using DataService.enhanced_generator (our synthetic generator)."""
    
    print(f"\n{'='*70}")
    print(f"Test with DataService Generator - {num_trainsets} trainsets")
    print(f"{'='*70}")
    
    # Step 1: Generate synthetic data using EnhancedMetroDataGenerator
    print("\nStep 1: Generating data with EnhancedMetroDataGenerator...")
    
    try:
        generator = EnhancedMetroDataGenerator(num_trainsets=num_trainsets)
        data = generator.generate_complete_enhanced_dataset()
    except Exception as e:
        print(f"❌ Failed to generate data: {e}")
        return False
    
    # Remove job_cards (not needed)
    synthetic_data = {
        "trainset_status": data["trainset_status"],
        "fitness_certificates": data["fitness_certificates"],
        "component_health": data["component_health"]
    }
    
    print(f"βœ“ Generated: {len(synthetic_data['trainset_status'])} trainsets, "
          f"{len(synthetic_data['fitness_certificates'])} certificates, "
          f"{len(synthetic_data['component_health'])} component records")
    
    # Count by status
    status_counts = {}
    for ts in synthetic_data['trainset_status']:
        status = ts['operational_status']
        status_counts[status] = status_counts.get(status, 0) + 1
    print(f"  Status breakdown: {status_counts}")
    
    # Step 2: Prepare schedule request
    schedule_request = {
        "trainset_status": synthetic_data["trainset_status"],
        "fitness_certificates": synthetic_data["fitness_certificates"],
        "component_health": synthetic_data["component_health"],
        "date": datetime.now().strftime("%Y-%m-%d"),
        "method": "ga",
        "config": {
            "required_service_trains": 15,
            "min_standby": 2,
            "population_size": 50,
            "generations": 100
        }
    }
    
    # Save input
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    input_file = f"{output_dir}/dataservice_gen_{num_trainsets}_input_{timestamp}.json"
    output_file = f"{output_dir}/dataservice_gen_{num_trainsets}_output_{timestamp}.json"
    
    with open(input_file, 'w') as f:
        json.dump(schedule_request, f, indent=2)
    print(f"βœ“ Input saved: {input_file}")
    
    # Step 3: Call /schedule endpoint
    print("\nStep 2: Calling /schedule endpoint...")
    
    schedule_response = requests.post(
        f"{BASE_URL}/schedule",
        json=schedule_request
    )
    
    if schedule_response.status_code != 200:
        print(f"❌ Schedule endpoint failed: {schedule_response.status_code}")
        error_file = f"{output_dir}/dataservice_gen_{num_trainsets}_error_{timestamp}.json"
        with open(error_file, 'w') as f:
            json.dump({"status_code": schedule_response.status_code, "error": schedule_response.text}, f, indent=2)
        print(f"Error saved: {error_file}")
        return False
    
    schedule_result = schedule_response.json()
    
    with open(output_file, 'w') as f:
        json.dump(schedule_result, f, indent=2)
    print(f"βœ“ Output saved: {output_file}")
    
    # Print summary
    print_schedule_summary(schedule_result)
    
    return True


def main():
    """Run all tests."""
    
    # Create output directory
    output_dir = "test_output"
    os.makedirs(output_dir, exist_ok=True)
    
    print("="*70)
    print("Schedule Endpoint Test Suite")
    print("="*70)
    print(f"API URL: {BASE_URL}")
    print(f"Output directory: {output_dir}/")
    print("\nData generators being tested:")
    print("  1. API /generate-synthetic endpoint")
    print("  2. DataService.enhanced_generator (EnhancedMetroDataGenerator)")
    print("  3. Local inline generator")
    
    # Check API health
    try:
        health = requests.get(f"{BASE_URL}/health", timeout=5)
        if health.status_code != 200:
            print(f"\n❌ API not healthy: {health.status_code}")
            return
        print("\nβœ“ API is healthy")
    except Exception as e:
        print(f"\n❌ Cannot connect to API: {e}")
        print("Make sure the API is running: python api/greedyoptim_api.py")
        return
    
    results = []
    
    # Test 1: API generator with 25 trainsets
    results.append(("API Generator - 25 trainsets", test_with_api_generator(25, output_dir)))
    
    # Test 2: API generator with 30 trainsets
    results.append(("API Generator - 30 trainsets", test_with_api_generator(30, output_dir)))
    
    # Test 3: DataService generator with 25 trainsets
    results.append(("DataService Generator - 25 trainsets", test_with_dataservice_generator(25, output_dir)))
    
    # Test 4: DataService generator with 30 trainsets
    results.append(("DataService Generator - 30 trainsets", test_with_dataservice_generator(30, output_dir)))
    
    # Test 5: Local generator with 25 trainsets
    results.append(("Local Generator - 25 trainsets", test_with_local_generator(25, output_dir)))
    
    # Test 6: Local generator with 30 trainsets
    results.append(("Local Generator - 30 trainsets", test_with_local_generator(30, output_dir)))
    
    # Summary
    print("\n" + "="*70)
    print("Test Results Summary")
    print("="*70)
    
    for name, success in results:
        status = "βœ“ PASS" if success else "❌ FAIL"
        print(f"  {status}: {name}")
    
    print(f"\nOutput files saved to: {output_dir}/")
    print("="*70)


if __name__ == "__main__":
    main()