import Foundation







struct RunnerAlertLabelVocabulary {
  static let english = RunnerAlertLabelVocabulary(translations: [])

  private let sources: [String: [String]]

  init(translations: [(english: String, localized: String)]) {
    var sources: [String: [String]] = [:]
    for translation in translations where RunnerAlertButtonChoice.action(of: translation.english, wholeLabel: true) != nil {
      sources[Self.normalized(translation.localized), default: []].append(translation.english)
    }
    self.sources = sources.filter { label, english in
      RunnerAlertButtonChoice.action(of: label) == nil
        && Set(english.compactMap { RunnerAlertButtonChoice.action(of: $0) }).count == 1
    }
  }

  func englishLabels(for label: String) -> [String] {
    sources[Self.normalized(label)] ?? []
  }

  private static func normalized(_ label: String) -> String {
    label.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
  }
}

#if os(iOS) && targetEnvironment(simulator)
extension RunnerAlertLabelVocabulary {


  static let system = fromSystemStrings(languages: Locale.preferredLanguages)


  static func fromSystemStrings(languages: [String]) -> RunnerAlertLabelVocabulary {
    composed(
      permission: RunnerSystemPromptStrings.read(RunnerSystemPromptStrings.promptTables, languages: languages),
      launchConfirmation: RunnerSystemPromptStrings.read([RunnerSystemPromptStrings.launchConfirmationTable], languages: languages),
      languages: languages
    )
  }





  static func composed(
    permission: Result<[RunnerSystemPromptStrings], RunnerSystemPromptStrings.UnavailableSource>,
    launchConfirmation: Result<[RunnerSystemPromptStrings], RunnerSystemPromptStrings.UnavailableSource>,
    languages: [String]
  ) -> RunnerAlertLabelVocabulary {
    var tables: [RunnerSystemPromptStrings] = []
    switch permission {
    case .failure(let failure):
      RunnerSystemPromptStrings.logUnavailable(failure, subsystem: "alert-vocabulary", languages: languages)
    case .success(let read):
      tables = read
    }
    switch launchConfirmation {
    case .failure(let failure):
      RunnerSystemPromptStrings.logUnavailable(failure, subsystem: "alert-vocabulary-launch-confirmation", languages: languages)
    case .success(let read):
      tables += read.map { $0.limited(to: RunnerSystemPromptStrings.launchConfirmationLabelKeys) }
    }
    var translations: [(english: String, localized: String)] = []
    for table in tables {
      for strings in table.localized.values {
        for (key, value) in table.english {
          if let translation = strings[key] { translations.append((english: value, localized: translation)) }
        }
      }
    }
    return RunnerAlertLabelVocabulary(translations: translations)
  }
}
#else
extension RunnerAlertLabelVocabulary {
  static let system = english
}
#endif
