//===--- NinjaBuildDir.swift ----------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

import Synchronization

public final class NinjaBuildDir: Sendable {
  public let path: AbsolutePath
  public let projectRootDir: AbsolutePath
  private let _tripleSuffix: Result<String, any Error>

  private let repoBuildDirs = Mutex<[Repo: RepoBuildDir]>()

  private static func detectTripleSuffix(
    buildDir: AbsolutePath
  ) -> Result<String, any Error> {
    Result {
      for dir in try buildDir.getDirContents() {
        guard buildDir.appending(dir).isDirectory,
              let triple = dir.fileName.tryDropPrefix("swift-") else {
          continue
        }
        return triple
      }
      let couldBeParent = buildDir.fileName.hasPrefix("swift-")
      throw XcodeGenError.noSwiftBuildDir(buildDir, couldBeParent: couldBeParent)
    }
  }

  public var tripleSuffix: String {
    get throws {
      try _tripleSuffix.get()
    }
  }

  // We can infer the project root from the location of swift-xcodegen itself.
  //                      1     2         3          4           5         6      7
  // #filePath = <root>/swift/utils/swift-dev-utils/Sources/SwiftXcodeGen/Ninja/NinjaBuildDir.swift
  internal static let fallbackProjectRootPath = AbsolutePath(#filePath).dropLast(7)

  private static func detectProjectRoot(
    buildDir: AbsolutePath
  ) throws -> AbsolutePath {
    // First try to infer the project root relative to the build directory,
    // according to where build-script normally puts it:
    // '<root>/build/<build-dir>'. This lets swift-xcodegen produce a
    // correct project when run against a build directory belonging to a
    // different checkout than the one containing this file.
    //
    // TODO: Explore the possibility of inferring source directories on demand
    //       from CMake cache files instead of inferring a project root early.
    //       This will cover both the case described above and worktrees.
    if let parent = buildDir.parentDir, parent.fileName == "build",
      let projectRoot = parent.parentDir,
      projectRoot.appending(Repo.swift.relativePath).exists
    {
      return projectRoot
    }

    log.warning(
      """
      Failed to infer project root directory from build directory \
      '\(buildDir)'; falling back to '\(Self.fallbackProjectRootPath)'
      """
    )

    let inferredSwiftPath = fallbackProjectRootPath.appending(Repo.swift.relativePath)
    guard inferredSwiftPath.exists else {
      throw XcodeGenError.couldNotInferProjectRoot(
        reason: "expected swift repo at '\(inferredSwiftPath)'"
      )
    }
    return fallbackProjectRootPath
  }
  
  public init(at path: AbsolutePath, projectRootDir: AbsolutePath?) throws {
    guard path.exists else {
      throw XcodeGenError.pathNotFound(path)
    }
    self.path = path
    self._tripleSuffix = Self.detectTripleSuffix(buildDir: path)

    if let projectRootDir {
      self.projectRootDir = projectRootDir
    } else {
      self.projectRootDir = try Self.detectProjectRoot(buildDir: path)
      log.debug("Inferred project root directory as '\(self.projectRootDir)'")
    }
  }
  
  public func buildDir(for repo: Repo) throws -> RepoBuildDir {
    try repoBuildDirs.withLock { repoBuildDirs in
      if let buildDir = repoBuildDirs[repo] {
        return buildDir
      }
      let dir = try RepoBuildDir(repo, for: self)
      repoBuildDirs[repo] = dir
      return dir
    }
  }
}
