AudienceOverlap.psm1

Set-StrictMode -Version Latest

function ConvertTo-Share([double]$num, [double]$den) {
    if ($den -le 0) { return $null }
    [math]::Round($num / $den * 100, 1, [System.MidpointRounding]::AwayFromZero)
}

function ConvertTo-OverlapKey([string]$value, [bool]$isDomain) {
    $k = $value.Trim().ToLowerInvariant()
    if ($isDomain) {
        $k = $k -replace '^https?://', ''
        $k = $k -replace '^www\.', ''
        $slash = $k.IndexOf('/')
        if ($slash -ge 0) { $k = $k.Substring(0, $slash) }
        $k = $k.Trim()
    }
    $k
}

function Read-OverlapKeys([string]$path, [string]$keyColumn) {
    if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { throw "file not found: $path" }
    $rows = @(Import-Csv -LiteralPath $path)
    $set = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::Ordinal)
    $blank = 0
    $dups = 0
    if ($rows.Count -gt 0) {
        $col = $null
        foreach ($h in $rows[0].PSObject.Properties.Name) { if ($h -ieq $keyColumn) { $col = $h; break } }
        if ($null -eq $col) { throw "missing key column '$keyColumn' in $path" }
        $isDomain = ($keyColumn -ieq 'domain')
        foreach ($r in $rows) {
            $k = ConvertTo-OverlapKey ([string]$r.PSObject.Properties[$col].Value) $isDomain
            if ($k -eq '') { $blank++ }
            elseif (-not $set.Add($k)) { $dups++ }
        }
    }
    else {
        # a file with a header only has no rows: check the header line for the key column
        $first = Get-Content -LiteralPath $path -TotalCount 1
        if ([string]::IsNullOrWhiteSpace($first)) { throw "missing key column '$keyColumn' in $path" }
        $names = @($first | ConvertFrom-Csv -Header (1..([regex]::Matches($first, ',').Count + 1) | ForEach-Object { "c$_" }) | ForEach-Object { $_.PSObject.Properties.Value })
        $found = $false
        foreach ($n in $names) { if (([string]$n).Trim('"').Trim() -ieq $keyColumn) { $found = $true } }
        if (-not $found) { throw "missing key column '$keyColumn' in $path" }
    }
    [pscustomobject]@{ Keys = $set; Blank = $blank; Duplicates = $dups }
}

function Get-AudienceOverlap {
<#
.SYNOPSIS
Compare a seed audience with a candidate list by a key column and report how much they overlap.
.DESCRIPTION
Both CSV files need the key column (default email; header matching is case-insensitive). Keys are trimmed and lowercased.
When the key column is named domain, a leading http:// or https://, a leading www. and everything after the first slash are removed too.
Blank keys are skipped and counted. A key repeated within one list counts once and the repeats are counted.
Returns one object: SeedUnique, CandidateUnique, InBoth, OnlySeed, OnlyCandidate, SeedInCandidatePct, CandidateInSeedPct,
JaccardPct (in both divided by the union, as a percentage), SeedBlank, SeedDuplicates, CandidateBlank, CandidateDuplicates and Report.
A share is empty (null) when its list has no keys.
.EXAMPLE
Get-AudienceOverlap -SeedPath seed.csv -CandidatePath candidates.csv
#>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][string]$SeedPath,
        [Parameter(Mandatory)][string]$CandidatePath,
        [string]$KeyColumn = 'email'
    )

    if ([string]::IsNullOrWhiteSpace($KeyColumn)) { throw 'KeyColumn must not be empty' }
    $seed = Read-OverlapKeys $SeedPath $KeyColumn
    $cand = Read-OverlapKeys $CandidatePath $KeyColumn

    $both = 0
    foreach ($k in $seed.Keys) { if ($cand.Keys.Contains($k)) { $both++ } }
    $su = $seed.Keys.Count
    $cu = $cand.Keys.Count
    $union = $su + $cu - $both

    $sShare = ConvertTo-Share $both $su
    $cShare = ConvertTo-Share $both $cu
    $jac = ConvertTo-Share $both $union
    function Show($v) { if ($null -eq $v) { 'n/a' } else { '{0:0.0}%' -f $v } }

    $lines = @(
        "Key column: $KeyColumn",
        "Seed unique keys: $su",
        "Candidate unique keys: $cu",
        "In both: $both",
        "Only in seed: $($su - $both)",
        "Only in candidate: $($cu - $both)",
        "Seed also in candidate: $(Show $sShare)",
        "Candidate also in seed: $(Show $cShare)",
        "Jaccard overlap: $(Show $jac)",
        "Seed: $($seed.Blank) blank skipped, $($seed.Duplicates) duplicates removed",
        "Candidate: $($cand.Blank) blank skipped, $($cand.Duplicates) duplicates removed"
    )

    [pscustomobject]@{
        KeyColumn           = $KeyColumn
        SeedUnique          = $su
        CandidateUnique     = $cu
        InBoth              = $both
        OnlySeed            = $su - $both
        OnlyCandidate       = $cu - $both
        SeedInCandidatePct  = $sShare
        CandidateInSeedPct  = $cShare
        JaccardPct          = $jac
        SeedBlank           = $seed.Blank
        SeedDuplicates      = $seed.Duplicates
        CandidateBlank      = $cand.Blank
        CandidateDuplicates = $cand.Duplicates
        Report              = ($lines -join [Environment]::NewLine)
    }
}

Export-ModuleMember -Function Get-AudienceOverlap