# GTMP — بیلد خودکار فورک روی GitHub Actions (ویندوز)
name: Build GTMP Fork (Windows)

on:
  workflow_dispatch:
    inputs:
      build_client:
        description: 'کلاینت بازی هم بیلد شود؟ (کندتر)'
        default: 'no'

jobs:
  build:
    runs-on: windows-latest
    timeout-minutes: 350
    steps:
      - name: Checkout gtmp
        uses: actions/checkout@v4
        with:
          ref: arena/01a03426-starkmp

      - name: Setup Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.11'

      - name: Free disk
        shell: pwsh
        run: |
          Remove-Item -Recurse -Force "C:\Android" -ErrorAction SilentlyContinue
          Get-PSDrive C | Select-Object Used,Free

      - name: Clone + patch + rebrand (make-fork)
        shell: bash
        run: bash server/fork/make-fork.sh

      - name: Install premake5
        shell: pwsh
        run: |
          $url = "https://github.com/premake/premake-core/releases/download/v5.0.0-beta2/premake-5.0.0-beta2-windows.zip"
          Invoke-WebRequest $url -OutFile premake5.zip
          Expand-Archive premake5.zip -DestinationPath C:\premake
          echo "C:\premake" | Out-File -FilePath $env:GITHUB_PATH -Append

      - name: Setup MSYS2 + lua (طبق مستندات رسمی)
        uses: msys2/setup-msys2@v2
        with:
          msystem: UCRT64
          install: mingw-w64-ucrt-x86_64-lua
          release: false

      - name: Setup Node (طبق مستندات رسمی)
        uses: actions/setup-node@v5
        with:
          node-version: '20'

      - name: Prebuild (natives بدون yarn_cli مشکل‌دار)
        shell: pwsh
        run: |
          $env:PATH = "$env:pythonLocation;$env:PATH"
          & "$env:pythonLocation\python.exe" -m pip install setuptools --quiet
          $root = "$env:GITHUB_WORKSPACE\server\fork\gtmp-src"
          $code = "$root\code"
          cd $code
          # ۱) prebuild_misc
          cmd /c prebuild_misc.cmd
          if ($LASTEXITCODE -ne 0) { Write-Host "prebuild_misc warn" }
          # ۲) natives — مستقیم، دور زدن yarn_cli (که node v12 آن را ESM می‌پندارد)
          #    a) دانلود natives از static.cfx.re (همان URL های prebuild_natives)
          $nat = "$root\ext\natives\inp"
          New-Item -ItemType Directory -Force -Path $nat | Out-Null
          $files = @{
            "natives_global.lua" = "https://static.cfx.re/natives/natives.lua"
            "natives_rdr3.lua"   = "https://static.cfx.re/natives/natives_rdr3.lua"
          }
          foreach ($k in $files.Keys) {
            Invoke-WebRequest $files[$k] -OutFile "$nat\$k"
            Write-Host "got $k ($((Get-Item "$nat\$k").Length) bytes)"
          }
          #    b) yarn رسمی (classic) + نصب deps با node خود CI (v20)
          $dg = "$root\ext\native-doc-gen"
          Invoke-WebRequest https://github.com/yarnpkg/yarn/releases/download/v1.22.22/yarn-v1.22.22.tar.gz -OutFile $env:TEMP\yarn.tgz
          tar -xzf $env:TEMP\yarn.tgz -C $env:TEMP
          $yarnJs = "$env:TEMP\yarn-v1.22.22\bin\yarn.js"
          $tooling = "$root\ext\native-doc-tooling"
          if (Test-Path $tooling) {
            cd $tooling
            node $yarnJs install --network-timeout 600000 2>&1 | Select-Object -Last 3
            cd $dg
          }
          #    c) lua از msys2 (در step Setup نصب شده)
          $env:PATH = "C:\msys64\ucrt64\bin;$env:PATH"
          #    d) codegen — ext/natives بخشی از خود ریپوی فایوام است (clone ما داردش)
          $natRoot = "$root\ext\natives"
          if (-not (Test-Path "$natRoot\codegen.lua")) {
            Write-Host "✗ codegen.lua در ext/natives نیست — clone خراب است"; exit 1
          }
          # natives_global.lua از قبل در inp است (دانلود مستقیم همان‌جا) — فقط اطمینان
          $luaCmd = "C:\msys64\ucrt64\bin\lua.exe"
          Write-Host "lua: $luaCmd"
          cd $natRoot
          & $luaCmd codegen.lua inp/natives_global.lua markdown server rpc 2>&1 | Select-Object -Last 5
          if ($LASTEXITCODE -ne 0) { Write-Host "codegen failed: $LASTEXITCODE"; Get-ChildItem . | Select Name | Format-Table; exit 1 }
          #    e) کپی خروجی‌ها (همان xcopy های prebuild_natives)
          if (Test-Path out) {
            New-Item -ItemType Directory -Force -Path "$root\code\client\clrcore-v2\Native" | Out-Null
            Copy-Item out\*.lua "$root\data\shared\citizen\scripting\lua" -Force -ErrorAction SilentlyContinue
            Copy-Item out\*.cs "$root\code\client\clrcore" -Recurse -Force -ErrorAction SilentlyContinue
            Copy-Item out\v2\*.cs "$root\code\client\clrcore-v2\Native" -Recurse -Force -ErrorAction SilentlyContinue
            Copy-Item out\Natives*.h "$root\code\components\citizen-scripting-lua\src" -Force -ErrorAction SilentlyContinue
            Copy-Item out\NativeTypes*.h "$root\code\components\citizen-scripting-core\src" -Force -ErrorAction SilentlyContinue
          }
          #    f) udis86 itab
          cd "$env:GITHUB_WORKSPACE\server\fork\gtmp-src\vendor\udis86"
          if (-not (Test-Path libudis86\itab.c)) {
            & "$env:pythonLocation\python.exe" scripts/ud_itab.py docs/x86/optable.xml ./libudis86/
          }
          cd "$env:GITHUB_WORKSPACE\server\fork\gtmp-src\code"
          $ok = Test-Path "client\clrcore-v2\Native\NativesServer.cs"
          if (-not $ok) {
            # شاید فقط v2 نیاز است — چک کل
            $any = Get-ChildItem client\clrcore-v2\Native -Filter Natives*.cs -ErrorAction SilentlyContinue
            Write-Host "Natives*.cs in v2: $($any.Count)"
            Get-ChildItem "$root\ext\natives\out" -ErrorAction SilentlyContinue | Select-Object Name | Format-Table
            exit 1
          }
          Write-Host "✓ NativesServer.cs OK"

      - name: NuGet restore
        shell: pwsh
        run: |
          # nuget.exe نیست روی runner — دانلود رسمی
          Invoke-WebRequest https://dist.nuget.org/win-x86-commandline/latest/nuget.exe -OutFile C:\nuget.exe
          cd server\fork\gtmp-src\code\build\server\windows
          # فقط csproj های C# (sln شامل vcxproj است که msbuild خودش میگیرد)
          Get-ChildItem -Filter *.csproj | ForEach-Object {
            Write-Host "restoring $($_.Name)"
            & C:\nuget.exe restore $_.FullName 2>&1 | Select-Object -Last 3
          }

      - name: Build StarkServer (server فقط)
        shell: pwsh
        run: |
          cd server\fork\gtmp-src\code
          $sln = Get-ChildItem build -Filter *.sln -Recurse | Select-Object -First 1
          if (-not $sln) { $sln = Get-ChildItem -Filter *.sln -Recurse | Select-Object -First 1 }
          Write-Host "Solution: $($sln.FullName)"
          $vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
          $msbuild = & $vswhere -latest -products * -requires Microsoft.Component.MSBuild -find MSBuild\**\Bin\MSBuild.exe | Select-Object -First 1
          Write-Host "MSBuild: $msbuild"
          # SDK موجود را پیدا کن
          $sdk = (Get-ChildItem "C:\Program Files (x86)\Windows Kits\10\Include" -ErrorAction SilentlyContinue | Sort-Object Name -Descending | Select-Object -First 1).Name
          Write-Host "Using Windows SDK: $sdk"
          & $msbuild $sln.FullName /m /p:Configuration=Release /p:Platform=x64 "/p:WindowsTargetPlatformVersion=$sdk" /p:TargetFrameworkVersion=v4.7.2 2>&1 | Select-Object -Last 60

      - name: Build game client (اختیاری)
        if: ${{ github.event.inputs.build_client == 'yes' }}
        shell: pwsh
        run: |
          cd server\fork\gtmp-src\code
          $sln = Get-ChildItem build -Filter *.sln -Recurse | Select-Object -First 1
          if (-not $sln) { $sln = Get-ChildItem -Filter *.sln -Recurse | Select-Object -First 1 }
          $vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
          $msbuild = & $vswhere -latest -products * -requires Microsoft.Component.MSBuild -find MSBuild\**\Bin\MSBuild.exe | Select-Object -First 1
          & $msbuild $sln.FullName /m /p:Configuration=Release /p:Platform=x64 2>&1 | Select-Object -Last 40

      - name: Collect artifacts
        shell: pwsh
        run: |
          New-Item -ItemType Directory -Force -Path artifacts | Out-Null
          $bins = Get-ChildItem server\fork\gtmp-src\code\build\bin -ErrorAction SilentlyContinue
          if ($bins) { Copy-Item server\fork\gtmp-src\code\build\bin\* artifacts\ -Recurse }
          else {
            $exes = Get-ChildItem server\fork\gtmp-src\code -Include *.exe,*.dll -Recurse | Where-Object { $_.FullName -match "build" } | Select-Object -First 50
            $exes | ForEach-Object { Copy-Item $_.FullName artifacts\ -ErrorAction SilentlyContinue }
          }
          Get-ChildItem artifacts -Recurse | Select-Object FullName

      - uses: actions/upload-artifact@v4
        with:
          name: gtmp-fork-windows
          path: artifacts/
          retention-days: 14

      - name: Summary
        shell: bash
        run: echo "بیلد فورک تمام شد — خروجی در Artifacts"
