Public/Set-PCSecret.ps1

function Set-PCSecret {
    <#
    .SYNOPSIS
        Stores or updates a secret for a service.

    .DESCRIPTION
        Writes the secret to ~/.powercraft/secrets.json with restrictive file permissions.
        Creates the store if it doesn't exist.

    .PARAMETER Name
        Service name (e.g., 'openai', 'anthropic', 'brave-search').

    .PARAMETER ApiKey
        The API key value to store.

    .PARAMETER Properties
        A hashtable of properties to store (for services with multiple values).
        Merged with any existing properties for the service.

    .PARAMETER EnvVar
        Optional custom environment variable name for Import-PCSecrets.

    .EXAMPLE
        Set-PCSecret -Name 'openai' -ApiKey 'sk-proj-...'

    .EXAMPLE
        Set-PCSecret -Name 'azure' -Properties @{ speechKey = 'abc'; region = 'westeurope' }

    .EXAMPLE
        Set-PCSecret -Name 'custom-api' -ApiKey 'key123' -EnvVar 'MY_CUSTOM_KEY'
    #>

    [CmdletBinding(SupportsShouldProcess)]
    param(
        [Parameter(Mandatory, Position = 0)]
        [string]$Name,

        [Parameter(ParameterSetName = 'ApiKey')]
        [string]$ApiKey,

        [Parameter(ParameterSetName = 'Properties')]
        [hashtable]$Properties,

        [Parameter()]
        [string]$EnvVar
    )

    $secrets = Read-PCSecretsFile

    # Build the entry
    if (-not $secrets[$Name]) { $secrets[$Name] = @{} }

    if ($PSCmdlet.ParameterSetName -eq 'Properties' -and $Properties) {
        foreach ($key in $Properties.Keys) {
            $secrets[$Name][$key] = $Properties[$key]
        }
    }
    else {
        $secrets[$Name]['apiKey'] = $ApiKey
    }

    # Store custom env var mapping if provided
    if ($EnvVar) {
        $secrets[$Name]['envVar'] = $EnvVar
    }

    # Mask for ShouldProcess display
    $displayValue = if ($ApiKey) {
        $ApiKey.Substring(0, [Math]::Min(12, $ApiKey.Length)) + '...'
    }
    else {
        '(properties)'
    }

    if ($PSCmdlet.ShouldProcess("$Name", "Set secret ($displayValue)")) {
        Write-PCSecretsFile -Secrets $secrets
        Write-Verbose "Saved secret: $Name"
    }
}