<#
.SYNOPSIS
    Automates deployment of NT8 SDK to NinjaTrader 8.

.DESCRIPTION
    Builds, tests, copies DLLs/strategy source files, and verifies deployment.
#>

param(
    [switch]$BuildFirst = $true,
    [switch]$RunTests = $true,
    [switch]$CopyStrategies = $true,
    [switch]$SkipVerification = $false,
    [string]$Configuration = "Release"
)

$ErrorActionPreference = "Stop"

$sdkRoot = "C:\dev\nt8-sdk"
$nt8Custom = "$env:USERPROFILE\Documents\NinjaTrader 8\bin\Custom"
$nt8Strategies = "$nt8Custom\Strategies"

$coreDllPath = "$sdkRoot\src\NT8.Core\bin\$Configuration\net48"
$adaptersDllPath = "$sdkRoot\src\NT8.Adapters\bin\$Configuration\net48"
$strategiesPath = "$sdkRoot\src\NT8.Adapters\Strategies"

function Write-Header {
    param([string]$Message)
    Write-Host ""
    Write-Host ("=" * 70) -ForegroundColor Cyan
    Write-Host $Message -ForegroundColor Cyan
    Write-Host ("=" * 70) -ForegroundColor Cyan
}

function Write-Step {
    param([string]$Step, [string]$Message)
    Write-Host "`n[$Step] $Message" -ForegroundColor Yellow
}

function Write-Success {
    param([string]$Message)
    Write-Host "  [OK] $Message" -ForegroundColor Green
}

function Write-Warn {
    param([string]$Message)
    Write-Host "  [WARN] $Message" -ForegroundColor Yellow
}

if (-not (Test-Path $sdkRoot)) {
    throw "SDK root not found: $sdkRoot"
}

if (-not (Test-Path $nt8Custom)) {
    throw "NinjaTrader 8 Custom directory not found: $nt8Custom"
}

$strategyFiles = @(
    "NT8StrategyBase.cs",
    "SimpleORBNT8.cs",
    "MinimalTestStrategy.cs"
)

Write-Header "NT8 SDK Deployment Script"
Write-Host "Configuration: $Configuration"
Write-Host "SDK Root: $sdkRoot"
Write-Host "NT8 Custom: $nt8Custom"

$startTime = Get-Date

if ($BuildFirst) {
    Write-Step "1/6" "Building SDK"
    Push-Location $sdkRoot
    try {
        & dotnet clean --configuration $Configuration --verbosity quiet
        if ($LASTEXITCODE -ne 0) { throw "Clean failed" }

        & dotnet build --configuration $Configuration --verbosity quiet
        if ($LASTEXITCODE -ne 0) { throw "Build failed" }

        Write-Success "Build succeeded"
    }
    finally {
        Pop-Location
    }
}
else {
    Write-Step "1/6" "Skipping build"
}

if ($RunTests) {
    Write-Step "2/6" "Running tests"
    Push-Location $sdkRoot
    try {
        & dotnet test --configuration $Configuration --no-build --verbosity quiet
        if ($LASTEXITCODE -ne 0) { throw "Tests failed" }
        Write-Success "Tests passed"
    }
    finally {
        Pop-Location
    }
}
else {
    Write-Step "2/6" "Skipping tests"
}

Write-Step "3/6" "Copying SDK DLLs"
if (Test-Path "$coreDllPath\NT8.Core.dll") {
    Copy-Item "$coreDllPath\NT8.Core.dll" $nt8Custom -Force
    Write-Success "Copied NT8.Core.dll"
}
else {
    throw "NT8.Core.dll not found at $coreDllPath"
}

if (Test-Path "$adaptersDllPath\NT8.Adapters.dll") {
    Copy-Item "$adaptersDllPath\NT8.Adapters.dll" $nt8Custom -Force
    Write-Success "Copied NT8.Adapters.dll"
}
else {
    Write-Warn "NT8.Adapters.dll not found (may be expected)"
}

Write-Step "4/6" "Copying dependencies"
$dependencies = @(
    "Microsoft.Extensions.*.dll",
    "System.Memory.dll",
    "System.Buffers.dll",
    "System.Runtime.CompilerServices.Unsafe.dll"
)

$depCopied = 0
foreach ($pattern in $dependencies) {
    $files = Get-ChildItem "$coreDllPath\$pattern" -ErrorAction SilentlyContinue
    foreach ($f in $files) {
        Copy-Item $f.FullName $nt8Custom -Force
        $depCopied++
    }
}

if ($depCopied -gt 0) {
    Write-Success ("Copied {0} dependencies" -f $depCopied)
}
else {
    Write-Warn "No dependency files copied"
}

if ($CopyStrategies) {
    Write-Step "5/6" "Copying strategy files"
    if (-not (Test-Path $nt8Strategies)) {
        New-Item -ItemType Directory -Path $nt8Strategies -Force | Out-Null
    }

    $copied = 0
    foreach ($file in $strategyFiles) {
        $sourcePath = Join-Path $strategiesPath $file
        if (Test-Path $sourcePath) {
            Copy-Item $sourcePath $nt8Strategies -Force
            Write-Success ("Copied {0}" -f $file)
            $copied++
        }
        else {
            Write-Warn ("Missing {0}" -f $file)
        }
    }

    if ($copied -eq 0) {
        throw "No strategy files copied"
    }
}
else {
    Write-Step "5/6" "Skipping strategy copy"
}

if (-not $SkipVerification) {
    Write-Step "6/6" "Verifying deployment"
    $ok = $true

    if (-not (Test-Path "$nt8Custom\NT8.Core.dll")) {
        $ok = $false
        Write-Warn "NT8.Core.dll missing after copy"
    }

    foreach ($file in $strategyFiles) {
        if (-not (Test-Path (Join-Path $nt8Strategies $file))) {
            $ok = $false
            Write-Warn ("{0} missing after copy" -f $file)
        }
    }

    if (-not $ok) {
        throw "Deployment verification failed"
    }

    Write-Success "Deployment verification passed"
}
else {
    Write-Step "6/6" "Skipping verification"
}

$duration = (Get-Date) - $startTime
Write-Header "Deployment Complete"
Write-Host ("Duration: {0:F1} seconds" -f $duration.TotalSeconds)
Write-Host "Next: Open NinjaTrader 8 -> NinjaScript Editor -> Compile All"

exit 0

