from flask import Flask, jsonify, request, session
from flask_cors import CORS
import os
import re
from datetime import datetime
import pandas as pd
import logging
from logging.handlers import RotatingFileHandler

app = Flask(__name__)
CORS(app, supports_credentials=True)
app.secret_key = 'super_secret_key_1234567890'  # Заміни на свій ключ

ADMINS = {
    "admin1": "QwErTy2024!@#",
    "admin2": "ZxCvBn$5678^&*",
    "admin3": "AsDfGh_!2345",
    "admin4": "PoIuYt*()_+",
    "admin5": "LkJhGf#0987",
    "admin6": "MnBvCx!@2024",
    "admin7": "TrEwQz$%123",
    "admin8": "PlOkMiN&*456"
}

@app.route('/api/login', methods=['POST'])
def login():
    data = request.json
    username = data.get('username')
    password = data.get('password')
    if username in ADMINS and ADMINS[username] == password:
        session['admin'] = username
        return jsonify({"success": True})
    return jsonify({"success": False}), 401

@app.route('/api/check_auth', methods=['GET'])
def check_auth():
    return jsonify({"auth": 'admin' in session})

@app.route('/api/logout', methods=['POST'])
def logout():
    session.pop('admin', None)
    return jsonify({"success": True})

def parse_log_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # Парсинг базової інформації
    player_info = {
        'nickname': re.search(r'Никнеймы игрока: (.*?)\n|Player Nicknames: (.*?)\n', content).group(1) or re.search(r'Никнеймы игрока: (.*?)\n|Player Nicknames: (.*?)\n', content).group(2),
        'ip': re.search(r'IP-адрес игрока: (.*?) \(|IP Address: (.*?) \(', content).group(1) or re.search(r'IP-адрес игрока: (.*?) \(|IP Address: (.*?) \(', content).group(2),
        'country': re.search(r'Country: ([^,\)\n]+)', content).group(1),
        'scan_date': re.search(r'Отчет PlayBF2 AntiCheat \((.*?)\)|PlayBF2 AntiCheat Report \((.*?)\)', content).group(1) or re.search(r'Отчет PlayBF2 AntiCheat \((.*?)\)|PlayBF2 AntiCheat Report \((.*?)\)', content).group(2),
        'cheats_detected': 'Нет',
        'cheats_details': [],
        'suspicious_processes': 'Нет' if 'Подозрительные процессы:\nНет' in content or 'Suspicious Processes:\nNone' in content else 'Да',
        'alpha_tools': 'Не найден' if 'AlphaTools: Не найден' in content or 'AlphaTools: Not found' in content else 'Найден'
    }
    
    # Парсинг детальних читів
    cheats_block = re.search(r'(Обнаруженные читы:|Detected Cheats:)([\s\S]+?)(\n\w|\n\-|\nSuspicious Processes:|\nПодозрительные процессы:)', content)
    if cheats_block:
        cheats_text = cheats_block.group(2)
        if not ('Нет' in cheats_text or 'None' in cheats_text):
            player_info['cheats_detected'] = 'Да'
            cheats = re.findall(r'- ([^\n]+) \(Location: ([^\)]+)\)([\s\S]+?)(?=\n- |\n\w|\n\-|\nSuspicious Processes:|\nПодозрительные процессы:|$)', cheats_text)
            for cheat in cheats:
                name = cheat[0].strip()
                location = cheat[1].strip()
                details = cheat[2].strip()
                size = re.search(r'Size: ([^\n]+)', details)
                created = re.search(r'Created: ([^\n]+)', details)
                modified = re.search(r'Modified: ([^\n]+)', details)
                accessed = re.search(r'Last Accessed: ([^\n]+)', details)
                player_info['cheats_details'].append({
                    'name': name,
                    'location': location,
                    'size': size.group(1) if size else '',
                    'created': created.group(1) if created else '',
                    'modified': modified.group(1) if modified else '',
                    'accessed': accessed.group(1) if accessed else ''
                })
    
    return player_info

@app.route('/api/logs', methods=['GET'])
def get_logs():
    logs_dir = './logs'
    log_files = [f for f in os.listdir(logs_dir) if f.endswith('.txt')]
    
    all_logs = []
    countries = set()
    for log_file in log_files:
        try:
            log_info = parse_log_file(os.path.join(logs_dir, log_file))
            log_info['filename'] = log_file
            all_logs.append(log_info)
            countries.add(log_info['country'])
        except Exception as e:
            print(f"Error parsing {log_file}: {str(e)}")
    
    return jsonify({'logs': all_logs, 'countries': sorted(list(countries))})

@app.route('/api/search', methods=['GET'])
def search_logs():
    query = request.args.get('query', '').lower()
    country_filter = request.args.get('country', '').lower()
    logs_dir = './logs'
    log_files = [f for f in os.listdir(logs_dir) if f.endswith('.txt')]
    
    results = []
    for log_file in log_files:
        try:
            with open(os.path.join(logs_dir, log_file), 'r', encoding='utf-8') as f:
                content = f.read().lower()
                if (query in content) and (not country_filter or f'country: {country_filter}' in content):
                    log_info = parse_log_file(os.path.join(logs_dir, log_file))
                    log_info['filename'] = log_file
                    results.append(log_info)
        except Exception as e:
            print(f"Error searching in {log_file}: {str(e)}")
    
    return jsonify(results)

@app.route('/api/logfile', methods=['GET'])
def get_logfile():
    filename = request.args.get('filename')
    logs_dir = './logs'
    if not filename or not filename.endswith('.txt'):
        return jsonify({'error': 'Invalid filename'}), 400
    file_path = os.path.join(logs_dir, filename)
    if not os.path.exists(file_path):
        return jsonify({'error': 'File not found'}), 404
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    return jsonify({'content': content})

@app.route('/api/stats', methods=['GET'])
def get_stats():
    logs_dir = './logs'
    log_files = [f for f in os.listdir(logs_dir) if f.endswith('.txt')]
    
    all_logs = []
    for log_file in log_files:
        try:
            log_info = parse_log_file(os.path.join(logs_dir, log_file))
            all_logs.append(log_info)
        except Exception as e:
            print(f"Error parsing {log_file}: {str(e)}")
    
    df = pd.DataFrame(all_logs)
    
    stats = {
        'total_scans': len(all_logs),
        'cheats_detected': len(df[df['cheats_detected'] == 'Да']),
        'suspicious_processes': len(df[df['suspicious_processes'] == 'Да']),
        'alpha_tools_detected': len(df[df['alpha_tools'] == 'Найден']),
        'countries': df['country'].value_counts().to_dict()
    }
    
    return jsonify(stats)

if __name__ == '__main__':
       app.run(debug=True, host='0.0.0.0', port=5000)