package puzzle;

import com.google.gson.Gson;
import lombok.val;
import puzzle.SwedishGenerator.Lemma;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.stream.IntStream;
public class Meta {
   
   static final         Gson GSON    = new Gson();
   private static final int  VERSION = 1;
   
   static record ShardLem(long w, int simpel, String[] clues) { }
   
   static final int SHARD_MAGIC = 0x49445831; // "IDX1"
   static ShardLem readRecord(Path shardFile, int i) {
      try (FileChannel ch = FileChannel.open(shardFile, StandardOpenOption.READ)) {
         ByteBuffer hdr = ByteBuffer.allocate(12);
         ch.read(hdr);
         hdr.flip();
         int magic = hdr.getInt();
         int ver   = hdr.getInt();
         int n     = hdr.getInt();
         if (magic != SHARD_MAGIC || ver != VERSION) throw new IOException("Bad shard");
         if (i < 0 || i >= n) throw new IndexOutOfBoundsException();
         
         long tableStart = 12L;
         long dataStart  = 12L + (long) n * 4L;
         
         int offI = readIntAt(ch, tableStart + (long) i * 4L);
         int offIp = (i + 1 < n) ? readIntAt(ch, tableStart + (long) (i + 1) * 4L)
                                 : (int) (ch.size() - dataStart);
         
         int        len = offIp - offI;
         ByteBuffer buf = ByteBuffer.allocate(len);
         ch.position(dataStart + offI);
         ch.read(buf);
         buf.flip();
         var string = StandardCharsets.UTF_8.decode(buf).toString();
         val parts  = string.split("\t", 3);
         return new ShardLem(Lemma.from(parts[0]), Integer.parseInt(parts[1]), GSON.fromJson(parts[2], String[].class));
      } catch (Exception e) {
         e.printStackTrace();
         return new ShardLem(Lemma.from("XXX"), -1, new String[0]);
      }
   }
   static final Path[] SHARDS = IntStream.range(0, 10).mapToObj(sId -> Path.of("src/main/generated-sources/puzzle").resolve(sId + ".idx")).toArray(
           Path[]::new);
   static Path shardKey(long word) {
      return SHARDS[Lemma.unpackSize(word) + 1];
   }
   static int readIntAt(FileChannel ch, long pos) throws IOException {
      ByteBuffer b = ByteBuffer.allocate(4);
      ch.position(pos);
      ch.read(b);
      b.flip();
      return b.getInt();
   }
}
