param(
    [Parameter(Position = 0)]
    [string]$Command = "status"
)

Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"

function Emit-Json {
    param([Parameter(Mandatory = $true)][string]$Payload)
    Write-Output $Payload
}

function Resolve-AgentRoot {
    # .../iuve_connect_agents/desktop/platform_adapters/windows -> install root
    return (Resolve-Path (Join-Path $PSScriptRoot "../../../..")).Path
}

function Resolve-PythonExe {
    param([Parameter(Mandatory = $true)][string]$AgentRoot)

    $BundledPython = Join-Path $AgentRoot "runtime/python/python.exe"
    if (Test-Path $BundledPython) {
        return $BundledPython
    }
    if ($env:IUVE_AGENT_PYTHON -and (Test-Path $env:IUVE_AGENT_PYTHON)) {
        return $env:IUVE_AGENT_PYTHON
    }
    $SystemPython = Get-Command python -ErrorAction SilentlyContinue
    if ($SystemPython) {
        return $SystemPython.Source
    }
    return $null
}

function Resolve-BackgroundPythonExe {
    param([Parameter(Mandatory = $true)][string]$AgentRoot)

    $BundledPythonw = Join-Path $AgentRoot "runtime/python/pythonw.exe"
    if (Test-Path $BundledPythonw) {
        return $BundledPythonw
    }
    $ForegroundPython = Resolve-PythonExe -AgentRoot $AgentRoot
    if ($null -eq $ForegroundPython) {
        return $null
    }
    $SiblingPythonw = Join-Path (Split-Path $ForegroundPython -Parent) "pythonw.exe"
    if (Test-Path $SiblingPythonw) {
        return $SiblingPythonw
    }
    return $ForegroundPython
}

function Open-IuveConnectWeb {
    param([string]$Url = "https://www.iuve.eu/app/connect")

    try {
        Start-Process $Url | Out-Null
    } catch {
        # Best-effort only; agent start must not fail if browser launch fails.
    }
}

function Invoke-AgentModule {
    param(
        [Parameter(Mandatory = $true)][string]$PythonExe,
        [Parameter(Mandatory = $true)][string]$AgentRoot,
        [Parameter(Mandatory = $true)][string[]]$Args
    )

    $env:PYTHONPATH = "$(Join-Path $AgentRoot 'vendor');$AgentRoot"
    $previousLocation = Get-Location
    try {
        Set-Location $AgentRoot
        & $PythonExe -m iuve_connect_agents.desktop.app @Args
        return $LASTEXITCODE
    } finally {
        Set-Location $previousLocation
    }
}

function Test-NativeConsoleEnabled {
    $raw = [string]$env:IUVE_WIN_NATIVE_CONSOLE
    if ([string]::IsNullOrWhiteSpace($raw)) {
        return $true
    }
    $v = $raw.Trim().ToLowerInvariant()
    return -not ($v -eq "0" -or $v -eq "false" -or $v -eq "no" -or $v -eq "off")
}

function Test-ForceBrowserConsole {
    $raw = [string]$env:IUVE_WIN_NO_WEBVIEW
    if ([string]::IsNullOrWhiteSpace($raw)) {
        return $false
    }
    $v = $raw.Trim().ToLowerInvariant()
    return ($v -eq "1" -or $v -eq "true" -or $v -eq "yes" -or $v -eq "on")
}

function Open-NativeConsole {
    param(
        [Parameter(Mandatory = $true)][string]$AgentRoot,
        [Parameter(Mandatory = $true)][string]$PythonExe,
        [Parameter(Mandatory = $true)][string]$ConfigPath
    )

    $env:PYTHONPATH = "$(Join-Path $AgentRoot 'vendor');$AgentRoot"
    $env:IUVE_AGENT_PYTHON = $PythonExe
    $logDir = Join-Path $env:USERPROFILE ".config\iuve-connect-agent"
    if (-not (Test-Path $logDir)) {
        New-Item -ItemType Directory -Path $logDir -Force | Out-Null
    }
    # Prefer pythonw so Console has no black cmd flash; pywebview owns the window.
    $UiPython = Resolve-BackgroundPythonExe -AgentRoot $AgentRoot
    if ($null -eq $UiPython) {
        $UiPython = $PythonExe
    }
    $args = @(
        "-m", "iuve_connect_agents.desktop.ui_bridge",
        "--launch-console",
        "--config", $ConfigPath
    )
    # Opt-out: IUVE_WIN_NO_WEBVIEW=1 → system browser (loopback ui_web still).
    if (Test-ForceBrowserConsole) {
        $args += "--no-webview"
    }
    Start-Process -FilePath $UiPython -ArgumentList $args -WorkingDirectory $AgentRoot | Out-Null
    Emit-Json '{"ok":true,"adapter":"windows","ui_surface":"native_console","phase":"C.5.1","hint":"WebView2 console via pywebview (fallback: browser). Same ui_web as macOS."}'
    return 0
}

$AgentRoot = Resolve-AgentRoot
$PythonExe = Resolve-PythonExe -AgentRoot $AgentRoot
$ConfigPath = Join-Path $env:USERPROFILE ".config\iuve-connect-agent\desktop-config.json"

switch ($Command) {
    "status" {
        if ($null -eq $PythonExe) {
            Emit-Json '{"ok":false,"error":"python_unavailable","hint":"Install Python 3.10+ or set IUVE_AGENT_PYTHON"}'
            exit 1
        }
        $exitCode = Invoke-AgentModule -PythonExe $PythonExe -AgentRoot $AgentRoot -Args @("status", "--config", $ConfigPath)
        exit $exitCode
    }
    "run" {
        if ($null -eq $PythonExe) {
            Emit-Json '{"ok":false,"error":"python_unavailable"}'
            exit 1
        }
        $exitCode = Invoke-AgentModule -PythonExe $PythonExe -AgentRoot $AgentRoot -Args @("run", "--config", $ConfigPath)
        exit $exitCode
    }
    "pair" {
        if ($null -eq $PythonExe) {
            Emit-Json '{"ok":false,"error":"python_unavailable"}'
            exit 1
        }
        if (-not $env:IUVE_PAIR_TOKEN) {
            Emit-Json '{"ok":false,"error":"pair_token_required","hint":"Set IUVE_PAIR_TOKEN before launcher pair"}'
            exit 2
        }
        $exitCode = Invoke-AgentModule -PythonExe $PythonExe -AgentRoot $AgentRoot -Args @(
            "pair", "--config", $ConfigPath, "--pair-token", $env:IUVE_PAIR_TOKEN
        )
        exit $exitCode
    }
    "console" {
        if ($null -eq $PythonExe) {
            Emit-Json '{"ok":false,"error":"python_unavailable","ui_surface":"native_console"}'
            exit 1
        }
        if (-not (Test-NativeConsoleEnabled)) {
            Open-IuveConnectWeb
            Emit-Json '{"ok":true,"adapter":"windows","ui_surface":"web_connect","hint":"IUVE_WIN_NATIVE_CONSOLE=0 — opened Connect web."}'
            exit 0
        }
        exit (Open-NativeConsole -AgentRoot $AgentRoot -PythonExe $PythonExe -ConfigPath $ConfigPath)
    }
    "dry-run" {
        $hasBundled = Test-Path (Join-Path $AgentRoot "runtime/python/python.exe")
        Emit-Json ('{"ok":true,"adapter":"windows","mode":"active_runtime_wiring","python_required":false,"bundled_python":' + ($(if ($hasBundled) { 'true' } else { 'false' })) + ',"ui_surface":"native_console","phase":"C.5.1","capabilities":["status","run","pair","dry-run","start","stop","console"]}')
        exit 0
    }
    "start" {
        $BackgroundPython = Resolve-BackgroundPythonExe -AgentRoot $AgentRoot
        if ($null -eq $BackgroundPython) {
            Emit-Json '{"ok":false,"error":"python_unavailable"}'
            exit 1
        }
        $env:PYTHONPATH = "$(Join-Path $AgentRoot 'vendor');$AgentRoot"
        Start-Process -FilePath $BackgroundPython -ArgumentList @(
            "-m", "iuve_connect_agents.desktop.app", "run", "--config", $ConfigPath
        ) -WorkingDirectory $AgentRoot -WindowStyle Hidden | Out-Null
        if (-not (Test-NativeConsoleEnabled)) {
            Open-IuveConnectWeb
            Emit-Json '{"ok":true,"adapter":"windows","started":true,"mode":"background_run","ui_surface":"web_connect"}'
            exit 0
        }
        if ($null -eq $PythonExe) {
            $PythonExe = Resolve-PythonExe -AgentRoot $AgentRoot
        }
        if ($null -eq $PythonExe) {
            Emit-Json '{"ok":true,"adapter":"windows","started":true,"mode":"background_run","ui_surface":"native_console","hint":"Agent started; console python unavailable"}'
            exit 0
        }
        exit (Open-NativeConsole -AgentRoot $AgentRoot -PythonExe $PythonExe -ConfigPath $ConfigPath)
    }
    "stop" {
        Get-Process python*, pythonw* -ErrorAction SilentlyContinue |
            Where-Object { $_.Path -like "*$AgentRoot*" -or $_.CommandLine -like "*iuve_connect_agents.desktop.app*" -or $_.CommandLine -like "*ui_bridge*" } |
            Stop-Process -Force -ErrorAction SilentlyContinue
        Emit-Json '{"ok":true,"adapter":"windows","stopped":true,"note":"best_effort_process_stop"}'
        exit 0
    }
    default {
        Emit-Json '{"ok":false,"error":"unsupported_command","allowed":["status","run","pair","start","stop","dry-run","console"]}'
        exit 2
    }
}
