package com.game.optimizer;

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

public class GameOptimizationSystem {
    private static final String TAG = "GameOptimizationSystem";
    
    // 核心组件
    private final CoreDevice coreDevice;
    private final ConfigScanner configScanner;
    private final ConfigAutoTuner configAutoTuner;
    
    // 运行时状态
    private final AtomicBoolean isRunning = new AtomicBoolean(false);
    private final ScheduledExecutorService scheduler;
    
    public GameOptimizationSystem() {
        this.coreDevice = new CoreDevice();
        this.configScanner = new ConfigScanner();
        this.configAutoTuner = new ConfigAutoTuner();
        this.scheduler = Executors.newScheduledThreadPool(4);
        
        // 初始化设备信息
        initializeDeviceInfo();
    }
    
    // 自动检测设备信息
    private void initializeDeviceInfo() {
        try {
            // 自动检测基础信息
            coreDevice.autoDetectBasicInfo();
            
            // 设置AutoTuner设备信息
            configAutoTuner.setDeviceSpecs(
                coreDevice.deviceName,
                coreDevice.cpu,
                coreDevice.gpu,
                coreDevice.ramGB,
                coreDevice.androidVer
            );
            
            System.out.println("设备信息初始化完成: " + coreDevice.deviceName);
            
        } catch (Exception e) {
            System.err.println("设备信息初始化失败: " + e.getMessage());
        }
    }
    
    // 手动设置设备信息（用户调用）
    public void setDeviceInfo(String deviceName, String model, String cpu, String gpu, 
                            int ramGB, int storageGB, int androidVer, String screenRes) {
        coreDevice.setDeviceInfo(deviceName, model, cpu, gpu, ramGB, storageGB, androidVer, screenRes);
        
        // 同步更新AutoTuner
        configAutoTuner.setDeviceSpecs(
            deviceName,
            cpu,
            gpu,
            ramGB,
            androidVer
        );
    }
    
    // 设置高级图形信息
    public void setGraphicsInfo(String gpu, String vulkanVersion, int refreshRate, boolean supportVulkan) {
        coreDevice.setGraphicsInfo(gpu, vulkanVersion, refreshRate, supportVulkan);
        
        // 更新AutoTuner的Vulkan支持状态
        if (supportVulkan) {
            configAutoTuner.enableVulkanSupport();
        }
    }
    
    // 启动全自动优化流程
    public void startFullOptimization() {
        if (isRunning.getAndSet(true)) {
            System.out.println("优化系统已在运行中");
            return;
        }
        
        if (!coreDevice.validateDeviceInfo()) {
            System.out.println("请先设置完整的设备信息");
            isRunning.set(false);
            return;
        }
        
        System.out.println("启动全自动游戏优化系统...");
        System.out.println(coreDevice.generateDeviceReport());
        
        // 阶段1：扫描游戏配置
        scheduler.execute(() -> {
            try {
                scanAndOptimizeGames();
            } catch (Exception e) {
                System.err.println("优化流程异常: " + e.getMessage());
            }
        });
        
        // 阶段2：启动持续监控
        startMonitoringService();
    }
    
    // 扫描并优化游戏
    private void scanAndOptimizeGames() {
        try {
            System.out.println("开始扫描游戏配置...");
            
            // 扫描游戏配置
            Map<String, List<File>> gameConfigs = configScanner.scanGameConfigs(coreDevice.androidVer);
            
            if (gameConfigs.isEmpty()) {
                System.out.println("未找到游戏配置文件");
                return;
            }
            
            // 添加并优化游戏
            gameConfigs.forEach((gameName, configFiles) -> {
                if (!configFiles.isEmpty()) {
                    optimizeDiscoveredGame(gameName, configFiles);
                }
            });
            
            // 启动自动优化
            configAutoTuner.startAutoTuning();
            
        } catch (Exception e) {
            System.err.println("游戏扫描优化失败: " + e.getMessage());
        }
    }
    
    // 优化发现的游戏
    private void optimizeDiscoveredGame(String gameName, List<File> configFiles) {
        File mainConfig = selectPrimaryConfig(configFiles);
        String packageName = extractPackageName(mainConfig.getPath());
        
        // 根据设备性能推荐设置
        int recommendedFPS = calculateRecommendedFPS(gameName);
        int recommendedQuality = calculateRecommendedQuality(gameName);
        
        // 添加到AutoTuner
        configAutoTuner.addGameInfo(new ConfigAutoTuner.GameInfo(
            gameName,
            packageName,
            "auto-detected",
            coreDevice.guessGameGenre(gameName),
            mainConfig.getAbsolutePath(),
            recommendedFPS,
            recommendedQuality
        ));
        
        System.out.printf("已添加并优化游戏: %s [FPS:%d 画质:%d]%n", 
            gameName, recommendedFPS, recommendedQuality);
    }
    
    // 选择主配置文件
    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 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 calculateRecommendedFPS(String gameName) {
        // 根据设备性能等级和游戏类型动态计算
        switch (coreDevice.performanceGrade) {
            case FLAGSHIP:
                return gameName.toLowerCase().contains("pubg") ? 90 : 120;
            case HIGH_END:
                return 90;
            case MID_RANGE:
                return 60;
            default:
                return 45;
        }
    }
    
    // 计算推荐画质等级
    private int calculateRecommendedQuality(String gameName) {
        // 1-5级画质，5为最高
        switch (coreDevice.performanceGrade) {
            case FLAGSHIP:
                return 5;
            case HIGH_END:
                return 4;
            case MID_RANGE:
                return 3;
            default:
                return 2;
        }
    }
    
    // 启动监控服务
    private void startMonitoringService() {
        // 每小时重新扫描一次游戏
        scheduler.scheduleAtFixedRate(() -> {
            if (isRunning.get()) {
                rescanAndUpdateGames();
            }
        }, 1, 1, TimeUnit.HOURS);
        
        // 每15分钟检查一次性能
        scheduler.scheduleAtFixedRate(this::checkAndReoptimize, 15, 15, TimeUnit.MINUTES);
        
        // 温度监控（每5分钟）
        scheduler.scheduleAtFixedRate(this::monitorThermal, 5, 5, TimeUnit.MINUTES);
    }
    
    // 重新扫描并更新游戏
    private void rescanAndUpdateGames() {
        try {
            System.out.println("执行定期游戏重新扫描...");
            Map<String, List<File>> newConfigs = configScanner.scanGameConfigs(coreDevice.androidVer);
            
            newConfigs.forEach((gameName, files) -> {
                if (!files.isEmpty()) {
                    File config = selectPrimaryConfig(files);
                    String path = config.getAbsolutePath();
                    
                    // 检查是否是新游戏
                    boolean exists = configAutoTuner.getGameInfos().stream()
                        .anyMatch(g -> g.gameName.equalsIgnoreCase(gameName));
                    
                    if (!exists) {
                        optimizeDiscoveredGame(gameName, files);
                    }
                }
            });
            
        } catch (Exception e) {
            System.err.println("游戏重新扫描失败: " + e.getMessage());
        }
    }
    
    // 检查并重新优化低效游戏
    private void checkAndReoptimize() {
        configAutoTuner.getTuningResults().forEach((gameId, result) -> {
            if (result.effectiveness != null && result.effectiveness.startsWith("低于")) {
                System.out.println("检测到低效游戏配置，重新优化: " + result.gameName);
                
                configAutoTuner.getGameInfos().stream()
                    .filter(g -> g.gameId.equals(gameId))
                    .findFirst()
                    .ifPresent(game -> {
                        scheduler.schedule(() -> configAutoTuner.tuneGameConfig(game), 1, TimeUnit.MINUTES);
                    });
            }
        });
    }
    
    // 温度监控
    private void monitorThermal() {
        // 模拟温度检测
        double temp = simulateTemperatureCheck();
        
        if (temp > 45.0) {
            System.out.printf("设备温度偏高: %.1f°C，降低画质设置%n", temp);
            adjustSettingsForThermal();
        }
    }
    
    // 模拟温度检测
    private double simulateTemperatureCheck() {
        // 实际项目中应读取真实温度数据
        Random random = new Random();
        return 35.0 + random.nextDouble() * 15.0; // 35-50°C之间
    }
    
    // 温度过高时调整设置
    private void adjustSettingsForThermal() {
        configAutoTuner.getGameInfos().forEach(game -> {
            // 降低一档画质
            int newQuality = Math.max(1, game.recommendedQuality - 1);
            game.recommendedQuality = newQuality;
            
            // 重新优化
            scheduler.execute(() -> configAutoTuner.tuneGameConfig(game));
        });
    }
    
    // 停止优化系统
    public void shutdown() {
        if (isRunning.getAndSet(false)) {
            configAutoTuner.stopTuning();
            scheduler.shutdownNow();
            System.out.println("游戏优化系统已关闭");
        }
    }
    
    // 获取系统状态报告
    public String getSystemStatus() {
        StringBuilder report = new StringBuilder();
        report.append("=== 游戏优化系统状态 ===\n");
        report.append("运行状态: ").append(isRunning.get() ? "运行中" : "已停止").append("\n");
        report.append("已优化游戏: ").append(configAutoTuner.getGameInfos().size()).append("\n");
        
        // 设备信息摘要
        report.append("\n[设备信息]\n")
              .append(coreDevice.deviceName).append(" (")
              .append(coreDevice.performanceGrade).append(")\n")
              .append("Android ").append(coreDevice.androidVer).append(" ")
              .append(coreDevice.androidCodeName).append("\n")
              .append(coreDevice.cpu).append(" + ").append(coreDevice.gpu).append("\n")
              .append(coreDevice.ramGB).append("GB RAM, ")
              .append(coreDevice.screenRes).append(" @").append(coreDevice.refreshRate).append("Hz\n");
        
        // 游戏优化状态
        report.append("\n[游戏优化状态]\n");
        configAutoTuner.getTuningResults().forEach((id, result) -> {
            report.append(String.format("%-20s: %-10s 效果: %s%n",
                result.gameName,
                result.tuneTime != null ? "已优化" : "待优化",
                result.effectiveness));
        });
        
        return report.toString();
    }
    
    // 获取优化建议
    public List<String> getOptimizationSuggestions() {
        List<String> suggestions = new ArrayList<>();
        
        // 设备级别建议
        suggestions.addAll(coreDevice.getOptimizationSuggestions());
        
        // 游戏特定建议
        configAutoTuner.getGameInfos().forEach(game -> {
            suggestions.add(game.gameName + ": 建议" + game.recommendedFPS + "FPS + 画质等级" + game.recommendedQuality);
        });
        
        return suggestions;
    }
    
    // 主入口（测试用）
    public static void main(String[] args) {
        GameOptimizationSystem system = new GameOptimizationSystem();
        
        // 设置设备信息（示例）
        system.setDeviceInfo(
            "Xiaomi 14 Pro",
            "23127PN0CC",
            "Snapdragon 8 Gen 3",
            "Adreno 750",
            12,
            256,
            15,
            "3200x1440"
        );
        
        // 设置图形信息
        system.setGraphicsInfo(
            "Adreno 750",
            "1.3",
            120,
            true
        );
        
        // 启动全自动优化
        system.startFullOptimization();
        
        // 30秒后打印状态（模拟）
        try {
            TimeUnit.SECONDS.sleep(30);
            System.out.println(system.getSystemStatus());
            
            // 保持运行1小时（实际应用可永久运行）
            TimeUnit.HOURS.sleep(1);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            system.shutdown();
        }
    }
}
