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

# Legacy compatibility helper only.
# Active SDT workflows and shell bootstrap now use Python scripts.

function Clear-SdtProxyEnv {
    Remove-Item Env:HTTP_PROXY -ErrorAction SilentlyContinue
    Remove-Item Env:HTTPS_PROXY -ErrorAction SilentlyContinue
    Remove-Item Env:ALL_PROXY -ErrorAction SilentlyContinue
    Remove-Item Env:http_proxy -ErrorAction SilentlyContinue
    Remove-Item Env:https_proxy -ErrorAction SilentlyContinue
    Remove-Item Env:all_proxy -ErrorAction SilentlyContinue
    Remove-Item Env:GIT_HTTP_PROXY -ErrorAction SilentlyContinue
    Remove-Item Env:GIT_HTTPS_PROXY -ErrorAction SilentlyContinue
    Remove-Item Env:PIP_NO_INDEX -ErrorAction SilentlyContinue
}

function Resolve-SdtRepoRoot {
    param([string]$StartPath)

    $candidateStarts = @()
    if (-not [string]::IsNullOrWhiteSpace($StartPath)) {
        $candidateStarts += $StartPath
    }
    $cwd = (Get-Location).Path
    if (-not [string]::IsNullOrWhiteSpace($cwd) -and ($candidateStarts -notcontains $cwd)) {
        $candidateStarts += $cwd
    }

    $override = $env:SDT_REPO_ROOT
    if ([string]::IsNullOrWhiteSpace($override)) {
        $override = $env:JOURNAL_REPO_ROOT # backward compatibility
    }
    if (-not [string]::IsNullOrWhiteSpace($override)) {
        $overridePath = [System.IO.Path]::GetFullPath($override)
        if (Test-Path (Join-Path $overridePath "devtool.json")) {
            return $overridePath
        }
    }

    foreach ($start in $candidateStarts) {
        $cursor = [System.IO.Path]::GetFullPath($start)
        while (-not [string]::IsNullOrWhiteSpace($cursor)) {
            if (Test-Path (Join-Path $cursor "devtool.json")) {
                return $cursor
            }
            $parent = [System.IO.Directory]::GetParent($cursor)
            if ($null -eq $parent -or $parent.FullName -eq $cursor) {
                break
            }
            $cursor = $parent.FullName
        }
    }

    if (Get-Command git -ErrorAction SilentlyContinue) {
        foreach ($start in $candidateStarts) {
            try {
                $gitRoot = & git -C $start rev-parse --show-toplevel 2>$null
                if ($? -and -not [string]::IsNullOrWhiteSpace($gitRoot)) {
                    return [System.IO.Path]::GetFullPath($gitRoot.Trim())
                }
            }
            catch {}
        }
    }

    throw "Could not locate repository root. Ensure a devtool.json exists in the project root."
}

function Initialize-SdtDotnetEnv {
    param([Parameter(Mandatory = $true)][string]$RepoRoot)

    $dotnetCliHome = Join-Path $RepoRoot ".dotnet_home"
    $nugetPackages = Join-Path $RepoRoot ".nuget\packages"
    $nugetHttpCachePath = Join-Path $RepoRoot ".nuget\http-cache"

    $env:DOTNET_CLI_HOME = $dotnetCliHome
    $env:NUGET_PACKAGES = $nugetPackages
    $env:NUGET_HTTP_CACHE_PATH = $nugetHttpCachePath
    $env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE = "1"
    $env:DOTNET_ADD_GLOBAL_TOOLS_TO_PATH = "0"
    $env:DOTNET_GENERATE_ASPNET_CERTIFICATE = "0"
    $env:DOTNET_CLI_TELEMETRY_OPTOUT = "1"
    $env:NUGET_CERT_REVOCATION_MODE = "offline"

    New-Item -ItemType Directory -Force -Path $dotnetCliHome, $nugetPackages, $nugetHttpCachePath | Out-Null
}

function Initialize-SdtPipEnv {
    param([Parameter(Mandatory = $true)][string]$RepoRoot)

    $pipCacheDir = Join-Path $RepoRoot ".pip\cache"
    $pipTempDir = Join-Path $RepoRoot ".tmp\pip-temp"

    $env:PIP_CACHE_DIR = $pipCacheDir
    $env:TEMP = $pipTempDir
    $env:TMP = $pipTempDir
    $env:PIP_DISABLE_PIP_VERSION_CHECK = "1"
    $env:PIP_DEFAULT_TIMEOUT = "30"
    $env:PIP_RETRIES = "2"

    New-Item -ItemType Directory -Force -Path $pipCacheDir, $pipTempDir | Out-Null
}

function Initialize-SdtHuggingFaceEnv {
    param([Parameter(Mandatory = $true)][string]$RepoRoot)

    $hfHome = Join-Path $RepoRoot ".cache\huggingface"
    $hfHubCache = Join-Path $hfHome "hub"

    $env:HF_HOME = $hfHome
    $env:HUGGINGFACE_HUB_CACHE = $hfHubCache
    $env:HF_HUB_DISABLE_SYMLINKS_WARNING = "1"

    New-Item -ItemType Directory -Force -Path $hfHubCache | Out-Null
}

# Backward-compatible aliases (legacy script calls)
Set-Alias -Name Clear-JournalProxyEnv -Value Clear-SdtProxyEnv -Scope Script
Set-Alias -Name Resolve-JournalRepoRoot -Value Resolve-SdtRepoRoot -Scope Script
Set-Alias -Name Initialize-JournalDotnetEnv -Value Initialize-SdtDotnetEnv -Scope Script
Set-Alias -Name Initialize-JournalPipEnv -Value Initialize-SdtPipEnv -Scope Script
Set-Alias -Name Initialize-JournalHuggingFaceEnv -Value Initialize-SdtHuggingFaceEnv -Scope Script
