param (
    [Parameter(Mandatory = $true)] [string]$blueprintName
)

$partnerBasePath = $PSScriptRoot + "/../blueprints/$blueprintName"
$licensesCustomPath = $PSScriptRoot + "/licensesCustomPath.json"

$jsLicenses = [System.Collections.ArrayList]@()

$partnerLibraries = npx license-checker `
--start $partnerBasePath `
--customPath $licensesCustomPath `
--production `
--csv `
| ConvertFrom-Csv 

foreach ($library in $partnerLibraries) {
    if ($library.name.Contains("@insite")) {
      continue
    }
    $libraryInfo = Select-Object -InputObject $library name, @{n = 'type'; e = { $_.licenses } }, @{ n = 'link'; e = { $_.repository } }
    $jsLicenses.Add($libraryInfo) > $null 
}

$jsLicenses | Sort-Object name, licenses  -Unique

$allowedLicensesTypeJsonPath = $PSScriptRoot + "/allowedLicenseTypes.json"

$allowedLicenses = Get-Content -Path $allowedLicensesTypeJsonPath | ConvertFrom-Json

$flaggedLicenses = $jsLicenses | Where-Object { -not $allowedLicenses.Contains($_.type) } | ConvertTo-Json 

if (($flaggedLicenses | Measure-Object | Select-Object -ExpandProperty Count) -gt 0) {
  throw "Error: License check failed: $flaggedLicenses"
}

# Container path is modules/Licensing/$blueprintName-3rdPartyLicenses.json
$outputPath = $PSScriptRoot + "/$blueprintName-3rdPartyLicenses.json"

@{jsLicenses = $jsLicenses } | ConvertTo-Json | Set-Content -Path $outputPath
