$location = Get-Location
$path = $location.Path

Write-Host "current location: $location"

$cssSourcePath = [System.IO.Path]::Combine($path,"Views","Shared","_IncludeCssFilePartial.cshtml");
if([System.IO.File]::Exists($cssSourcePath) -eq $false)
{
    Write-Host "CssSourcePath: $cssSourcePath does not exist" -ForegroundColor Red
    return;
}


$cssSourceContent = Get-Content -Path $cssSourcePath

$regex = '(?s)<environment include="Development">.*?</environment>'
$match = [regex]::Match($cssSourceContent, $regex)

if($match.Success -eq $false)
{
    Write-Host "Regex match failed" -ForegroundColor Red
}

# 获取匹配的内容
$devSection = $match.Groups[0].Value

# 提取所有 href 的值
$hrefRegex = 'href="([^"]+)"'
$hrefMatches = [regex]::Matches($devSection, $hrefRegex)

$actualPaths = @()
foreach ($hrefMatch in $hrefMatches) 
{
    # 获取原始 href 值
    $fullHref = $hrefMatch.Groups[1].Value
    
    # 移除查询字符串 (? 及其后面的部分)
    $cleanHref = $fullHref -replace '\?.*$', ''
    
   
    $cssPath = $cleanHref.TrimStart('~','/').Split('/')
    $actualPath = Join-Path $path 'wwwroot'
    foreach ($seg in $cssPath) 
    { 
        $actualPath = Join-Path $actualPath $seg 
    }
    
    if(-not (Test-Path $actualPath -PathType Leaf)) {
        Write-Host "$actualPath not exists" -ForegroundColor Red
        continue
    }
    
    $actualPaths += $actualPath
    
    #Write-Output $actualPath
}

Write-Host "--------------------------------" -ForegroundColor yellow
Write-Host "Merge global style" -ForegroundColor yellow
Write-Host "--------------------------------" -ForegroundColor yellow

$inputParameters = [System.String]::Join(" ",$actualPaths)
$outputPath = [System.IO.Path]::Combine($path,'wwwroot','css','global.min.css')
$execute = "cleancss -o $outputPath $inputParameters --with-rebase --debug"
Invoke-Expression $execute


$memberFiles = @()
$memberFiles += [System.IO.Path]::Combine($path,'wwwroot','css','member','member.css')
$memberFiles += [System.IO.Path]::Combine($path,'wwwroot','css','member','dark-mode.css')
$memberInputParameters = [System.String]::Join(" ",$memberFiles)
$memberOutputPath = [System.IO.Path]::Combine($path,'wwwroot','css','member','member.min.css')
$memberExecute = "cleancss -o $memberOutputPath $memberInputParameters --with-rebase --debug"
Invoke-Expression $memberExecute


$aiChatSourceFile = [System.IO.Path]::Combine($path,'wwwroot','css','chat.css')
$aiChatOutputFile = [System.IO.Path]::Combine($path,'wwwroot','css','chat.min.css')
$aiChatExecute = "cleancss -o $aiChatOutputFile $aiChatSourceFile --with-rebase --debug"
Invoke-Expression $aiChatExecute


Write-Host "--------------------------------" -ForegroundColor yellow
Write-Host "build javascript  files" -ForegroundColor yellow
Write-Host "--------------------------------" -ForegroundColor yellow

node ./esbuild/esbuild.config.js

node ./esbuild/member.esbuild.config.js

node ./esbuild/ai-chat.esbuild.config.js

Write-Host "--------------------------------" -ForegroundColor yellow
Write-Host "Hash files and generate manifest" -ForegroundColor yellow
Write-Host "--------------------------------" -ForegroundColor yellow

function Hash-And-Rename {
    param (
        [string]$FilePath,
        [string]$WebRootPath,
        [hashtable]$Manifest
    )

    if (Test-Path $FilePath) {
        $hash = Get-FileHash $FilePath -Algorithm MD5
        $hashString = $hash.Hash.Substring(0, 8).ToLower()
        
        $extension = [System.IO.Path]::GetExtension($FilePath)
        $directory = [System.IO.Path]::GetDirectoryName($FilePath)
        $fileNameWithoutExt = [System.IO.Path]::GetFileNameWithoutExtension($FilePath)
        
        # New filename: name.hash.ext
        $newFileName = "$fileNameWithoutExt.$hashString$extension"
        $newFilePath = Join-Path $directory $newFileName
        
        # 删除旧的哈希文件
        # pattern: name.*.ext (specifically looking for 8 char hash)
        $pattern = "^" + [regex]::Escape($fileNameWithoutExt) + "\.[a-f0-9]{8}" + [regex]::Escape($extension) + "$"
        
        Get-ChildItem -Path $directory -File | Where-Object { $_.Name -match $pattern } | ForEach-Object {
            Remove-Item $_.FullName -Force
            Write-Host "Deleted old file: $($_.Name)" -ForegroundColor DarkGray
        }
        
        Copy-Item $FilePath $newFilePath -Force
        
        # Relative paths for manifest
        $relativePath = $FilePath.Substring($WebRootPath.Length).TrimStart('\', '/')
        $relativeNewPath = $newFilePath.Substring($WebRootPath.Length).TrimStart('\', '/')
        
        # Normalize to forward slashes for JSON
        $relativePath = $relativePath -replace '\\', '/'
        $relativeNewPath = $relativeNewPath -replace '\\', '/'
        
        $Manifest[$relativePath] = $relativeNewPath
        
        Write-Host "Hashed: $relativePath -> $relativeNewPath" -ForegroundColor Cyan
    } else {
        Write-Host "File not found: $FilePath" -ForegroundColor Red
    }
}

$manifest = @{}
$webRoot = Join-Path $path 'wwwroot'

# Define files to process
$filesToHash = @(
    "css/global.min.css",
    "css/member/member.min.css",
    "css/chat.min.css",
    "css/markdown.css",
    "js/app.min.js",
    "js/member/main.min.js",
    "js/ai-chat/main.min.js"
)

foreach ($file in $filesToHash) {
    $fullPath = Join-Path $webRoot $file
    Hash-And-Rename -FilePath $fullPath -WebRootPath $webRoot -Manifest $manifest
}

# Write manifest
$manifestJson = $manifest | ConvertTo-Json
$manifestPath = Join-Path $webRoot "assets-manifest.json"
Set-Content -Path $manifestPath -Value $manifestJson
评论加载中...