#!/bin/bash
set -euo pipefail

# Description: Create distribution package with binaries and configs
# Arguments:   [version] - version string (default: from Cargo.toml)
# Returns:     0 on success, 1 on failure
# Output:      Distribution 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 BUILD_DIR="${WORKSPACE_ROOT}/target/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: Validate files exist
validate_files() {
    local missing=0

    for file in "$@"; do
        if [[ ! -f "$file" ]]; then
            log_error "Missing: $file"
            ((missing++))
        fi
    done

    return $((missing > 0 ? 1 : 0))
}

# Function: Create distribution directory
create_distro_structure() {
    local version="$1"
    local distro_path="${DISTRO_DIR}/typedialog-${version}"

    mkdir -p "${distro_path}"/{bin,config,docs,lib}

    echo "$distro_path"
}

# Function: Copy binaries
copy_binaries() {
    local distro_path="$1"

    if [[ -f "${BUILD_DIR}/typedialog" ]]; then
        cp "${BUILD_DIR}/typedialog" "${distro_path}/bin/"
    fi

    if [[ -f "${BUILD_DIR}/typedialog-tui" ]]; then
        cp "${BUILD_DIR}/typedialog-tui" "${distro_path}/bin/"
    fi

    if [[ -f "${BUILD_DIR}/typedialog-web" ]]; then
        cp "${BUILD_DIR}/typedialog-web" "${distro_path}/bin/"
    fi

    if [[ -f "${BUILD_DIR}/typedialog-ai" ]]; then
        cp "${BUILD_DIR}/typedialog-ai" "${distro_path}/bin/"
    fi

    if [[ -f "${BUILD_DIR}/typedialog-ag" ]]; then
        cp "${BUILD_DIR}/typedialog-ag" "${distro_path}/bin/"
    fi


    if [[ -f "${BUILD_DIR}/typedialog-prov-gen" ]]; then
        cp "${BUILD_DIR}/typedialog-prov-gen" "${distro_path}/bin/"
    fi
}

# Function: Copy configurations
copy_configs() {
    local distro_path="$1"

    cp -r "${WORKSPACE_ROOT}/config"/* "${distro_path}/config/" || {
        log_error "Failed to copy configurations"
        return 1
    }
}

# Function: Copy installers
copy_installers() {
    local distro_path="$1"

    mkdir -p "${distro_path}/installers"

    if [[ -f "${WORKSPACE_ROOT}/installers/bootstrap/install.sh" ]]; then
        cp "${WORKSPACE_ROOT}/installers/bootstrap/install.sh" "${distro_path}/installers/"
        chmod +x "${distro_path}/installers/install.sh"
    fi

    if [[ -f "${WORKSPACE_ROOT}/installers/bootstrap/install.ps1" ]]; then
        cp "${WORKSPACE_ROOT}/installers/bootstrap/install.ps1" "${distro_path}/installers/"
    fi

    if [[ -f "${WORKSPACE_ROOT}/installers/bootstrap/README.md" ]]; then
        cp "${WORKSPACE_ROOT}/installers/bootstrap/README.md" "${distro_path}/installers/"
    fi
}

# Function: Create manifest
create_manifest() {
    local distro_path="$1"
    local version="$2"
    local manifest="${distro_path}/MANIFEST.json"

    cat > "$manifest" <<EOF
{
  "name": "typedialog",
  "version": "$version",
  "created": "$(date -u +'%Y-%m-%dT%H:%M:%SZ')",
  "structure": {
    "bin": "Binary executables",
    "config": "Configuration files per backend/environment",
    "installers": "Installation scripts (Linux/macOS/Windows)",
    "docs": "Documentation"
  },
  "binaries": [
    "bin/typedialog",
    "bin/typedialog-tui",
    "bin/typedialog-web",
    "bin/typedialog-ai",
    "bin/typedialog-ag",
    "bin/typedialog-prov-gen"
  ],
  "configs": {
    "cli": [
      "config/cli/default.toml",
      "config/cli/dev.toml",
      "config/cli/production.toml"
    ],
    "tui": [
      "config/tui/default.toml",
      "config/tui/dev.toml",
      "config/tui/production.toml"
    ],
    "web": [
      "config/web/default.toml",
      "config/web/dev.toml",
      "config/web/production.toml"
    ],
    "ai": [
      "config/ai/default.toml",
      "config/ai/dev.toml",
      "config/ai/production.toml"
    ]
  },
  "installers": {
    "linux_macos": "installers/install.sh",
    "windows": "installers/install.ps1",
    "readme": "installers/README.md"
  }
}
EOF
}

# Function: Create tarball
create_tarball() {
    local distro_path="$1"
    local distro_name
    distro_name=$(basename "$distro_path")
    local tarball="${DISTRO_DIR}/${distro_name}.tar.gz"

    cd "$DISTRO_DIR"
    tar -czf "$tarball" "$distro_name"

    echo "$tarball"
}

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

    log_info "TypeDialog Distribution Builder"
    log_info "================================"

    # Build release first
    log_info "Building release binaries..."
    cd "$WORKSPACE_ROOT"
    cargo build --workspace --release || {
        log_error "Build failed"
        return 1
    }

    # Create distribution
    local distro_path
    distro_path=$(create_distro_structure "$version")
    log_info "Distribution path: $distro_path"

    copy_binaries "$distro_path"
    copy_configs "$distro_path"
    copy_installers "$distro_path"
    create_manifest "$distro_path" "$version"

    local tarball
    tarball=$(create_tarball "$distro_path")
    log_info "Distribution package: $tarball"

    echo "$tarball"
    return 0
}

main "$@"
