/*
 * Copyright © 2024-2026 Apple Inc. and the Pkl project authors. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.pkl.config.java.mapper;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import org.jspecify.annotations.Nullable;
import org.pkl.config.java.InvalidMappingException;
import org.pkl.core.PClassInfo;
import org.pkl.core.util.IoUtils;

/**
 * Describes mappings of Pkl class names to their corresponding Java classes.
 *
 * <p>This is used by {@link ValueMapper} to pick the correct Java class when mapping Pkl into Java.
 *
 * <p>Mappings are determined by scanning the <code>
 * /META-INF/org/pkl/config/java/mapper/classes</code> directory for properties files.
 *
 * <p>Property files should be in the form of <code>
 * org.pkl.config.java.mapper.[PKL_CLASS_NAME]=[JAVA_REFLECTION_CLASS_NAME]</code>
 *
 * <p>Mappings are optional, and only required if Pkl types are polymorphic.
 *
 * <p>They are generated by the Java and Kotlin code generators, and can be handwritten if not using
 * codegen.
 */
public class ClassRegistry {

  private static final Properties classMappings = new Properties();

  private static final Object lock = new Object();

  private static final String CLASSES_DIRECTORY = "/META-INF/org/pkl/config/java/mapper/classes";

  private static final String PREFIX = "org.pkl.config.java.mapper.";

  private static final Set<String> loadedModules = new HashSet<>();

  private ClassRegistry() {}

  static @Nullable Class<?> get(PClassInfo<?> pklClassInfo) {
    var pklModuleName = pklClassInfo.getModuleName();
    var pklClassName = pklClassInfo.getQualifiedName();
    initClassMappings(pklModuleName);
    var javaName = classMappings.getProperty(PREFIX + pklClassInfo.getQualifiedName());
    if (javaName == null) {
      return null;
    }
    try {
      return Class.forName(javaName);
    } catch (ClassNotFoundException e) {
      throw new InvalidMappingException(pklClassName, javaName, e);
    }
  }

  private static void initClassMappings(String pklModuleName) {
    synchronized (lock) {
      if (loadedModules.contains(pklModuleName)) {
        return;
      }
      loadedModules.add(pklModuleName);
      var url =
          ClassRegistry.class.getResourceAsStream(
              CLASSES_DIRECTORY + "/" + IoUtils.encodePath(pklModuleName) + ".properties");
      if (url == null) {
        return;
      }
      try {
        classMappings.load(url);
      } catch (IOException e) {
        throw new UncheckedIOException(e);
      }
    }
  }
}
