import argparse
import json
import sys
import statistics
from collections import defaultdict

def calculate_percentile(data, percentile):
    if not data:
        return 0
    data.sort()
    k = (len(data) - 1) * percentile / 100
    f = int(k)
    c = int(k) + 1
    if c >= len(data):
        return data[-1]
    d0 = data[f] * (c - k)
    d1 = data[c] * (k - f)
    return d0 + d1

def report_command(args):
    file_path = args.file
    try:
        with open(file_path, 'r') as f:
            lines = f.readlines()
    except FileNotFoundError:
        print(f"Error: File not found: {file_path}")
        sys.exit(1)

    stats = defaultdict(lambda: {'latencies': [], 'errors': 0, 'total': 0})

    for line in lines:
        try:
            data = json.loads(line)
            uid = data.get('universe_id', 'unknown')
            latency = data.get('latency_ms', 0)
            status = data.get('status_code', 200)

            stats[uid]['total'] += 1
            stats[uid]['latencies'].append(latency)
            if status >= 500:
                stats[uid]['errors'] += 1
        except json.JSONDecodeError:
            continue

    print(f"{'Universe ID':<20} | {'Requests':<10} | {'P50 (ms)':<10} | {'P95 (ms)':<10} | {'Error Rate':<10}")
    print("-" * 75)

    for uid, data in stats.items():
        total = data['total']
        latencies = data['latencies']
        errors = data['errors']
        
        p50 = calculate_percentile(latencies, 50)
        p95 = calculate_percentile(latencies, 95)
        error_rate = (errors / total) * 100 if total > 0 else 0

        print(f"{uid:<20} | {total:<10} | {p50:<10.1f} | {p95:<10.1f} | {error_rate:<9.1f}%")

def main():
    parser = argparse.ArgumentParser(description="UniverseOS CLI")
    subparsers = parser.add_subparsers(dest='command', required=True)

    report_parser = subparsers.add_parser('report', help='Generate metrics report')
    report_parser.add_argument('--file', default='metrics.jsonl', help='Path to metrics file')
    report_parser.set_defaults(func=report_command)

    args = parser.parse_args()
    args.func(args)

if __name__ == "__main__":
    main()
