from __future__ import annotations

import json
import subprocess
from pathlib import Path


def ps_single(value: str) -> str:
    return "'" + value.replace("'", "''") + "'"


def main() -> None:
    root = Path.cwd()
    cases_path = root / "scripts" / "order_status_flow_cases.json"
    cases = json.loads(cases_path.read_text(encoding="utf-8"))

    temp_path = root / "runtime" / "order_status_flow_cases_for_sheet.json"
    temp_path.parent.mkdir(parents=True, exist_ok=True)
    temp_path.write_text(json.dumps(cases, ensure_ascii=False, indent=2), encoding="utf-8-sig")

    ps_script = rf"""
$ErrorActionPreference = "Stop"
$WorkbookPath = Get-ChildItem -Path (Get-Location) -Filter "*.xlsx" |
    Where-Object {{ $_.Name -like "SaaS_E2E*" -and $_.Name -notlike "*副本*" }} |
    Sort-Object LastWriteTime -Descending |
    Select-Object -First 1 -ExpandProperty FullName
if (-not $WorkbookPath) {{ throw "Workbook not found." }}

$CasesPath = {ps_single(str(temp_path))}
$Cases = Get-Content -LiteralPath $CasesPath -Raw -Encoding UTF8 | ConvertFrom-Json
$SheetName = "订单状态流转"
$Excel = $null
$Workbook = $null

try {{
    $Excel = New-Object -ComObject Excel.Application
    $Excel.Visible = $false
    $Excel.DisplayAlerts = $false
    $Workbook = $Excel.Workbooks.Open($WorkbookPath)
    if ($Workbook.ReadOnly) {{
        throw "Workbook is read-only. Please close it in Excel and retry: $WorkbookPath"
    }}

    $ListSheet = $Workbook.Worksheets.Item("用例测试列表")
    $StatusSheet = $null
    foreach ($Ws in $Workbook.Worksheets) {{
        if ($Ws.Name -eq $SheetName) {{ $StatusSheet = $Ws }}
    }}
    if ($StatusSheet -ne $null) {{
        $StatusSheet.Delete() | Out-Null
    }}
    $StatusSheet = $Workbook.Worksheets.Add([System.Type]::Missing, $ListSheet)
    $StatusSheet.Name = $SheetName
    $ListSheet.Rows.Item(1).Copy()
    $StatusSheet.Rows.Item(1).PasteSpecial(-4104) | Out-Null
    $StatusSheet.Rows.Item(1).PasteSpecial(-4122) | Out-Null

    # Clear old status rows in the source list sheet so status-flow cases are no longer mixed into the main list.
    $UsedList = $ListSheet.UsedRange
    for ($Row = $UsedList.Rows.Count; $Row -ge 2; $Row--) {{
        $CaseId = ([string]$ListSheet.Cells.Item($Row, 1).Text).Trim()
        if ($CaseId -like "S-FLOW-*") {{
            $ListSheet.Rows.Item($Row).Delete() | Out-Null
        }}
    }}

    $UsedList = $ListSheet.UsedRange
    $Headers = @{{}}
    for ($Column = 1; $Column -le $UsedList.Columns.Count; $Column++) {{
        $Header = [string]$ListSheet.Cells.Item(1, $Column).Text
        if ($Header) {{
            $Headers[$Header] = $Column
            $StatusSheet.Cells.Item(1, $Column).Value2 = $Header
            $ListSheet.Cells.Item(1, $Column).Copy()
            $StatusSheet.Cells.Item(1, $Column).PasteSpecial(-4122) | Out-Null
        }}
    }}

    $Row = 2
    foreach ($Case in $Cases) {{
        foreach ($Header in $Headers.Keys) {{
            if ($Case.PSObject.Properties.Name -contains $Header) {{
                $Cell = $StatusSheet.Cells.Item($Row, $Headers[$Header])
                $Cell.Value2 = [string]$Case.$Header
                $Cell.WrapText = $true
                $Cell.VerticalAlignment = -4160
            }}
        }}
        $StatusSheet.Rows.Item($Row).Interior.Pattern = -4142
        $StatusSheet.Rows.Item($Row).AutoFit() | Out-Null
        $Row++
    }}

    $LastRow = [Math]::Max(1, $Cases.Count + 1)
    $LastColumn = $UsedList.Columns.Count
    $Range = $StatusSheet.Range($StatusSheet.Cells.Item(1, 1), $StatusSheet.Cells.Item($LastRow, $LastColumn))
    $Range.Borders.LineStyle = 1
    $Range.Borders.Weight = 2

    $StatusSheet.Activate()
    $Excel.ActiveWindow.SplitRow = 1
    $Excel.ActiveWindow.FreezePanes = $true
    $StatusSheet.Columns.AutoFit() | Out-Null
    if ($Headers.ContainsKey("执行步骤")) {{
        $StatusSheet.Columns.Item($Headers["执行步骤"]).ColumnWidth = 55
    }}
    if ($Headers.ContainsKey("预期结果")) {{
        $StatusSheet.Columns.Item($Headers["预期结果"]).ColumnWidth = 45
    }}
    if ($Headers.ContainsKey("跨端/状态断言")) {{
        $StatusSheet.Columns.Item($Headers["跨端/状态断言"]).ColumnWidth = 45
    }}
    for ($R = 2; $R -le $LastRow; $R++) {{
        $StatusSheet.Rows.Item($R).AutoFit() | Out-Null
    }}

    $Workbook.Save()
    Write-Host "Updated dedicated order status sheet: $($Cases.Count)"
}}
finally {{
    if ($Workbook -ne $null) {{
        $Workbook.Close($false)
        [System.Runtime.InteropServices.Marshal]::ReleaseComObject($Workbook) | Out-Null
    }}
    if ($Excel -ne $null) {{
        $Excel.Quit()
        [System.Runtime.InteropServices.Marshal]::ReleaseComObject($Excel) | Out-Null
    }}
    [GC]::Collect()
    [GC]::WaitForPendingFinalizers()
}}
"""

    result = subprocess.run(
        [
            r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe",
            "-NoProfile",
            "-ExecutionPolicy",
            "Bypass",
            "-Command",
            ps_script,
        ],
        cwd=root,
        text=True,
        capture_output=True,
        encoding="utf-8",
        errors="replace",
    )
    print(result.stdout)
    if result.returncode != 0:
        print(result.stderr)
        raise SystemExit(result.returncode)


if __name__ == "__main__":
    main()
