"""PowerShell completion handler."""

from .base import CompletionContext, CompletionHandler


class PowerShellCompletionHandler(CompletionHandler):
    """PowerShell-specific completion handler."""

    def generate_script(self, prog_name: str) -> str:
        """Generate PowerShell completion script."""
        script = f"""# PowerShell completion for {prog_name}
# Generated by freyja

Register-ArgumentCompleter -Native -CommandName {prog_name} -ScriptBlock {{
    param($wordToComplete, $commandAst, $cursorPosition)

    # Set up completion environment
    $env:_FREYJA_COMPLETE = "powershell"
    $env:COMP_WORDS_STR = $commandAst.ToString()
    $env:COMP_CWORD_NUM = $commandAst.CommandElements.Count

    # Get completions from the program
    try {{
        $completions = & {prog_name} --_complete 2>$null
        if ($LASTEXITCODE -eq 0) {{
            $completions | Where-Object {{ $_ -like "$wordToComplete*" }}
        }}
    }} catch {{
        # Silently ignore errors
    }} finally {{
        # Clean up environment
        $env:_FREYJA_COMPLETE = $null
        $env:COMP_WORDS_STR = $null
        $env:COMP_CWORD_NUM = $null
    }}
}}
"""
        return script

    def get_completions(self, context: CompletionContext) -> list[str]:
        """Get PowerShell-specific completions."""
        return self._get_generic_completions(context)

    def install_completion(self, prog_name: str) -> bool:
        """Install PowerShell completion."""
        from .installer import CompletionInstaller

        installer = CompletionInstaller(self, prog_name)
        return installer.install("powershell")
