import java.awt.GraphicsEnvironment;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.security.MessageDigest;
import java.util.*;
import javax.swing.*;

/** Local, narrowly scoped repair for pre-existing AEDF3 profiles. Java 8+. */
public final class RepararMultipart {
    static final String PREFIXED="mods/Lib-Forgemultipart-1.7.10-1.2.0.345-universal.jar";
    static final String CANON="mods/1.7.10/ForgeMultipart-1.7.10-1.2.0.345-universal.jar";
    static final String BROKEN="mods/1.7.10/ForgeMultipart-1.7.10-1.1.2.331-universal.jar";
    static final String GOOD="6ff759efc10f9ea0deabb4aed7c1f61408d9bb9bce278949544c0a613f7ae4c8";
    static final byte[] STUB="Moved Permanently".getBytes(StandardCharsets.US_ASCII);
    static final String STATE=".infinitycraft-recuperacao/multipart-345";
    static final LinkOption[] NO_LINKS={LinkOption.NOFOLLOW_LINKS};
    static Path checked(Path root,String relative)throws IOException {
        Path out=root;
        for(Path part:Paths.get(relative)){
            out=out.resolve(part);
            if(Files.isSymbolicLink(out)||Files.exists(out,NO_LINKS)&&!out.toRealPath().equals(out.toAbsolutePath().normalize()))throw new IOException("O perfil usa um link no caminho da correção.");
        }
        return out;
    }
    static String digest(Path path)throws Exception {
        if(!Files.exists(path,NO_LINKS))return "";
        if(!Files.isRegularFile(path,NO_LINKS)||Files.size(path)>1000000)return "desconhecido";
        byte[] hash=MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(path));
        StringBuilder result=new StringBuilder();
        for(byte item:hash)result.append(String.format("%02x",item&255));
        return result.toString();
    }
    static void require(boolean condition,String msg)throws IOException {if(!condition)throw new IOException(msg);}
    static void verifyProfile(Path root)throws Exception{
        Path mods=checked(root,"mods");
        require(Files.isDirectory(mods,NO_LINKS),"Escolha a pasta do AEDF3 que contém a pasta mods.");
        // Distinctive files of the distributed AEDF3. Neither personal mods nor similar pack names qualify.
        require(Files.isRegularFile(checked(root,"mods/Mekanism-1.7.10-9.1.1.1031.jar"),NO_LINKS)&&
                Files.isRegularFile(checked(root,"mods/InfinityCraft-Network-Integration-0.3.0-rc1.jar"),NO_LINKS),
                "Esta pasta não corresponde ao AEDF3 da InfinityCraft.");
        require(!Files.exists(checked(root,".infinity-instance.lock"),NO_LINKS),"Feche o jogo e aguarde o launcher encerrar a instância.");
    }
    static void copyChecked(Path source,Path target,String hash)throws Exception {
        if(Files.exists(target,NO_LINKS)){require(hash.equals(digest(target)),"Há um arquivo diferente no destino. A cópia existente foi preservada.");return;}
        Path temp=Files.createTempFile(target.getParent(),".multipart-",".part");
        try {
            Files.copy(source,temp,StandardCopyOption.REPLACE_EXISTING);
            require(hash.equals(digest(temp)),"A leitura mudou durante a cópia.");
            try{Files.createLink(target,temp);}catch(UnsupportedOperationException|FileSystemException e){
                if(!Files.exists(target,NO_LINKS))Files.move(temp,target);
            }
            require(hash.equals(digest(target)),"A cópia não coincide com o arquivo original.");
        }finally{Files.deleteIfExists(temp);}
    }
    static String apply(Path input)throws Exception{
        Path root=input.toRealPath();
        verifyProfile(root);
        Path old=checked(root,PREFIXED),canonical=checked(root,CANON),stub=checked(root,BROKEN);
        String oldHash=digest(old),newHash=digest(canonical),badHash=digest(stub);
        require(oldHash.isEmpty()||oldHash.equals(GOOD),"O arquivo com nome antigo foi modificado. Ele foi preservado.");
        require(newHash.isEmpty()||newHash.equals(GOOD),"A versão de destino foi modificada. Ela foi preservada.");
        require(oldHash.equals(GOOD)||newHash.equals(GOOD),"A biblioteca original não foi encontrada.");
        boolean knownStub=!badHash.isEmpty()&&Files.isRegularFile(stub,NO_LINKS)&&Files.size(stub)==STUB.length&&Arrays.equals(Files.readAllBytes(stub),STUB);
        require(badHash.isEmpty()||knownStub,"Há um arquivo diferente na posição da versão 331. Ele foi preservado.");
        if(oldHash.isEmpty()&&newHash.equals(GOOD)&&!knownStub)return "A biblioteca já está na posição correta.";
        Path dir=checked(root,STATE);
        Files.createDirectories(dir);
        Path recOld=checked(root,STATE+"/345-original.jar.copia"),recStub=checked(root,STATE+"/331-original.copia");
        Path lock=checked(root,STATE+"/reparo.lock");
        try(FileChannel channel=FileChannel.open(lock,StandardOpenOption.CREATE,StandardOpenOption.WRITE);FileLock held=channel.tryLock()){
            require(held!=null,"Outro reparo já está em andamento.");
            if(!oldHash.isEmpty())copyChecked(old,recOld,GOOD);
            if(knownStub)copyChecked(stub,recStub,badHash);
            Files.createDirectories(canonical.getParent());
            if(newHash.isEmpty())copyChecked(old,canonical,GOOD);
            if(!oldHash.isEmpty()){require(GOOD.equals(digest(old))&&GOOD.equals(digest(canonical))&&GOOD.equals(digest(recOld)),"O arquivo original mudou durante o reparo.");Files.delete(old);}
            if(knownStub){require(badHash.equals(digest(stub))&&badHash.equals(digest(recStub)),"O resíduo mudou durante o reparo.");Files.delete(stub);}
        }
        return "Reparo concluído. A cópia anterior está em "+STATE+".";
    }
    public static void main(String[] args)throws Exception{
        if(args.length==1){System.out.println(apply(Paths.get(args[0])));return;}
        require(args.length==0&&!GraphicsEnvironment.isHeadless(),"Escolha a pasta do perfil AEDF3.");
        SwingUtilities.invokeLater(()->{
            JFileChooser chooser=new JFileChooser();chooser.setDialogTitle("Escolher o perfil AEDF3");chooser.setAcceptAllFileFilterUsed(false);chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            if(chooser.showDialog(null,"Reparar perfil")!=JFileChooser.APPROVE_OPTION)return;
            try{JOptionPane.showMessageDialog(null,apply(chooser.getSelectedFile().toPath()),"InfinityCraft · AEDF3",JOptionPane.INFORMATION_MESSAGE);}
            catch(Exception e){JOptionPane.showMessageDialog(null,e.getMessage(),"InfinityCraft · AEDF3",JOptionPane.ERROR_MESSAGE);}
        });
    }
}
