# Synopsis: Launches the AgentOSH dynamic browser interface securely and bypasses local caches.
# Description: Boots the browser interface with a fresh local profile while avoiding host-specific executable paths.

$BaseDir = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent

$EdgeCandidates = @()
$EdgeCommand = Get-Command "msedge.exe" -ErrorAction SilentlyContinue
if ($EdgeCommand) { $EdgeCandidates += $EdgeCommand.Source }
if ($env:ProgramFiles) { $EdgeCandidates += (Join-Path $env:ProgramFiles "Microsoft\Edge\Application\msedge.exe") }
if (${env:ProgramFiles(x86)}) { $EdgeCandidates += (Join-Path ${env:ProgramFiles(x86)} "Microsoft\Edge\Application\msedge.exe") }
$EdgePath = $EdgeCandidates | Where-Object { $_ -and (Test-Path $_) } | Select-Object -First 1

# Generate a completely unique, timestamped User Data Directory to bypass browser caching of old HTML/JS assets
$Timestamp = (Get-Date).ToString("yyyyMMddHHmmss")
$UserDataDir = Join-Path $env:TEMP "EdgeInsecureAgentOSH_$Timestamp"
$HtmlPath = Join-Path $BaseDir "Scripts\AgentOSH_Chat.html"

if ($EdgePath) {
    if (Test-Path $HtmlPath) {
        # Convert path schema to file:/// canonical with proper forward slashes
        $FullPath = (Get-Item $HtmlPath).FullName.Replace("\", "/")
        $UriPath = "file:///$FullPath"
        
        Write-Output "SYSTEM: Initializing AgentOSH Launch Sequence..."
        Write-Output "PROFILE: Using unique, uncached directory profile at: $UserDataDir"
        
        # Deploy browser with file access enabled so the static page can read local package config.
        Start-Process -FilePath $EdgePath -ArgumentList `
            "--disable-web-security", `
            "--allow-file-access-from-files", `
            "--user-data-dir=`"$UserDataDir`"", `
            "--no-first-run", `
            "--no-default-browser-check", `
            "--new-window", `
            "`"$UriPath`""
        
        Write-Output "SUCCESS: AgentOSH browser window initialized with local config access."
    } else {
        Write-Output "ERROR: AgentOSH_Chat.html not found at $HtmlPath"
    }
} else {
    Write-Output "ERROR: Microsoft Edge executable not found via PATH or Program Files."
}
