tests/PowerCraft.AI.Tests.ps1

BeforeAll {
    # The module requires PowerCraft.Secrets 2.2.0 or later and takes a key with its
    # Resolve-PCSecret. That command is run as it is. What it asks of the store, Get-PCSecret,
    # is mocked inside PowerCraft.Secrets, so no test reads the store of the machine. And the
    # home of the store is an empty folder for this file: a call that a mock missed would
    # find no store there, and no key of the machine would reach a provider.
    $script:SavedHome = $env:POWERCRAFT_HOME
    $env:POWERCRAFT_HOME = Join-Path ([IO.Path]::GetTempPath()) "PowerCraftAITests_$([guid]::NewGuid().ToString('N').Substring(0, 8))"
    $null = New-Item -ItemType Directory -Path $env:POWERCRAFT_HOME -Force

    $modulePath = Split-Path $PSScriptRoot -Parent
    Import-Module $modulePath -Force

    # A key in the environment of the machine that runs the tests would answer before the
    # mocked store. The variables are taken out for this file and put back after it.
    $script:KeyVariables = 'OPENAI_API_KEY', 'GEMINI_API_KEY', 'GOOGLE_API_KEY', 'ANTHROPIC_API_KEY'
    $script:SavedKeyVariables = @{}
    foreach ($name in $script:KeyVariables) {
        $script:SavedKeyVariables[$name] = [Environment]::GetEnvironmentVariable($name)
        [Environment]::SetEnvironmentVariable($name, $null)
    }
}

AfterAll {
    foreach ($name in $script:KeyVariables) {
        [Environment]::SetEnvironmentVariable($name, $script:SavedKeyVariables[$name])
    }
    Remove-Item -LiteralPath $env:POWERCRAFT_HOME -Recurse -Force -ErrorAction SilentlyContinue
    $env:POWERCRAFT_HOME = $script:SavedHome
}

Describe 'Module loads correctly' {
    It 'Exports expected functions' {
        $expected = @(
            'Invoke-PCCompletion'
            'Invoke-PCCompletionCached'
            'Get-PCProviders'
            'Test-PCProvider'
        )
        $exported = (Get-Module PowerCraft.AI).ExportedFunctions.Keys
        foreach ($fn in $expected) {
            $exported | Should -Contain $fn
        }
    }
}

Describe 'What it requires of PowerCraft.Secrets' {
    It 'Requires the version that has Resolve-PCSecret' {
        $manifest = Import-PowerShellDataFile (Join-Path (Split-Path $PSScriptRoot -Parent) 'PowerCraft.AI.psd1')
        $needs = $manifest.RequiredModules | Where-Object { $_.ModuleName -eq 'PowerCraft.Secrets' }

        [version]$needs.ModuleVersion | Should -BeGreaterOrEqual ([version]'2.2.0')
        Get-Command Resolve-PCSecret -Module PowerCraft.Secrets -ErrorAction SilentlyContinue | Should -Not -BeNullOrEmpty
    }

    It 'Reads no environment variable and no store itself' {
        # One place takes a key, and it is one call. The names are put together here so
        # that this file does not hold them.
        $own = @(('GetEnvironment' + 'Variable'), ('Get-PC' + 'Secret\b'), ('\$env:\w+_API' + '_KEY'))
        $own.Count | Should -Be 3
        $root = Split-Path $PSScriptRoot -Parent
        $hits = Get-ChildItem (Join-Path $root 'Private'), (Join-Path $root 'Public') -Filter *.ps1 |
            Select-String -Pattern ($own -join '|')

        $hits | ForEach-Object { "$($_.Filename):$($_.LineNumber)" } | Should -BeNullOrEmpty
    }
}

Describe 'Provider configuration' {
    It 'Has openai provider defined' {
        InModuleScope PowerCraft.AI {
            $script:Providers.ContainsKey('openai') | Should -BeTrue
            $script:Providers.openai.DefaultModel | Should -Not -BeNullOrEmpty
        }
    }

    It 'Has gemini provider defined' {
        InModuleScope PowerCraft.AI {
            $script:Providers.ContainsKey('gemini') | Should -BeTrue
            $script:Providers.gemini.DefaultModel | Should -Not -BeNullOrEmpty
        }
    }

    It 'Has anthropic provider defined' {
        InModuleScope PowerCraft.AI {
            $script:Providers.ContainsKey('anthropic') | Should -BeTrue
            $script:Providers.anthropic.DefaultModel | Should -Not -BeNullOrEmpty
        }
    }
}

Describe 'Resolve-PCApiKey' {
    It 'Returns key from secrets store' {
        InModuleScope PowerCraft.AI {
            Mock Get-PCSecret -ModuleName PowerCraft.Secrets { return 'secret-key-123' } -ParameterFilter { $Name -eq 'openai' }
            $result = Resolve-PCApiKey -Provider 'openai'
            $result | Should -Be 'secret-key-123'
        }
    }

    It 'Returns null when no key in secrets store' {
        InModuleScope PowerCraft.AI {
            Mock Get-PCSecret -ModuleName PowerCraft.Secrets { return $null }
            $result = Resolve-PCApiKey -Provider 'openai'
            $result | Should -BeNullOrEmpty
        }
    }

    It 'Uses correct secret name per provider' {
        InModuleScope PowerCraft.AI {
            Mock Get-PCSecret -ModuleName PowerCraft.Secrets { return 'gemini-key' } -ParameterFilter { $Name -eq 'gemini' }
            $result = Resolve-PCApiKey -Provider 'gemini'
            $result | Should -Be 'gemini-key'
        }
    }

    It 'Resolves anthropic provider' {
        InModuleScope PowerCraft.AI {
            Mock Get-PCSecret -ModuleName PowerCraft.Secrets { return 'anthropic-key' } -ParameterFilter { $Name -eq 'anthropic' }
            $result = Resolve-PCApiKey -Provider 'anthropic'
            $result | Should -Be 'anthropic-key'
        }
    }

    Context 'A key in the environment' {
        # Resolve-PCSecret reads the variables the module names: Get-PCSecret reads the store only.
        AfterEach {
            foreach ($name in 'OPENAI_API_KEY', 'GEMINI_API_KEY', 'GOOGLE_API_KEY', 'ANTHROPIC_API_KEY') {
                [Environment]::SetEnvironmentVariable($name, $null)
            }
        }

        It 'Returns the key from <Variable> when the store has none' -ForEach @(
            @{ Provider = 'openai'; Variable = 'OPENAI_API_KEY' }
            @{ Provider = 'gemini'; Variable = 'GEMINI_API_KEY' }
            @{ Provider = 'gemini'; Variable = 'GOOGLE_API_KEY' }
            @{ Provider = 'anthropic'; Variable = 'ANTHROPIC_API_KEY' }
        ) {
            [Environment]::SetEnvironmentVariable($Variable, "env-key-of-$Provider")
            InModuleScope PowerCraft.AI -Parameters @{ Provider = $Provider } {
                Mock Get-PCSecret -ModuleName PowerCraft.Secrets { return $null }
                Resolve-PCApiKey -Provider $Provider | Should -Be "env-key-of-$Provider"
            }
        }

        It 'Lets the variable win over the store, and does not ask the store' {
            [Environment]::SetEnvironmentVariable('OPENAI_API_KEY', 'env-key')
            InModuleScope PowerCraft.AI {
                Mock Get-PCSecret -ModuleName PowerCraft.Secrets { return 'store-key' }
                Resolve-PCApiKey -Provider 'openai' | Should -Be 'env-key'
                Should -Invoke Get-PCSecret -ModuleName PowerCraft.Secrets -Times 0 -Exactly
            }
        }

        It 'Reads GEMINI_API_KEY before GOOGLE_API_KEY' {
            [Environment]::SetEnvironmentVariable('GEMINI_API_KEY', 'gemini-named')
            [Environment]::SetEnvironmentVariable('GOOGLE_API_KEY', 'google-named')
            InModuleScope PowerCraft.AI {
                Mock Get-PCSecret -ModuleName PowerCraft.Secrets { return $null }
                Resolve-PCApiKey -Provider 'gemini' | Should -Be 'gemini-named'
            }
        }

        It 'Does not answer one provider from the variable of another' {
            [Environment]::SetEnvironmentVariable('OPENAI_API_KEY', 'env-key')
            InModuleScope PowerCraft.AI {
                Mock Get-PCSecret -ModuleName PowerCraft.Secrets { return $null }
                Resolve-PCApiKey -Provider 'anthropic' | Should -BeNullOrEmpty
            }
        }

        It 'Says once that the store could not be read, and still lists a provider from the environment' {
            # What a PowerCraft.Secrets 2 store does when it is locked on the machine: it throws.
            [Environment]::SetEnvironmentVariable('ANTHROPIC_API_KEY', 'env-key')
            # PowerCraft.Secrets keeps what it has said for the session: forgotten here, so
            # that this test does not depend on the ones before it.
            & (Get-Module PowerCraft.Secrets) { $script:PCStoreProblemsSaid.Clear() }
            InModuleScope PowerCraft.AI {
                Mock Get-PCSecret -ModuleName PowerCraft.Secrets { throw 'the store is locked here' }

                # Two providers have no variable, so the store is asked twice and says it once.
                $all = @(Get-PCProviders 3>&1)
                $said = @($all | Where-Object { $_ -is [System.Management.Automation.WarningRecord] })
                $providers = @($all | Where-Object { $_ -isnot [System.Management.Automation.WarningRecord] })

                $providers.Provider | Should -Be @('anthropic')
                @($said | Where-Object { "$_" -match 'the store is locked here' }).Count | Should -Be 1
                Should -Invoke Get-PCSecret -ModuleName PowerCraft.Secrets -Times 2 -Exactly
                { Invoke-PCCompletion -Provider openai -UserPrompt 'x' 3>$null } | Should -Throw '*No API key*'
            }
        }

        It 'Lists a provider whose key is only in the environment' {
            [Environment]::SetEnvironmentVariable('ANTHROPIC_API_KEY', 'env-key')
            InModuleScope PowerCraft.AI {
                Mock Get-PCSecret -ModuleName PowerCraft.Secrets { return $null }
                @(Get-PCProviders).Provider | Should -Be @('anthropic')
            }
        }
    }
}

Describe 'Get-PCProviders' {
    # Get-PCProviders asks for every provider's key. The default mock answers for the ones a
    # test does not name: Pester 6 throws on an unmatched call, and Pester 5 let it through
    # to the real secrets store of whichever machine ran the test.
    It 'Returns providers with configured keys' {
        InModuleScope PowerCraft.AI {
            Mock Get-PCSecret -ModuleName PowerCraft.Secrets { return $null }
            Mock Get-PCSecret -ModuleName PowerCraft.Secrets { return 'test-key' } -ParameterFilter { $Name -eq 'openai' }
            $result = Get-PCProviders
            $result | Where-Object Provider -eq 'openai' | Should -Not -BeNullOrEmpty
        }
    }

    It 'Shows DefaultModel for each provider' {
        InModuleScope PowerCraft.AI {
            Mock Get-PCSecret -ModuleName PowerCraft.Secrets { return $null }
            Mock Get-PCSecret -ModuleName PowerCraft.Secrets { return 'test-key' } -ParameterFilter { $Name -eq 'gemini' }
            $result = Get-PCProviders
            $gemini = $result | Where-Object Provider -eq 'gemini'
            $gemini.DefaultModel | Should -Not -BeNullOrEmpty
        }
    }
}

Describe 'Invoke-PCCompletion parameter validation' {
    It 'Throws when no provider can be resolved' {
        InModuleScope PowerCraft.AI {
            Mock Get-PCSecret -ModuleName PowerCraft.Secrets { return $null }
            { Invoke-PCCompletion -UserPrompt "test" } | Should -Throw '*No AI provider*'
        }
    }

    It 'Throws when API key missing for specified provider' {
        InModuleScope PowerCraft.AI {
            Mock Get-PCSecret -ModuleName PowerCraft.Secrets { return $null }
            { Invoke-PCCompletion -Provider openai -UserPrompt "test" } | Should -Throw '*No API key*'
        }
    }

    It 'Auto-detects provider from model name' {
        InModuleScope PowerCraft.AI {
            Mock Get-PCSecret -ModuleName PowerCraft.Secrets { return 'fake-key' } -ParameterFilter { $Name -eq 'gemini' }
            # This will throw on API call but should correctly pick gemini provider
            { Invoke-PCCompletion -Model 'gemini-2.5-flash' -UserPrompt "test" } | Should -Throw
        }
    }
}

Describe 'Invoke-PCCompletionCached' {
    BeforeAll {
        $cacheDir = Join-Path $TestDrive 'ai-cache'
    }

    It 'Creates cache file on miss' {
        # Pre-populate a cache file to simulate a hit (we cannot call real APIs)
        $cacheFile = Join-Path $cacheDir 'test-item.json'
        New-Item -ItemType Directory -Path $cacheDir -Force | Out-Null
        @{
            schema       = 'ai-response-cache'
            version      = '1.0'
            cache_key    = 'test-item'
            metadata     = @{
                model       = 'gpt-4o'
                provider    = 'openai'
                timestamp   = (Get-Date).ToString('o')
                duration_ms = 1000
                max_tokens  = 4096
                response_length = 5
            }
            raw_response = 'Hello'
        } | ConvertTo-Json -Depth 5 | Set-Content $cacheFile

        $result = Invoke-PCCompletionCached -UserPrompt "test" -CachePath $cacheDir -CacheKey 'test-item' -Provider openai
        $result | Should -Be 'Hello'
    }

    It 'Returns cached response on hit' {
        $cacheFile = Join-Path $cacheDir 'cached-hit.json'
        @{
            schema       = 'ai-response-cache'
            version      = '1.0'
            cache_key    = 'cached-hit'
            metadata     = @{
                model       = 'gpt-4o'
                provider    = 'openai'
                timestamp   = (Get-Date).ToString('o')
                duration_ms = 500
                max_tokens  = 4096
                response_length = 11
            }
            raw_response = 'cached reply'
        } | ConvertTo-Json -Depth 5 | Set-Content $cacheFile

        $result = Invoke-PCCompletionCached -UserPrompt "anything" -CachePath $cacheDir -CacheKey 'cached-hit' -Provider openai
        $result | Should -Be 'cached reply'
    }

    It 'Respects cache TTL — returns cached if not expired' {
        $cacheFile = Join-Path $cacheDir 'ttl-fresh.json'
        @{
            schema       = 'ai-response-cache'
            version      = '1.0'
            cache_key    = 'ttl-fresh'
            metadata     = @{
                model       = 'gpt-4o'
                provider    = 'openai'
                timestamp   = (Get-Date).ToString('o')
                duration_ms = 100
                max_tokens  = 4096
                response_length = 5
            }
            raw_response = 'fresh'
        } | ConvertTo-Json -Depth 5 | Set-Content $cacheFile

        $result = Invoke-PCCompletionCached -UserPrompt "x" -CachePath $cacheDir -CacheKey 'ttl-fresh' -CacheTTLHours 24
        $result | Should -Be 'fresh'
    }

    It 'Expires cache when TTL exceeded' {
        $cacheFile = Join-Path $cacheDir 'ttl-expired.json'
        @{
            schema       = 'ai-response-cache'
            version      = '1.0'
            cache_key    = 'ttl-expired'
            metadata     = @{
                model       = 'gpt-4o'
                provider    = 'openai'
                timestamp   = (Get-Date).AddHours(-48).ToString('o')
                duration_ms = 100
                max_tokens  = 4096
                response_length = 7
            }
            raw_response = 'expired'
        } | ConvertTo-Json -Depth 5 | Set-Content $cacheFile

        # Will try to call API and fail (no real key), which proves cache was skipped
        InModuleScope PowerCraft.AI -Parameters @{ cacheDir = $cacheDir } {
            Mock Get-PCSecret -ModuleName PowerCraft.Secrets { return $null }
            { Invoke-PCCompletionCached -UserPrompt "x" -CachePath $cacheDir -CacheKey 'ttl-expired' -CacheTTLHours 1 -Provider openai } | Should -Throw '*No API key*'
        }
    }
}

Describe 'Test-PCProvider' {
    It 'Returns false when no key configured' {
        InModuleScope PowerCraft.AI {
            Mock Get-PCSecret -ModuleName PowerCraft.Secrets { return $null }
            $result = Test-PCProvider -Name openai -WarningAction SilentlyContinue
            $result | Should -BeFalse
        }
    }
}