#!/bin/bash
set -euo pipefail

# Description: Package and checksum distribution for release
# Arguments:   [version] - version string (default: from Cargo.toml)
# Returns:     0 on success, 1 on failure
# Output:      Final release package path

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly SCRIPT_DIR
WORKSPACE_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
readonly WORKSPACE_ROOT
readonly DISTRO_DIR="${WORKSPACE_ROOT}/distribution"
readonly RELEASE_DIR="${WORKSPACE_ROOT}/release"

# Extract version from Cargo.toml
get_version() {
    grep '^version' "${WORKSPACE_ROOT}/crates/typedialog-core/Cargo.toml" |
        head -1 |
        sed 's/.*"\([^"]*\)".*/\1/'
}

# Function: Print info message
log_info() {
    echo "[INFO] $*" >&2
}

# Function: Print error message
log_error() {
    echo "[ERROR] $*" >&2
}

# Function: Print success message
log_success() {
    echo "[✓] $*" >&2
}

# Function: Create release directory
create_release_dir() {
    mkdir -p "$RELEASE_DIR"
}

# Function: Copy distribution packages
copy_packages() {
    local version="$1"
    local distro_tar="${DISTRO_DIR}/typedialog-${version}.tar.gz"

    if [[ ! -f "$distro_tar" ]]; then
        log_error "Distribution package not found: $distro_tar"
        return 1
    fi

    cp "$distro_tar" "$RELEASE_DIR/"
    log_success "Copied distribution package"
}

# Function: Generate checksums
generate_checksums() {
    local version="$1"
    local checksum_file="${RELEASE_DIR}/SHA256SUMS"

    log_info "Generating checksums..."

    cd "$RELEASE_DIR"
    sha256sum "typedialog-${version}.tar.gz" > "$checksum_file"

    log_success "Checksums generated: $checksum_file"
}

# Function: Create release notes
create_release_notes() {
    local version="$1"
    local notes_file="${RELEASE_DIR}/RELEASE_NOTES.md"

    cat > "$notes_file" <<EOF
# TypeDialog $version

## Contents

- **typedialog-${version}.tar.gz** - Distribution package

## Installation

### Automatic (Linux/macOS)
\`\`\`bash
tar -xzf typedialog-${version}.tar.gz
cd typedialog-${version}
bash installers/install.sh
\`\`\`

### Automatic (Windows PowerShell)
\`\`\`powershell
tar -xf typedialog-${version}.tar.gz
cd typedialog-${version}
.\installers\install.ps1
\`\`\`

### Manual

1. Extract the archive
2. Copy binaries from \`bin/\` to your system PATH
3. Copy config from \`config/\` to \`~/.config/typedialog/\`

## Verification

Verify integrity with SHA256:
\`\`\`bash
sha256sum -c SHA256SUMS
\`\`\`

## Contents

The package includes:

- **bin/** - Compiled binaries for all backends
  - typedialog - CLI backend
  - typedialog-tui - TUI backend
  - typedialog-web - Web backend
  - typedialog-ai - AI backend (FormBackend + microservice)
  - typedialog-ag - Agent executor
  - typedialog-prov-gen - Provisioning generator

- **config/** - Configuration files for each backend and environment
  - cli/{default,dev,production}.toml
  - tui/{default,dev,production}.toml
  - web/{default,dev,production}.toml

- **installers/** - Installation scripts
  - install.sh - For Linux and macOS
  - install.ps1 - For Windows
  - README.md - Installation instructions

- **MANIFEST.json** - Package contents and structure

## Supported Platforms

- Linux (x86_64, aarch64)
- macOS (x86_64, aarch64)
- Windows (x86_64)

## Documentation

See installers/README.md for detailed installation instructions.

---
Released: $(date -u +'%Y-%m-%d %H:%M:%S UTC')
EOF

    log_success "Release notes created: $notes_file"
}

# Function: List release contents
list_release() {
    log_info "Release contents:"
    ls -lh "$RELEASE_DIR"
}

# Function: Main entry point
main() {
    local version="${1:-$(get_version)}"

    log_info "TypeDialog Release Packager"
    log_info "============================="
    log_info "Version: $version"

    create_release_dir
    copy_packages "$version"
    generate_checksums "$version"
    create_release_notes "$version"

    log_success "Release package ready!"
    log_info "Release directory: $RELEASE_DIR"

    list_release

    return 0
}

main "$@"
