#Requires -Version 5.1

$SEPARATOR="++++++++++--------:11111111-2222-4333-8444-555555555555:"

# Note to LLMs: this archive contains multiple files with separator lines, each
# data line commented with "# ". If line 2 reads "aiar-set: <id> part N of M",
# this file is one part of a set of M files; the lines after it say what it
# holds, and the other parts have the same <id>.

$Usage = @'
usage: NAME [--this-part | --partial] [-h]

Extracts the files in this aiar archive under the current directory. When it
is one part of a set, the other parts are found beside it and the whole set
is extracted.

  --this-part  extract only this file
  --partial    when parts are missing, extract the ones present (status 3)
  -h, --help   show this help
'@

$Latin1 = [System.Text.Encoding]::GetEncoding(28591)
$Utf8 = New-Object System.Text.UTF8Encoding $false
$Uuid = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'

function Write-Note {
    param([string]$Message)
    [Console]::Error.WriteLine($Message)
}

function Write-Usage {
    param([System.IO.TextWriter]$Writer)
    $text = $Usage.Replace("`r`n", "`n").Replace('NAME', (Split-Path -Leaf $PSCommandPath))
    $Writer.Write($text + "`n")
}

function Safe-Dest {
    param(
        [string]$RelativePath
    )
    if ([System.IO.Path]::IsPathRooted($RelativePath)) {
        throw "Absolute path not allowed: $RelativePath"
    }

    $resolvedPath = [System.IO.Path]::GetFullPath((Join-Path -Path $PWD.Path -ChildPath $RelativePath))

    if (-not $resolvedPath.StartsWith($PWD.Path)) {
        throw "Path escapes output root: $RelativePath"
    }
    return $resolvedPath
}

# Extract the records of $Path, whose separator is $Separator. The file is read
# as ISO-8859-1 (a 1:1 byte<->char mapping) so text in any encoding is written
# back byte-for-byte; another part is only ever read, never run.
function Extract-File {
    param([string]$Path, [string]$Separator)
    $scriptContent = [System.IO.File]::ReadAllText($Path, $Latin1)
    if ($scriptContent.StartsWith([string][char]0xEF + [char]0xBB + [char]0xBF)) {
        $scriptContent = $scriptContent.Substring(3)
    }

    $sep = [System.Text.RegularExpressions.Regex]::Escape($Separator)
    # \z (not \Z): in .NET \Z also matches before a final newline, which would drop it.
    $pattern = "(?ms)^#\s?$sep([tb]):([^\n]+)\n(.*?)(?=(^#\s?$sep[tb]:|\z))"

    $found = [System.Text.RegularExpressions.Regex]::Matches($scriptContent, $pattern)

    foreach ($match in $found) {
        $ftype = $match.Groups[1].Value
        $relPath = $Utf8.GetString($Latin1.GetBytes($match.Groups[2].Value.Trim()))
        $body = $match.Groups[3].Value

        try {
            $dest = Safe-Dest -RelativePath $relPath
        }
        catch {
            Write-Warning "Warning: $_. Skipping."
            continue
        }

        if (Test-Path -LiteralPath $dest) {
            [Console]::Out.WriteLine("Skipping already existing file: '$dest'")
            continue
        }

        [Console]::Out.WriteLine("Creating: $dest")
        $null = New-Item -ItemType Directory -Force -Path (Split-Path -Path $dest -Parent)

        $uncommentedBody = $body -replace '(?m)^#\s?' , ''

        if ($ftype -ceq 't') { # Text file
            [System.IO.File]::WriteAllBytes($dest, $Latin1.GetBytes($uncommentedBody))
        }
        elseif ($ftype -ceq 'b') { # Binary file
            $cleanBase64String = $uncommentedBody -replace '\s'
            $bytes = [System.Convert]::FromBase64String($cleanBase64String)
            [System.IO.File]::WriteAllBytes($dest, $bytes)
        }
        else {
            Write-Warning "Unknown file type '$ftype' for '$relPath'. Skipping."
        }
    }
    return ($found.Count -gt 0)
}

function Read-Head {
    param([string]$Path, [int]$Size)
    try {
        $stream = [System.IO.File]::Open($Path, 'Open', 'Read', 'ReadWrite')
    }
    catch {
        return $null
    }
    try {
        $buffer = New-Object byte[] $Size
        $total = 0
        while ($total -lt $Size) {
            $read = $stream.Read($buffer, $total, $Size - $total)
            if ($read -le 0) { break }
            $total += $read
        }
        $result = New-Object byte[] $total
        [Array]::Copy($buffer, $result, $total)
        return ,$result
    }
    catch {
        return $null
    }
    finally {
        $stream.Dispose()
    }
}

function Get-Lines {
    param([byte[]]$Data, [System.Text.Encoding]$Encoding)
    $start = 0
    if ($Data.Length -ge 3 -and $Data[0] -eq 0xEF -and $Data[1] -eq 0xBB -and $Data[2] -eq 0xBF) {
        $start = 3
    }
    $text = $Encoding.GetString($Data, $start, $Data.Length - $start)
    $lines = $text.Split([char]10)
    for ($i = 0; $i -lt $lines.Length; $i++) {
        if ($lines[$i].EndsWith([string][char]13)) {
            $lines[$i] = $lines[$i].Substring(0, $lines[$i].Length - 1)
        }
    }
    return ,$lines
}

# @{ Status = 'part'; Id; N; M; Fmt }, or Status 'none', 'malformed' or 'utf16'.
function Read-SetLine {
    param([byte[]]$Data)
    if ($Data.Length -ge 2 -and (($Data[0] -eq 0xFF -and $Data[1] -eq 0xFE) -or ($Data[0] -eq 0xFE -and $Data[1] -eq 0xFF))) {
        return @{ Status = 'utf16' }
    }
    $lines = Get-Lines -Data $Data -Encoding $Latin1
    $first = $lines[0]
    $second = ''
    if ($lines.Length -gt 1) { $second = $lines[1] }
    if (-not ($second.StartsWith('# aiar-set: ', [StringComparison]::Ordinal) -or $second.StartsWith('// aiar-set: ', [StringComparison]::Ordinal))) {
        return @{ Status = 'none' }
    }
    $fmt = $null
    if ([regex]::IsMatch($first, '^#!/bin/bash\z')) { $fmt = 'bash' }
    elseif ([regex]::IsMatch($first, '^#!/usr/bin/env node\z')) { $fmt = 'nodejs' }
    elseif ([regex]::IsMatch($first, '^#Requires -Version [^\n]*\z')) { $fmt = 'powershell' }
    elseif ([regex]::IsMatch($first, '^SEPARATOR="[^\n]*"\z')) { $fmt = 'bare' }
    elseif ([regex]::IsMatch($first, '^(# -\*- coding: latin-1 -\*-)?\z')) { $fmt = 'py' }
    if ($null -eq $fmt) {
        return @{ Status = 'malformed' }
    }
    $prefix = '# '
    if ($fmt -ceq 'nodejs') { $prefix = '// ' }
    $tail = ''
    if ($fmt -ceq 'bash') { $tail = ' #' }
    $re = '^' + [regex]::Escape($prefix) + 'aiar-set: (' + $Uuid + ') part ([0-9]+) of ([0-9]+)' + [regex]::Escape($tail) + '\z'
    $match = [regex]::Match($second, $re)
    if (-not $match.Success) {
        return @{ Status = 'malformed' }
    }
    $number = $match.Groups[2].Value
    $total = $match.Groups[3].Value
    if ($total.Length -gt 9) {
        return @{ Status = 'malformed' }
    }
    $n = [int]$number
    $m = [int]$total
    if ($number.Length -ne $total.Length -or $total.Length -ne ([string]$m).Length -or $n -lt 1 -or $n -gt $m -or $m -lt 2) {
        return @{ Status = 'malformed' }
    }
    return @{ Status = 'part'; Id = $match.Groups[1].Value; N = $n; M = $m; Fmt = $fmt }
}

function Get-PartName {
    param([string]$Output, [int]$N, [int]$Total)
    $tag = ([string]$N).PadLeft(([string]$Total).Length, '0') + 'of' + $Total
    $components = $Output.Split('.')
    $stem = $components[0]
    $suffixes = @()
    if ($components.Length -gt 1) { $suffixes = $components[1..($components.Length - 1)] }
    $lowered = @($suffixes | ForEach-Object { $_.ToLowerInvariant() })
    $languages = @('py', 'js', 'sh', 'bash', 'zsh', 'ps1', 'psm1')
    $k = $suffixes.Length
    $at = -1
    $inserted = @()
    for ($i = $k - 2; $i -ge 0; $i--) {
        if ($lowered[$i] -ceq 'aiar') { $at = $i + 1; $inserted = @($tag); break }
    }
    if ($at -lt 0 -and $k -ge 1 -and $lowered[$k - 1] -ceq 'aiar') {
        $at = $k - 1
        $inserted = @($tag)
    }
    if ($at -lt 0) {
        $at = $k
        if ($k -ge 1 -and $languages -ccontains $lowered[$k - 1]) { $at = $k - 1 }
        elseif ($k -ge 2 -and $lowered[$k - 1] -ceq 'txt' -and $languages -ccontains $lowered[$k - 2]) { $at = $k - 2 }
        elseif ($k -ge 1 -and $lowered[$k - 1] -ceq 'txt') { $at = $k - 1 }
        $inserted = @('aiar', $tag)
    }
    $parts = New-Object System.Collections.Generic.List[string]
    $parts.Add($stem)
    for ($i = 0; $i -lt $at; $i++) { $parts.Add($suffixes[$i]) }
    foreach ($x in $inserted) { $parts.Add($x) }
    for ($i = $at; $i -lt $k; $i++) { $parts.Add($suffixes[$i]) }
    return [string]::Join('.', $parts.ToArray())
}

function Get-OutputName {
    param([string]$Path, [int]$N, [int]$M)
    $data = Read-Head -Path $Path -Size 65536
    if ($null -eq $data) { return $null }
    $lines = Get-Lines -Data $data -Encoding $Utf8
    if ($lines.Length -lt 4) { return $null }
    $match = [regex]::Match($lines[2], '^# aiar part ([0-9]+) of ([0-9]+) of (.*), limit ([0-9]+) bytes\z')
    if (-not $match.Success -or [int]$match.Groups[1].Value -ne $N -or [int]$match.Groups[2].Value -ne $M) {
        return $null
    }
    return $match.Groups[3].Value
}

function Get-PartSeparator {
    param([string]$Path)
    $data = Read-Head -Path $Path -Size 65536
    if ($null -eq $data) { return $null }
    $match = [regex]::Match($Latin1.GetString($data), '(?m)^\$SEPARATOR="([^"]+)"')
    if ($match.Success) { return $match.Groups[1].Value }
    return $null
}

function Test-SameContent {
    param([string]$A, [string]$B)
    $x = [System.IO.File]::ReadAllBytes($A)
    $y = [System.IO.File]::ReadAllBytes($B)
    if ($x.Length -ne $y.Length) { return $false }
    for ($i = 0; $i -lt $x.Length; $i++) {
        if ($x[$i] -ne $y[$i]) { return $false }
    }
    return $true
}

function Test-RegularFile {
    param([string]$Path)
    $info = New-Object System.IO.FileInfo $Path
    if (-not $info.Exists) { return $false }
    if (($info.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) { return $false }
    if ($PSVersionTable.PSVersion.Major -ge 6 -and -not $IsWindows) {
        $item = Get-Item -LiteralPath $Path -Force
        $mode = $item.PSObject.Properties['UnixMode']
        if ($null -ne $mode -and -not ([string]$mode.Value).StartsWith('-')) { return $false }
    }
    return $true
}

function Get-IncompleteGroups {
    param($Parts, [int[]]$Missing)
    $names = New-Object System.Collections.Generic.List[string]
    foreach ($n in ($Parts.Keys | Sort-Object)) {
        $data = Read-Head -Path $Parts[$n] -Size 65536
        if ($null -eq $data) { continue }
        $lines = Get-Lines -Data $data -Encoding $Utf8
        for ($i = 2; $i -lt $lines.Length; $i++) {
            if (-not $lines[$i].StartsWith('# partial: ', [StringComparison]::Ordinal)) { continue }
            $body = $lines[$i].Substring('# partial: '.Length)
            foreach ($match in [regex]::Matches($body, '(.+?) \(also in parts? ([0-9, -]+)\)(?: |$)')) {
                $hit = $false
                foreach ($piece in $match.Groups[2].Value.Split(@(', '), [StringSplitOptions]::None)) {
                    $bounds = $piece.Split('-')
                    $a = [int]$bounds[0]
                    $b = [int]$bounds[$bounds.Length - 1]
                    for ($k = $a; $k -le $b; $k++) {
                        if ($Missing -contains $k) { $hit = $true }
                    }
                }
                $name = $match.Groups[1].Value
                if ($hit -and -not $names.Contains($name)) { $names.Add($name) }
            }
            break
        }
    }
    return ,$names
}

function Invoke-Main {
    param([string[]]$Arguments)
    $me = $PSCommandPath
    $myName = Split-Path -Leaf $me
    $thisPart = $false
    $partial = $false
    foreach ($arg in $Arguments) {
        if ($arg -ceq '--this-part') { $thisPart = $true }
        elseif ($arg -ceq '--partial') { $partial = $true }
        elseif ($arg -ceq '-h' -or $arg -ceq '--help') {
            Write-Usage -Writer ([Console]::Out)
            return 0
        }
        else {
            Write-Note "Error: unknown argument '$arg'"
            Write-Usage -Writer ([Console]::Error)
            return 2
        }
    }
    if ($thisPart -and $partial) {
        Write-Note 'Error: --this-part and --partial cannot be used together'
        Write-Usage -Writer ([Console]::Error)
        return 2
    }

    $ownData = Read-Head -Path $me -Size 4096
    if ($null -eq $ownData) { $ownData = New-Object byte[] 0 }
    $own = Read-SetLine -Data $ownData
    if ($own.Status -ceq 'malformed') {
        Write-Note "Error: ${myName}: malformed set line"
        return 1
    }
    if ($own.Status -cne 'part' -or $thisPart) {
        if (-not (Extract-File -Path $me -Separator $SEPARATOR)) {
            Write-Note 'Error: No payload sections found in data block.'
            return 1
        }
        [Console]::Out.WriteLine('Extraction complete.')
        return 0
    }

    # This file is one part of a set: find the others beside it, as data only.
    $width = ([string]$own.M).Length
    $candidates = @{}
    $candidates[$own.N] = New-Object System.Collections.Generic.List[string]
    $candidates[$own.N].Add($me)
    $errors = 0
    $otherParts = 0
    $otherIds = New-Object 'System.Collections.Generic.HashSet[string]' ([StringComparer]::Ordinal)
    $directory = Split-Path -Parent $me
    $names = @()
    try {
        $names = @([System.IO.Directory]::GetFileSystemEntries($directory) | ForEach-Object { [System.IO.Path]::GetFileName($_) })
    }
    catch {
        $names = @()
    }
    $sorted = [string[]]$names
    [Array]::Sort($sorted, [StringComparer]::Ordinal)
    foreach ($name in $sorted) {
        if ($name -ceq $myName) { continue }
        $path = Join-Path -Path $directory -ChildPath $name
        if (-not (Test-RegularFile -Path $path)) { continue }
        $data = Read-Head -Path $path -Size 4096
        if ($null -eq $data) { continue }
        $found = Read-SetLine -Data $data
        if ($found.Status -ceq 'utf16') {
            Write-Note "${name}: UTF-16, re-save as UTF-8 or use aiar extract"
            continue
        }
        if ($found.Status -ceq 'malformed') {
            Write-Note "${name}: malformed set line, ignored"
            continue
        }
        if ($found.Status -cne 'part') { continue }
        if ($found.Id -cne $own.Id) {
            $null = $otherIds.Add($found.Id)
            $otherParts++
            continue
        }
        if ($found.Fmt -cne $own.Fmt) {
            Write-Note "Error: $name is a part of this set in another format"
            $errors++
            continue
        }
        if ($found.M -ne $own.M) {
            Write-Note ("Error: $name says this set has {0} parts, not {1}" -f $found.M, $own.M)
            $errors++
            continue
        }
        if (-not $candidates.ContainsKey($found.N)) {
            $candidates[$found.N] = New-Object System.Collections.Generic.List[string]
        }
        $candidates[$found.N].Add($path)
    }

    $parts = @{}
    foreach ($n in ($candidates.Keys | Sort-Object)) {
        $list = $candidates[$n]
        $first = $list[0]
        $parts[$n] = $first
        $num = ([string]$n).PadLeft($width, '0')
        for ($i = 1; $i -lt $list.Count; $i++) {
            $a = Split-Path -Leaf $first
            $b = Split-Path -Leaf $list[$i]
            if (Test-SameContent -A $first -B $list[$i]) {
                Write-Note "$a and $b are identical copies of part $num; using $a"
            }
            else {
                Write-Note "Error: $a and $b are different files for part $num"
                $errors++
            }
        }
    }
    if ($otherParts -gt 0) {
        $wordParts = 'parts'
        if ($otherParts -eq 1) { $wordParts = 'part' }
        $wordSets = 'sets'
        if ($otherIds.Count -eq 1) { $wordSets = 'set' }
        Write-Note ("ignored {0} {1} of {2} other {3}" -f $otherParts, $wordParts, $otherIds.Count, $wordSets)
    }

    $missing = @()
    for ($n = 1; $n -le $own.M; $n++) {
        if (-not $parts.ContainsKey($n)) { $missing += $n }
    }
    if ($missing.Count -gt 0) {
        $word = 'parts'
        if ($missing.Count -eq 1) { $word = 'part' }
        $numbers = @($missing | ForEach-Object { ([string]$_).PadLeft($width, '0') })
        $message = "missing $word " + [string]::Join(', ', $numbers) + " of $($own.M)"
        $oname = Get-OutputName -Path $me -N $own.N -M $own.M
        if ($null -ne $oname) {
            $expected = @($missing | ForEach-Object { Get-PartName -Output $oname -N $_ -Total $own.M })
            $message += ' (expected ' + [string]::Join(', ', $expected) + ')'
        }
        if ($partial) {
            Write-Note "Warning: $message"
        }
        else {
            Write-Note "Error: $message"
            $errors++
        }
    }
    if ($errors -gt 0) {
        Write-Note 'Nothing was extracted.'
        return 1
    }

    foreach ($n in ($parts.Keys | Sort-Object)) {
        $file = $parts[$n]
        if ($file -ceq $me) {
            $separator = $SEPARATOR
        }
        else {
            $separator = Get-PartSeparator -Path $file
        }
        if ($null -eq $separator) {
            Write-Note ("Error: No SEPARATOR in '{0}'." -f (Split-Path -Leaf $file))
            return 1
        }
        $null = Extract-File -Path $file -Separator $separator
    }
    if ($missing.Count -gt 0) {
        $groups = Get-IncompleteGroups -Parts $parts -Missing $missing
        if ($groups.Count -gt 0) {
            Write-Note ('Warning: incomplete groups: ' + [string]::Join(' ', $groups.ToArray()))
        }
        [Console]::Out.WriteLine(("Extraction incomplete: {0} of {1} parts." -f $parts.Count, $own.M))
        return 3
    }
    [Console]::Out.WriteLine('Extraction complete.')
    return 0
}

# --- Main execution ---
$status = Invoke-Main -Arguments $args

# The script must exit here to prevent PowerShell from trying to interpret the payload.
exit $status

# --- PAYLOAD ---
# ++++++++++--------:11111111-2222-4333-8444-555555555555:t:empty.txt
# ++++++++++--------:11111111-2222-4333-8444-555555555555:t:legacy/latin1.txt
# caf
# ++++++++++--------:11111111-2222-4333-8444-555555555555:t:readme.md
# # Title
# 
# Some text.
# ++++++++++--------:11111111-2222-4333-8444-555555555555:t:src/crlf.txt
# line one
# line two
# ++++++++++--------:11111111-2222-4333-8444-555555555555:t:src/main.c
# int main(void) {
#     return 0;
# }
# ++++++++++--------:11111111-2222-4333-8444-555555555555:t:src/no_newline.txt
# last line without newline
# ++++++++++--------:11111111-2222-4333-8444-555555555555:t:src/utf8.txt
# café   über
