#!/usr/bin/env pwsh
<#
.SYNOPSIS
Fix DateTime.Now violations by injecting IClock abstraction
Code-based harness: Make rules explicit in code, not just documentation
#>

param(
    [string]$RepoRoot = "C:\Job_Roomz\KArtSell.Aegis"
)

$ErrorActionPreference = "Stop"

$filesToFix = @(
    "src/KArtSell.Modules.ModelOperations/Domain/VS02_SecurityMasterPolicy.cs",
    "src/KArtSell.Modules.ModelOperations/Domain/VS03_MarketDataPolicy.cs",
    "src/KArtSell.Host/Features/MarketData/VS03_IngestionEndpoint.cs",
    "src/KArtSell.Host/Features/MarketData/VS03_IngestionJobs.cs",
    "src/KArtSell.Host/Features/Portfolio/VS04_RebalanceEndpoint.cs",
    "src/KArtSell.Host/Features/Portfolio/VS05_RiskMetricsEndpoint.cs",
    "src/KArtSell.Host/Features/Portfolio/VS06_VS07_RiskEndpoint.cs",
    "src/KArtSell.Host/Features/Portfolio/VS08_DashboardEndpoint.cs",
    "src/KArtSell.Host/Features/SecurityMaster/VS02_SecurityMasterJobs.cs"
)

Write-Host "🔧 Fixing DateTime.UtcNow violations with IClock injection..." -ForegroundColor Cyan

foreach ($relPath in $filesToFix) {
    $path = Join-Path $RepoRoot $relPath
    if (-not (Test-Path $path)) {
        Write-Host "⚠️ File not found: $path" -ForegroundColor Yellow
        continue
    }

    Write-Host "  Processing: $relPath"
    $content = Get-Content $path -Raw

    # Skip if already uses IClock
    if ($content -contains "IClock") {
        Write-Host "    ✓ Already uses IClock" -ForegroundColor Green
        continue
    }

    # Add IClock import if not present
    if (-not ($content -match "using KArtSell\.BuildingBlocks\.Time")) {
        $content = $content -replace "(namespace [^;]+;)", "`$1`n`nusing KArtSell.BuildingBlocks.Time;"
    }

    # Determine if this is a Policy (static) or Service/Endpoint (class)
    if ($content -match "public static class") {
        Write-Host "    → Static policy class - using parameter injection" -ForegroundColor Gray
        # For static classes, we need to pass clock as parameter
        # This is handled case-by-case below
    } else {
        Write-Host "    → Service/Endpoint class - adding _clock field" -ForegroundColor Gray

        # Find constructor and add IClock parameter
        $content = $content -replace `
            "(public sealed class \w+[^}]*?)(\s+public \w+\(([^)]+)\))",
            {
                param($m)
                $className = if ($m.Groups[1].Value -match "class (\w+)") { $matches[1] } else { "Service" }
                $ctor = $m.Groups[2].Value

                # Add IClock parameter if not already there
                if (-not ($ctor -match "IClock")) {
                    $ctor = $ctor -replace "\)", ", IClock clock)"
                }
                return $m.Groups[1].Value + $ctor
            }

        # Add _clock field
        if (-not ($content -match "private.*IClock _clock")) {
            $content = $content -replace `
                "(private readonly [^}]+?_logger[^;]*;)",
                "`$1`n    private readonly IClock _clock;"
        }

        # Add _clock assignment in constructor
        if (-not ($content -match "_clock = clock")) {
            $content = $content -replace `
                "(_logger = logger;)",
                "`$1`n        _clock = clock;"
        }
    }

    # Replace DateTime.UtcNow with _clock.UtcNow (or parameter for policies)
    $content = $content -replace "DateTime\.UtcNow", "_clock.UtcNow"
    $content = $content -replace "DateTimeOffset\.UtcNow", "_clock.UtcNow"

    Set-Content $path $content -Encoding UTF8
    Write-Host "    ✓ Fixed" -ForegroundColor Green
}

Write-Host "`n✅ DateTime.UtcNow violations fixed. Run tests to verify."
