# 批量给 fs-admin-saas 的独立模块控制器添加 @Profile("admin")
$saasRoot = "d:\ylrz\ylrz_saas_his_scrm\fs-admin-saas\src\main\java\com\fs"

# 需要添加 @Profile("admin") 的模块（com.fs.X.controller 或 com.fs.X 直接包含控制器）
$modules = @("his","course","crm","qw","live","chat","hisStore","fastGpt","newAdv","ad","billing","user","stats","tenant")

$modifiedCount = 0
$skippedCount = 0

foreach ($m in $modules) {
    $ctrlPath = "$saasRoot\$m\controller"
    if (-not (Test-Path $ctrlPath)) {
        # 有些模块没有 controller 子目录，控制器直接在模块包下
        $ctrlPath = "$saasRoot\$m"
    }
    if (-not (Test-Path $ctrlPath)) { continue }

    Get-ChildItem $ctrlPath -Recurse -Filter "*Controller.java" -ErrorAction SilentlyContinue | ForEach-Object {
        $file = $_.FullName
        $content = Get-Content $file -Raw -Encoding UTF8
        
        # 已经有 @Profile 的跳过
        if ($content -match '@Profile\(') {
            $skippedCount++
            return
        }
        
        # 检查是否有 @RestController 或 @Controller
        if ($content -notmatch '@RestController' -and $content -notmatch '@Controller') {
            return
        }
        
        # 在 @RestController 或 @Controller 前面添加 @Profile("admin")
        # 同时确保 import org.springframework.context.annotation.Profile; 存在
        
        # 添加 import
        if ($content -notmatch 'import org\.springframework\.context\.annotation\.Profile;') {
            # 找到最后一个 import 行后添加
            $content = $content -replace "(import\s+[^;]+;\r?\n)(?!import)", "`$1import org.springframework.context.annotation.Profile;`n"
        }
        
        # 在 @RestController 或 @Controller 前添加 @Profile("admin")
        $content = $content -replace '(@RestController)', '@Profile("admin")`n`$1'
        $content = $content -replace '(@Controller)', '@Profile("admin")`n`$1'
        
        # 修正反引号 - PowerShell 的 -replace 使用 $1 而不是 \1
        # 重新处理
    }
}

# 上面的替换在 PowerShell 中有问题，改用更可靠的方式
$modifiedCount = 0
$skippedCount = 0

foreach ($m in $modules) {
    $ctrlPath = "$saasRoot\$m\controller"
    if (-not (Test-Path $ctrlPath)) {
        $ctrlPath = "$saasRoot\$m"
    }
    if (-not (Test-Path $ctrlPath)) { continue }

    Get-ChildItem $ctrlPath -Recurse -Filter "*Controller.java" -ErrorAction SilentlyContinue | ForEach-Object {
        $file = $_.FullName
        $lines = Get-Content $file -Encoding UTF8
        
        # 已经有 @Profile 的跳过
        $hasProfile = $false
        foreach ($line in $lines) {
            if ($line -match '@Profile\(') { $hasProfile = $true; break }
        }
        if ($hasProfile) { $skippedCount++; return }
        
        # 检查是否有 @RestController 或 @Controller
        $hasController = $false
        foreach ($line in $lines) {
            if ($line -match '@RestController|@Controller') { $hasController = $true; break }
        }
        if (-not $hasController) { return }
        
        $newLines = @()
        $importAdded = $false
        $profileAdded = $false
        
        foreach ($line in $lines) {
            # 添加 import Profile
            if (-not $importAdded -and $line -match '^import ' -and $line -notmatch '^import org\.springframework\.context\.annotation\.Profile;') {
                # 检查是否是最后一个 import
                $nextIdx = [array]::IndexOf($lines, $line) + 1
                if ($nextIdx -lt $lines.Count -and $lines[$nextIdx] -notmatch '^import ') {
                    $newLines += $line
                    $newLines += "import org.springframework.context.annotation.Profile;"
                    $importAdded = $true
                } else {
                    $newLines += $line
                }
            }
            # 在 @RestController 或 @Controller 前添加 @Profile("admin")
            elseif (-not $profileAdded -and ($line -match '^\s*@RestController' -or $line -match '^\s*@Controller\s')) {
                $newLines += '@Profile("admin")'
                $newLines += $line
                $profileAdded = $true
            }
            else {
                $newLines += $line
            }
        }
        
        # 如果 import 没添加（所有 import 都连续），在第一个 import 块末尾添加
        if (-not $importAdded -and $profileAdded) {
            $idx = 0
            for ($i = $newLines.Count - 1; $i -ge 0; $i--) {
                if ($newLines[$i] -match '^import ') {
                    $idx = $i
                    break
                }
            }
            if ($idx -gt 0) {
                $before = $newLines[0..$idx]
                $after = $newLines[($idx+1)..($newLines.Count-1)]
                $newLines = $before + "import org.springframework.context.annotation.Profile;" + $after
                $importAdded = $true
            }
        }
        
        if ($profileAdded) {
            Set-Content $file $newLines -Encoding UTF8
            $modifiedCount++
        }
    }
}

"Modified: $modifiedCount controllers, Skipped (already has @Profile): $skippedCount"
