import com.fasterxml.jackson.databind.node.ObjectNode;
import io.delta.standalone.DeltaLog;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Stream;
import org.apache.hadoop.conf.Configuration;
import org.apache.iceberg.HistoryEntry;
import org.apache.iceberg.Snapshot;
import org.apache.iceberg.SnapshotRef;
import org.apache.iceberg.Table;
import org.apache.iceberg.catalog.Namespace;
import org.apache.iceberg.catalog.TableIdentifier;
import org.apache.iceberg.delta.DeltaLakeToIcebergMigrationActionsProvider;
import org.apache.iceberg.delta.SnapshotDeltaLakeTable;
import org.apache.iceberg.hadoop.HadoopCatalog;
import org.apache.iceberg.util.JsonUtil;
import org.apache.iceberg.util.SnapshotUtil;

class ClockReplay {
  private static final long FIRST_TIME = 1_577_836_800_000L;
  private static final long SECOND_FILE_TIME = FIRST_TIME + 2_000;
  private static final Namespace NS = Namespace.of("fixture");
  private static final String SCHEMA =
      "{\"type\":\"struct\",\"fields\":["
          + "{\"name\":\"id\",\"type\":\"long\",\"nullable\":true,\"metadata\":{}}]}";

  public static void main(String[] args) throws IOException {
    require(args.length == 1, "Supply one empty temporary directory");
    Path scratch = Path.of(args[0]).toRealPath();
    try (Stream<Path> files = Files.list(scratch)) {
      require(files.findAny().isEmpty(), "The temporary directory must be empty");
    }
    Configuration conf = new Configuration(false);
    conf.set("fs.defaultFS", "file:///");
    conf.set("fs.file.impl", "org.apache.hadoop.fs.RawLocalFileSystem");

    Path warehouse = Files.createDirectory(scratch.resolve("warehouse"));
    try (HadoopCatalog catalog = new HadoopCatalog(conf, warehouse.toUri().toString())) {
      catalog.createNamespace(NS, Map.of());
      TableIdentifier distinct = TableIdentifier.of(NS, "distinct_times");
      Path first = writeSource(scratch.resolve("distinct_delta"), FIRST_TIME + 1);
      requireSource(conf, first, FIRST_TIME + 1);
      require(migration(catalog, conf, first, distinct).execute().snapshotDataFilesCount() == 0,
          "The fixture should migrate zero data files");
      requireDistinctHistory(catalog.loadTable(distinct));

      TableIdentifier repeated = TableIdentifier.of(NS, "repeated_time");
      Path second = writeSource(scratch.resolve("repeated_delta"), FIRST_TIME);
      requireSource(conf, second, FIRST_TIME);
      require(!catalog.tableExists(repeated), "The repeated case already has a catalog entry");
      try {
        migration(catalog, conf, second, repeated).execute();
        throw new AssertionError("Expected an equal timestamp tag to be rejected");
      } catch (IllegalArgumentException expected) {
        require(("Ref delta-ts-" + FIRST_TIME + " already exists").equals(expected.getMessage()),
            "Unexpected migration exception: " + expected);
      }
      require(!catalog.tableExists(repeated), "The failed case has a catalog entry");
      System.out.println("REPEATED duplicateTimestampTagRejected=true catalogTableExists=false");
    }
  }

  private static Path writeSource(Path root, long secondStoredTime) throws IOException {
    Path log = Files.createDirectories(root.resolve("_delta_log"));
    ObjectNode versionZero = JsonUtil.mapper().createObjectNode();
    versionZero.putObject("protocol").put("minReaderVersion", 1).put("minWriterVersion", 2);
    ObjectNode versionMetadata = JsonUtil.mapper().createObjectNode();
    ObjectNode metadata = versionMetadata.putObject("metaData");
    UUID id = UUID.nameUUIDFromBytes(root.getFileName().toString().getBytes(StandardCharsets.UTF_8));
    metadata.put("id", id.toString());
    metadata.put("schemaString", SCHEMA).put("createdTime", FIRST_TIME);
    metadata.putObject("format").put("provider", "parquet").putObject("options");
    metadata.putArray("partitionColumns");
    metadata.putObject("configuration");
    writeVersion(log, 0, FIRST_TIME,
        List.of(versionZero, versionMetadata, commitInfo(FIRST_TIME, "CREATE TABLE")));
    writeVersion(log, 1, SECOND_FILE_TIME, List.of(commitInfo(secondStoredTime, "WRITE")));
    return root;
  }

  private static ObjectNode commitInfo(long time, String operation) {
    ObjectNode action = JsonUtil.mapper().createObjectNode();
    action.putObject("commitInfo").put("timestamp", time).put("operation", operation)
        .putObject("operationParameters");
    return action;
  }

  private static void writeVersion(Path log, int version, long fileTime, List<ObjectNode> actions)
      throws IOException {
    Path commit = log.resolve(String.format(Locale.ROOT, "%020d.json", version));
    Files.write(commit, actions.stream().map(ObjectNode::toString).toList());
    Files.setLastModifiedTime(commit, FileTime.fromMillis(fileTime));
    require(Files.getLastModifiedTime(commit).toMillis() == fileTime, "Wrong log file time");
  }

  private static void requireSource(Configuration conf, Path source, long secondStoredTime) {
    DeltaLog delta = DeltaLog.forTable(conf, source.toUri().toString());
    require(delta.tableExists(), "The source fixture has no Delta table");
    require(delta.update().getVersion() == 1, "Expected two readable Delta versions");
    require(delta.getSnapshotForVersionAsOf(0).getAllFiles().isEmpty(),
        "Expected an empty version 0");
    require(delta.getSnapshotForVersionAsOf(1).getAllFiles().isEmpty(),
        "Expected an empty version 1");
    require(delta.getVersionBeforeOrAtTimestamp(FIRST_TIME) == 0,
        "Wrong source cutoff at version 0");
    require(delta.getVersionBeforeOrAtTimestamp(SECOND_FILE_TIME) == 1,
        "Wrong source cutoff at version 1");
    require(delta.getCommitInfoAt(0).getTimestamp().getTime() == FIRST_TIME,
        "Wrong v0 commit time");
    require(delta.getCommitInfoAt(1).getTimestamp().getTime() == secondStoredTime,
        "Wrong v1 commit time");
  }

  private static SnapshotDeltaLakeTable migration(
      HadoopCatalog catalog, Configuration conf, Path source, TableIdentifier target) {
    return DeltaLakeToIcebergMigrationActionsProvider.defaultActions()
        .snapshotDeltaLakeTable(source.toUri().toString())
        .icebergCatalog(catalog)
        .as(target)
        .deltaLakeConfiguration(conf)
        .tableLocation(null);
  }

  private static void requireDistinctHistory(Table table) {
    SnapshotRef first = table.refs().get("delta-version-0");
    SnapshotRef second = table.refs().get("delta-version-1");
    require(first != null && first.isTag(), "Missing version 0 tag");
    require(second != null && second.isTag(), "Missing version 1 tag");
    require(first.snapshotId() != second.snapshotId(), "Migration reused a snapshot ID");
    require(first.equals(table.refs().get("delta-ts-" + FIRST_TIME)), "Wrong version 0 time tag");
    require(second.equals(table.refs().get("delta-ts-" + (FIRST_TIME + 1))),
        "Wrong version 1 time tag");
    Snapshot firstSnapshot = table.snapshot(first.snapshotId());
    Snapshot secondSnapshot = table.snapshot(second.snapshotId());
    require(firstSnapshot != null && secondSnapshot != null, "Missing referenced snapshot");
    require(Objects.equals(secondSnapshot.parentId(), first.snapshotId()),
        "The migrated snapshot lineage is incomplete");

    List<HistoryEntry> history = table.history();
    require(history.size() == 1, "Expected just the final main snapshot in published history");
    HistoryEntry committed = history.get(0);
    require(committed.snapshotId() == second.snapshotId(), "Published history points to the wrong version");
    require(committed.timestampMillis() > SECOND_FILE_TIME, "Unexpected history at the original cutoff");
    require(SnapshotUtil.nullableSnapshotIdAsOfTime(table, SECOND_FILE_TIME) == null,
        "The target cutoff unexpectedly resolved to a snapshot");

    long firstCreated = firstSnapshot.timestampMillis();
    Long expectedAtFirst = firstCreated < committed.timestampMillis() ? null : second.snapshotId();
    require(Objects.equals(SnapshotUtil.nullableSnapshotIdAsOfTime(table, firstCreated), expectedAtFirst),
        "Unexpected target lookup at the first snapshot's creation time");
    require(SnapshotUtil.snapshotIdAsOfTime(table, committed.timestampMillis()) == second.snapshotId(),
        "The committed history timestamp selected the wrong snapshot");
    System.out.println("DISTINCT sourceCutoffVersion=1 migratedSnapshots=2 migrationTags=4 "
        + "publishedHistoryEntries=1 targetCutoffSnapshot=null");
  }

  private static void require(boolean condition, String problem) {
    if (!condition) {
      throw new AssertionError(problem);
    }
  }
}
