$ErrorActionPreference = 'Stop'

$Workspace = 'C:\Users\user\Documents\New project'
$BaseSet = Join-Path $Workspace 'KOUCHA_GOLD_BASKET_CLOSE_PROFIT_COMPARE\P0_A2_BASE_D4_M1_20260501_20260529\P0_A2_BASE_D4_M1_20260501_20260529.set'
$BaseIni = Join-Path $Workspace 'KOUCHA_GOLD_BASKET_CLOSE_PROFIT_COMPARE\P0_A2_BASE_D4_M1_20260501_20260529\P0_A2_BASE_D4_M1_20260501_20260529.ini'
$OutRoot = Join-Path $Workspace 'KOUCHA_GOLD_GLOBAL_MARKET_CLOSED_RETRY_COMPARE'

if (!(Test-Path -LiteralPath $BaseSet)) { throw "Base set not found: $BaseSet" }
if (!(Test-Path -LiteralPath $BaseIni)) { throw "Base ini not found: $BaseIni" }

New-Item -ItemType Directory -Force -Path $OutRoot | Out-Null

function Set-InputValue {
    param([string[]]$Lines, [string]$Key, [string]$Value)
    $found = $false
    $out = foreach ($line in $Lines) {
        if ($line -match ('^' + [regex]::Escape($Key) + '=')) {
            $found = $true
            if ($line -like '*||*') {
                $parts = $line -split '\|\|', 2
                "$Key=$Value||$($parts[1])"
            } else {
                "$Key=$Value"
            }
        } else {
            $line
        }
    }
    if (!$found) { $out += "$Key=$Value" }
    return $out
}

function Write-TestFiles {
    param(
        [string]$Pattern,
        [hashtable]$Overrides
    )
    $testName = "${Pattern}_M1_20260501_20260529"
    $testDir = Join-Path $OutRoot $testName
    New-Item -ItemType Directory -Force -Path $testDir | Out-Null
    $setPath = Join-Path $testDir "$testName.set"
    $iniPath = Join-Path $testDir "$testName.ini"

    $setLines = @(Get-Content -LiteralPath $BaseSet -Encoding Unicode)

    $standard = @{
        BacktestPatternName = $Pattern
        UseBacktestFastCompareMode = 'true'
        UseBacktestDiagnosticMode = 'false'
        UseDxyVixOnlyCache = 'true'
        DxyVixOnlyCacheSeconds = '5'
        UsePerformanceCache = 'false'
        DisableMaGoldTechnicalCacheForSafety = 'true'
        KeepEntryCriticalFiltersTickExact = 'true'
        EnableEntryDecisionTrace = 'false'
        EnableReactiveHedgeEligibilityTrace = 'false'
        EnableRejectedEntryDetailLog = 'false'
        EnableShadowEntryCandidateLog = 'false'
        EnableTickLevelTraceLog = 'false'
        EnableHeavyPrintLog = 'false'
        UseBacktestLightLogMode = 'true'
        AuditSummaryOnlyMode = 'true'
        AuditSummaryIntervalMinutes = '240'

        UsePostDefenseHedgeExitControl = 'false'
        UsePostHedgeSelectiveExitOnly = 'false'
        UseSinglePositionContraryEarlyExit = 'false'
        UseHardStopOriginEntryBlock = 'false'
        UseSinglePositionReactiveDefenseHedge = 'false'
        UsePostHedgeMarketClosedRetry = 'false'

        GlobalMarketClosedRetrySeconds = '60'
        GlobalMarketClosedMaxRetryMinutes = '720'
        BlockNewEntryWhileCloseRetryPending = 'true'
        RetryHardStopClose = 'true'
        RetryBasketClose = 'true'
        RetryBasketRecoveryClose = 'true'
        RetryBasketRecoveryLossCutClose = 'true'
        RetryHedgedBasketTimeExitClose = 'true'
        RetryDefenseHedgeExitClose = 'true'
        RetryManualForceClose = 'true'
    }
    foreach ($k in $standard.Keys) {
        $setLines = @(Set-InputValue -Lines $setLines -Key $k -Value $standard[$k])
    }
    foreach ($k in $Overrides.Keys) {
        $setLines = @(Set-InputValue -Lines $setLines -Key $k -Value $Overrides[$k])
    }
    Set-Content -LiteralPath $setPath -Value $setLines -Encoding Unicode

    $iniLines = @(Get-Content -LiteralPath $BaseIni -Encoding Unicode)
    $iniLines = $iniLines | ForEach-Object {
        if ($_ -match '^FromDate=') { 'FromDate=2026.05.01' }
        elseif ($_ -match '^ToDate=') { 'ToDate=2026.05.29' }
        elseif ($_ -match '^Deposit=') { 'Deposit=50000' }
        elseif ($_ -match '^Currency=') { 'Currency=JPY' }
        elseif ($_ -match '^Leverage=') { 'Leverage=1:888' }
        elseif ($_ -match '^Symbol=') { 'Symbol=GOLD' }
        elseif ($_ -match '^Period=') { 'Period=M5' }
        elseif ($_ -match '^Model=') { 'Model=0' }
        else { $_ }
    }
    $idx = [Array]::IndexOf($iniLines, '[TesterInputs]')
    if ($idx -lt 0) { throw "TesterInputs section not found in $BaseIni" }
    $head = @($iniLines[0..$idx])
    $head + $setLines | Set-Content -LiteralPath $iniPath -Encoding Unicode

    [pscustomobject]@{
        TestName = $testName
        Pattern = $Pattern
        Segment = 'M1_20260501_20260529'
        FromDate = '2026.05.01'
        ToDate = '2026.05.29'
        Set = $setPath
        Ini = $iniPath
    }
}

$tests = @()
$tests += Write-TestFiles -Pattern 'R0_P0_BASE' -Overrides @{
    UseGlobalMarketClosedRetry = 'false'
}
$tests += Write-TestFiles -Pattern 'R1_GlobalMarketClosedRetryOnly' -Overrides @{
    UseGlobalMarketClosedRetry = 'true'
}

$manifest = Join-Path $OutRoot 'test_manifest.csv'
$tests | Export-Csv -LiteralPath $manifest -NoTypeInformation -Encoding UTF8
Copy-Item -LiteralPath (Join-Path $Workspace 'KOUCHA_GOLD_KIWAMI_SURVIVAL_TICK.mq5') -Destination (Join-Path $OutRoot 'KOUCHA_GOLD_KIWAMI_SURVIVAL_TICK.mq5') -Force
Copy-Item -LiteralPath (Join-Path $Workspace 'compile_global_market_retry_from_metaeditor.log') -Destination (Join-Path $OutRoot 'compile_result.txt') -Force -ErrorAction SilentlyContinue
Write-Host "Created global market closed retry test files: $manifest"
