import xsbti.HashedVirtualFileRef

autoAPIMappings := true
packageDoc / publishArtifact := false
packageSrc / publishArtifact := false
organization := "org.example"
scalaVersion := "3.2.1"
version := "1.0"

val aPublishResolver = Def.setting {
  Resolver.file("a-resolver", (ThisBuild / baseDirectory).value / "a-repo")
}
val aResolver = Def.setting {
  val dir = (ThisBuild / baseDirectory).value
  "a-resolver" at s"file://${dir.getAbsolutePath}/a-repo"
}

val bResolver = Def.setting {
  val dir = (ThisBuild / baseDirectory).value / "b-repo"
  Resolver.file("b-resolver", dir)(Resolver.defaultIvyPatterns)
}

val apiBaseSetting = apiURL := Some(apiBase(name.value))
def apiBase(projectName: String) = url(s"http://example.org/${projectName}")
def scalaLibraryBase(v: String) = url(s"https://www.scala-lang.org/api/$v/")
def addDep(projectName: String) =
  libraryDependencies += organization.value %% projectName % version.value

val checkApiMappings = taskKey[Unit]("Verifies that the API mappings are collected as expected.")

def expectedMappings = Def.task {
  val stdLibVersion = "2.13.10"
  val binVersion = scalaBinaryVersion.value
  val converter = fileConverter.value
  val ms = update.value.configuration(Compile).get.modules.flatMap { mod =>
    mod.artifacts.flatMap { case (a, f) =>
      val n = a.name.stripSuffix("_" + binVersion)
      n match {
        case "a" | "b" | "c" =>
          (converter.toVirtualFile(f.toPath()): HashedVirtualFileRef, apiBase(n)) :: Nil
        case "scala-library" =>
          (
            converter.toVirtualFile(f.toPath()): HashedVirtualFileRef,
            scalaLibraryBase(stdLibVersion)
          ) :: Nil
        case _ => Nil
      }
    }
  }
  val mc = (c / Compile / packageBin).value -> apiBase("c")
  (mc +: ms).toMap
}

val a = project.settings(
  apiBaseSetting,
  publishMavenStyle := true,
  publishTo := Some(aPublishResolver.value)
)

val b = project.settings(
  apiBaseSetting,
  publishMavenStyle := false,
  publishTo := Some(bResolver.value)
)

val c = project.settings(apiBaseSetting)

val d = project
  .dependsOn(c)
  .settings(
    externalResolvers := Def.uncached(Seq(aResolver.value, bResolver.value)),
    addDep("a"),
    addDep("b"),
    checkApiMappings := Def.uncached {
      val actual = (Compile / doc / apiMappings).value
      println("Actual API Mappings: " + actual.mkString("\n\t", "\n\t", ""))
      val expected = expectedMappings.value
      println("Expected API Mappings: " + expected.mkString("\n\t", "\n\t", ""))
      assert(actual.toString.replaceAll(">sha256-.*/256", "") == expected.toString)
    }
  )
