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_excel.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
$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"
    }}
    $Worksheet = $Workbook.Worksheets.Item("用例测试列表")
    $Used = $Worksheet.UsedRange
    $Headers = @{{}}
    for ($Column = 1; $Column -le $Used.Columns.Count; $Column++) {{
        $Header = [string]$Worksheet.Cells.Item(1, $Column).Text
        if ($Header) {{ $Headers[$Header] = $Column }}
    }}
    $CaseIdColumn = $Headers["用例编号"]
    if (-not $CaseIdColumn) {{ throw "Missing 用例编号 column." }}

    $ExistingRows = @{{}}
    $LastStatusRow = 0
    $Used = $Worksheet.UsedRange
    for ($Row = 2; $Row -le $Used.Rows.Count; $Row++) {{
        $CaseId = ([string]$Worksheet.Cells.Item($Row, $CaseIdColumn).Text).Trim()
        if ($CaseId) {{
            $ExistingRows[$CaseId] = $Row
            if ($CaseId -like "S-*") {{ $LastStatusRow = $Row }}
        }}
    }}
    if ($LastStatusRow -eq 0) {{ $LastStatusRow = $Used.Rows.Count }}

    $InsertAt = $LastStatusRow + 1
    foreach ($Case in $Cases) {{
        $CaseId = [string]$Case."用例编号"
        if ($ExistingRows.ContainsKey($CaseId)) {{
            $Row = $ExistingRows[$CaseId]
        }} else {{
            $Worksheet.Rows.Item($InsertAt).Insert() | Out-Null
            $Worksheet.Rows.Item($LastStatusRow).Copy()
            $Worksheet.Rows.Item($InsertAt).PasteSpecial(-4122) | Out-Null
            $Row = $InsertAt
            $ExistingRows[$CaseId] = $Row
            $InsertAt++
            $LastStatusRow = $Row
        }}

        foreach ($Header in $Headers.Keys) {{
            if ($Case.PSObject.Properties.Name -contains $Header) {{
                $Cell = $Worksheet.Cells.Item($Row, $Headers[$Header])
                $Cell.Value2 = [string]$Case.$Header
                $Cell.WrapText = $true
            }}
        }}
        $Worksheet.Rows.Item($Row).AutoFit() | Out-Null
    }}

    $Workbook.Save()
    Write-Host "Updated order status flow cases: $($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()
