package com.game.autotune;

import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.*;

public class GameOptimizer {
    private static final String TAG = "GameOptimizer";
    
    // 主组件
    private final ConfigAutoTuner autoTuner;
    private final ConfigScanner configScanner;
    
    // 运行状态
    private final AtomicBoolean isScanning = new AtomicBoolean(false);
    private final ScheduledExecutorService scheduler;
    
    public GameOptimizer() {
        this.autoTuner = new ConfigAutoTuner();
        this.configScanner = new ConfigScanner();
        this.scheduler = Executors.newScheduledThreadPool(4);
    }
    
    // 全自动模式：扫描->识别->优化
    public void startFullAutoMode(int androidVersion) {
        if (isScanning.getAndSet(true)) {
            System.out.println("已在扫描优化中");
            return;
        }
        
        scheduler.execute(() -> {
            try {
                System.out.println("开始全自动扫描优化...");
                
                // 阶段1：扫描游戏配置
                Map<String, List<File>> gameConfigs = configScanner.scanGameConfigs(androidVersion);
                
                // 阶段2：自动识别并添加游戏
                gameConfigs.forEach((gameName, configFiles) -> {
                    if (!configFiles.isEmpty()) {
                        File mainConfig = selectPrimaryConfig(configFiles);
                        addDiscoveredGame(gameName, mainConfig);
                    }
                });
                
                // 阶段3：启动优化引擎
                autoTuner.startAutoTuning();
                
                // 阶段4：启动持续监控
                startContinuousMonitoring();
                
            } catch (Exception e) {
                System.err.println("全自动模式失败: " + e.getMessage());
            } finally {
                isScanning.set(false);
            }
        });
    }
    
    // 智能选择主配置文件
    private File selectPrimaryConfig(List<File> configFiles) {
        // 优先级：GameUserSettings.ini > 其他.ini > 其他格式
        Optional<File> primary = configFiles.stream()
            .filter(f -> f.getName().equalsIgnoreCase("GameUserSettings.ini"))
            .findFirst();
        
        if (primary.isPresent()) return primary.get();
        
        return configFiles.stream()
            .filter(f -> f.getName().toLowerCase().endsWith(".ini"))
            .findFirst()
            .orElse(configFiles.get(0));
    }
    
    // 添加发现的游戏到优化器
    private void addDiscoveredGame(String gameName, File configFile) {
        try {
            String packageName = extractPackageName(configFile.getPath());
            int recommendedFps = detectRecommendedFPS(gameName);
            int recommendedQuality = detectRecommendedQuality(gameName);
            
            autoTuner.addGameInfo(new ConfigAutoTuner.GameInfo(
                gameName,
                packageName,
                "auto-detected",
                guessGameGenre(gameName),
                configFile.getAbsolutePath(),
                recommendedFps,
                recommendedQuality
            ));
            
            System.out.printf("已添加游戏: %s [FPS:%d 画质:%d]%n", 
                gameName, recommendedFps, recommendedQuality);
            
        } catch (Exception e) {
            System.err.println("添加游戏失败: " + gameName + " - " + e.getMessage());
        }
    }
    
    // 从路径提取包名
    private String extractPackageName(String path) {
        String[] parts = path.split("/");
        for (String part : parts) {
            if (part.contains(".") && part.length() > 3) {
                return part;
            }
        }
        return "unknown." + gameName.replaceAll("\\s+", "").toLowerCase();
    }
    
    // 根据游戏名称智能推荐FPS
    private int detectRecommendedFPS(String gameName) {
        if (gameName.toLowerCase().contains("pubg") || 
            gameName.toLowerCase().contains("peacekeeper")) {
            return 90; // 和平精英推荐90帧
        }
        
        if (gameName.toLowerCase().contains("cod") || 
            gameName.toLowerCase().contains("callofduty")) {
            return 120; // COD手游支持高帧率
        }
        
        return 60; // 默认60帧
    }
    
    // 根据游戏名称智能推荐画质等级
    private int detectRecommendedQuality(String gameName) {
        // 根据设备内存动态调整
        int ramGB = autoTuner.getDeviceSpecs().ramGB;
        
        if (gameName.toLowerCase().contains("genshin")) {
            return ramGB >= 12 ? 4 : 3; // 原神吃配置
        }
        
        if (gameName.toLowerCase().contains("pubg")) {
            return ramGB >= 8 ? 4 : 3; // 吃鸡游戏中高画质
        }
        
        return ramGB >= 8 ? 3 : 2; // 默认中等画质
    }
    
    // 猜测游戏类型
    private String guessGameGenre(String gameName) {
        String lowerName = gameName.toLowerCase();
        
        if (lowerName.contains("pubg") || lowerName.contains("battle") || lowerName.contains("royale")) {
            return "BattleRoyale";
        }
        if (lowerName.contains("cod") || lowerName.contains("duty") || lowerName.contains("shooter")) {
            return "FPS";
        }
        if (lowerName.contains("genshin") || lowerName.contains("honkai") || lowerName.contains("impact")) {
            return "OpenWorld";
        }
        if (lowerName.contains("mobile") || lowerName.contains("legends") || lowerName.contains("arena")) {
            return "MOBA";
        }
        
        return "Unknown";
    }
    
    // 启动持续监控
    private void startContinuousMonitoring() {
        // 每小时重新扫描一次
        scheduler.scheduleAtFixedRate(() -> {
            if (!isScanning.get()) {
                rescanAndUpdateGames();
            }
        }, 1, 1, TimeUnit.HOURS);
        
        // 每15分钟检查一次性能
        scheduler.scheduleAtFixedRate(this::checkAndReoptimize, 15, 15, TimeUnit.MINUTES);
    }
    
    // 重新扫描并更新游戏列表
    private void rescanAndUpdateGames() {
        try {
            System.out.println("执行定期重新扫描...");
            Map<String, List<File>> newConfigs = configScanner.scanGameConfigs(
                autoTuner.getDeviceSpecs().androidVersion);
            
            newConfigs.forEach((gameName, files) -> {
                if (!files.isEmpty()) {
                    File config = selectPrimaryConfig(files);
                    String path = config.getAbsolutePath();
                    
                    // 检查是否是新游戏或配置路径变更
                    boolean exists = autoTuner.getGameInfos().stream()
                        .anyMatch(g -> g.gameName.equalsIgnoreCase(gameName));
                    
                    if (!exists) {
                        addDiscoveredGame(gameName, config);
                    }
                }
            });
            
        } catch (Exception e) {
            System.err.println("重新扫描失败: " + e.getMessage());
        }
    }
    
    // 检查并重新优化低效游戏
    private void checkAndReoptimize() {
        autoTuner.getTuningResults().forEach((gameId, result) -> {
            if (result.effectiveness != null && 
                result.effectiveness.startsWith("低于")) {
                System.out.println("检测到低效游戏配置，重新优化: " + result.gameName);
                
                autoTuner.getGameInfos().stream()
                    .filter(g -> g.gameId.equals(gameId))
                    .findFirst()
                    .ifPresent(game -> {
                        scheduler.schedule(() -> autoTuner.tuneGameConfig(game), 1, TimeUnit.MINUTES);
                    });
            }
        });
    }
    
    // 停止所有服务
    public void shutdown() {
        autoTuner.stopTuning();
        scheduler.shutdownNow();
        System.out.println("游戏优化器已关闭");
    }
    
    // 获取当前状态报告
    public String getStatusReport() {
        StringBuilder report = new StringBuilder();
        report.append("=== 游戏优化器状态 ===\n");
        report.append("运行模式: ").append(isScanning.get() ? "全自动" : "待机").append("\n");
        report.append("已管理游戏: ").append(autoTuner.getGameInfos().size()).append("\n");
        
        autoTuner.getTuningResults().forEach((id, result) -> {
            report.append(String.format(
                "游戏: %-20s 状态: %-10s 效果: %s%n",
                result.gameName, 
                result.tuneTime != null ? "已优化" : "待优化",
                result.effectiveness
            ));
        });
        
        return report.toString();
    }
    
    // 获取设备信息
    public String getDeviceInfo() {
        ConfigAutoTuner.DeviceSpecs specs = autoTuner.getDeviceSpecs();
        return String.format(
            "设备: %s\nCPU: %s\nGPU: %s\n内存: %dGB\n安卓版本: %d",
            specs.model, specs.cpu, specs.gpu, specs.ramGB, specs.androidVersion
        );
    }
    
    // 主入口（测试用）
    public static void main(String[] args) {
        GameOptimizer optimizer = new GameOptimizer();
        
        // 设置设备信息（示例）
        optimizer.autoTuner.setDeviceSpecs(
            "Xiaomi 14 Pro", 
            "Snapdragon 8 Gen 3", 
            "Adreno 750", 
            12, 
            15
        );
        
        // 启动全自动模式
        optimizer.startFullAutoMode(15);
        
        // 30秒后打印状态（模拟）
        try {
            TimeUnit.SECONDS.sleep(30);
            System.out.println(optimizer.getStatusReport());
            
            // 保持运行1小时（实际应用可永久运行）
            TimeUnit.HOURS.sleep(1);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            optimizer.shutdown();
        }
    }
}
