package engine;

import core.CoreDevice;
import registry.GameRegistry.Game;
import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;

public class OptimizerEngine {
    private final CoreDevice dev;
    private final ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);
    private final Map<String, Double> scoreMap = new ConcurrentHashMap<>();

    public OptimizerEngine(CoreDevice d){ this.dev = d; }

    public void start(List<Game> list){
        list.forEach(g -> pool.scheduleWithFixedDelay(() -> optimizeGame(g),0,120,TimeUnit.SECONDS));
    }

    private void optimizeGame(Game g){
        try{
            optimizeDir(g.iniPath,".ini",g);
            optimizeDir(g.jsonPath,".json",g);
            autoRetune(g);
        }catch(Exception e){ e.printStackTrace(); }
    }

    private void optimizeDir(String dir,String ext,Game g) throws Exception{
        List<File> files = scanner.ConfigScanner.scan(dir,ext);
        for(File f:files){
            Map<String,String> kv = load(f);
            kv = tune(kv,g);
            save(f,ext,kv);
        }
    }

    private Map<String,String> load(File f) throws IOException{
        Map<String,String> m = new LinkedHashMap<>();
        List<String> lines = Files.readAllLines(f.toPath());
        for(String l:lines){
            l=l.trim();
            if(l.startsWith("#")||l.startsWith("//")||l.isEmpty()) continue;
            if(l.contains("=")){
                String[] sp=l.split("=",2);
                m.put(sp[0].trim(),sp[1].trim());
            }
        }
        return m;
    }

    private Map<String,String> tune(Map<String,String> m,Game g){
        m.put("target_fps",String.valueOf(g.targetFps));
        m.put("graphics_level",String.valueOf(Math.max(1,g.gfxLevel-(dev.ramGB<6?1:0))));
        m.put("android15_boost","true");
        m.put("gpu_driver_optimize","true");
        m.put("device_name",dev.deviceName);
        m.put("optimized_at",String.valueOf(System.currentTimeMillis()));
        return m;
    }

    private void save(File f,String ext,Map<String,String> kv) throws IOException{
        File out = new File(f.getParent(),f.getName().replace(ext,"_opt"+ext));
        try(PrintWriter pw=new PrintWriter(out)){
            kv.forEach((k,v)->pw.println(k+"="+v));
        }
    }

    private void autoRetune(Game g){
        double sc = scoreMap.getOrDefault(g.id,10.0);
        if(sc<6){
            System.out.println("效果差，重优："+g.name);
            scoreMap.put(g.id,10.0); // reset
        }
    }

    public void reportEffect(String gameId,double sc){ scoreMap.put(gameId,sc); }

    public void stop(){ pool.shutdownNow(); }
}