#!/usr/bin/env python3
import json
from collections import Counter, defaultdict
import sys

tool_counts = Counter()
event_counts = Counter()
error_records = []
workflow_sequences = []
user_correction_markers = []
tool_error_map = defaultdict(int)

try:
    with open('/tmp/ecc-observer-analysis.KWPPw1.jsonl', 'r') as f:
        line_num = 0
        for line in f:
            line_num += 1
            try:
                record = json.loads(line)
                tool = record.get('tool')
                event = record.get('event')
                timestamp = record.get('timestamp')

                if tool:
                    tool_counts[tool] += 1

                if event:
                    event_counts[event] += 1

                # Track error patterns
                if event == 'tool_complete':
                    output = record.get('output', '')
                    if isinstance(output, str):
                        if 'error' in output.lower() or 'failed' in output.lower():
                            error_records.append({
                                'timestamp': timestamp,
                                'tool': tool,
                                'output': output[:300]
                            })
                            tool_error_map[tool] += 1

                # Track user input that looks like corrections
                if event == 'tool_start' and tool == 'AskUserQuestion':
                    user_correction_markers.append(timestamp)

            except json.JSONDecodeError as e:
                print(f"JSON error at line {line_num}: {e}", file=sys.stderr)
                continue

    print("=== TOOL USAGE (Top 20) ===")
    for tool, count in tool_counts.most_common(20):
        print(f"{tool:30} {count:4d}")

    print("\n=== EVENT TYPES ===")
    for event, count in sorted(event_counts.items(), key=lambda x: x[1], reverse=True):
        print(f"{event:20} {count:4d}")

    print("\n=== TOOLS WITH ERRORS ===")
    for tool, count in sorted(tool_error_map.items(), key=lambda x: x[1], reverse=True):
        if count > 0:
            print(f"{tool:30} {count:3d} errors")

    print(f"\n=== ERROR SAMPLES ===")
    for i, err in enumerate(error_records[:5]):
        print(f"\n[{i+1}] {err['tool']} @ {err['timestamp']}")
        print(f"    {err['output'][:150]}...")

    print(f"\n=== TOTALS ===")
    print(f"Total events: {sum(event_counts.values())}")
    print(f"Total lines: {line_num}")
    print(f"Total error records: {len(error_records)}")
    print(f"User question events: {len(user_correction_markers)}")

except Exception as e:
    print(f"File error: {e}", file=sys.stderr)
