#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# log_analyzer.py
# 日志分析工具

import re
import sys
from collections import Counter
from datetime import datetime

def analyze_logs(log_file):
    """分析日志文件"""
    errors = []
    warnings = []
    patterns = {
        'crash': r'FATAL|crash|exception',
        'anr': r'ANR|Application Not Responding',
        'oom': r'OutOfMemory|OOM',
        'nullpointer': r'NullPointerException',
        'illegalstate': r'IllegalStateException',
    }
    
    pattern_matches = {key: [] for key in patterns.keys()}
    
    print(f"Analyzing log file: {log_file}")
    print("=" * 60)
    
    try:
        with open(log_file, 'r', encoding='utf-8', errors='ignore') as f:
            for line_num, line in enumerate(f, 1):
                # 检查错误
                if 'E/' in line or 'ERROR' in line.upper():
                    errors.append((line_num, line.strip()))
                
                # 检查警告
                if 'W/' in line or 'WARN' in line.upper():
                    warnings.append((line_num, line.strip()))
                
                # 检查特定模式
                for pattern_name, pattern in patterns.items():
                    if re.search(pattern, line, re.IGNORECASE):
                        pattern_matches[pattern_name].append((line_num, line.strip()))
        
        # 输出统计信息
        print(f"\nSummary:")
        print(f"  Total lines analyzed: {line_num}")
        print(f"  Errors: {len(errors)}")
        print(f"  Warnings: {len(warnings)}")
        
        for pattern_name, matches in pattern_matches.items():
            if matches:
                print(f"  {pattern_name.upper()}: {len(matches)}")
        
        # 显示错误示例
        if errors:
            print(f"\nFirst 10 errors:")
            for line_num, line in errors[:10]:
                print(f"  Line {line_num}: {line[:100]}")
        
        # 显示模式匹配示例
        for pattern_name, matches in pattern_matches.items():
            if matches:
                print(f"\n{pattern_name.upper()} occurrences (first 5):")
                for line_num, line in matches[:5]:
                    print(f"  Line {line_num}: {line[:100]}")
        
        # 生成报告文件
        report_file = log_file + ".report.txt"
        with open(report_file, 'w', encoding='utf-8') as f:
            f.write(f"Log Analysis Report\n")
            f.write(f"Generated: {datetime.now()}\n")
            f.write(f"Source file: {log_file}\n")
            f.write("=" * 60 + "\n\n")
            f.write(f"Errors: {len(errors)}\n")
            f.write(f"Warnings: {len(warnings)}\n\n")
            
            if errors:
                f.write("Errors:\n")
                for line_num, line in errors:
                    f.write(f"  Line {line_num}: {line}\n")
        
        print(f"\nReport saved to: {report_file}")
        
    except FileNotFoundError:
        print(f"Error: File not found: {log_file}")
        return 1
    except Exception as e:
        print(f"Error: {e}")
        return 1
    
    return 0

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print("Usage: python log_analyzer.py <log_file>")
        sys.exit(1)
    
    log_file = sys.argv[1]
    exit_code = analyze_logs(log_file)
    sys.exit(exit_code)
