#!/bin/bash
set -e

# QuoteForge Release Build Script
# Creates binaries for all platforms and packages them for release

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Get version from git
VERSION=$(git describe --tags --always --dirty 2>/dev/null || echo "dev")
if [[ $VERSION == *"dirty"* ]]; then
    echo -e "${RED}✗ Error: Working directory has uncommitted changes${NC}"
    echo "  Commit your changes first"
    exit 1
fi

echo -e "${GREEN}Building QuoteForge version: ${VERSION}${NC}"
echo ""

ensure_release_notes() {
    local notes_path="$1"
    if [ -f "${notes_path}" ]; then
        echo -e "${GREEN}  ✓ Preserving existing RELEASE_NOTES.md${NC}"
        return
    fi

    cat > "${notes_path}" <<EOF
# QuoteForge ${VERSION}

Дата релиза: $(date +%Y-%m-%d)
Тег: \`${VERSION}\`

## Что нового

- TODO: опишите ключевые изменения релиза.

## Запуск на macOS

Снимите карантинный атрибут через терминал: \`xattr -d com.apple.quarantine /path/to/qfs-darwin-arm64\`  
После этого бинарник запустится без предупреждения Gatekeeper.
EOF
    echo -e "${GREEN}  ✓ Created RELEASE_NOTES.md template${NC}"
}

# Create release directory
RELEASE_DIR="releases/${VERSION}"
mkdir -p "${RELEASE_DIR}"

# Create release notes template only when missing.
ensure_release_notes "${RELEASE_DIR}/RELEASE_NOTES.md"

# Build binaries
echo -e "${YELLOW}→ Building binaries...${NC}"

LDFLAGS="-s -w -X main.Version=${VERSION}"

echo "Building qfs for macOS (Apple Silicon)..."
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -ldflags="${LDFLAGS}" -o bin/qfs-darwin-arm64 ./cmd/qfs
echo "✓ Built: bin/qfs-darwin-arm64"

echo "Building qfs for Windows..."
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags="${LDFLAGS}" -o bin/qfs-windows-amd64.exe ./cmd/qfs
echo "✓ Built: bin/qfs-windows-amd64.exe"

# Package binaries with checksums
echo ""
echo -e "${YELLOW}→ Creating release packages...${NC}"

# macOS Apple Silicon
cd bin
tar -czf "../${RELEASE_DIR}/qfs-${VERSION}-darwin-arm64.tar.gz" qfs-darwin-arm64
cd ..
echo -e "${GREEN}  ✓ qfs-${VERSION}-darwin-arm64.tar.gz${NC}"

# Windows AMD64
cd bin
zip -q "../${RELEASE_DIR}/qfs-${VERSION}-windows-amd64.zip" qfs-windows-amd64.exe
cd ..
echo -e "${GREEN}  ✓ qfs-${VERSION}-windows-amd64.zip${NC}"

# Generate checksums
echo ""
echo -e "${YELLOW}→ Generating checksums...${NC}"
cd "${RELEASE_DIR}"
shasum -a 256 *.tar.gz *.zip > SHA256SUMS.txt 2>/dev/null || shasum -a 256 * | grep -v SHA256SUMS > SHA256SUMS.txt
cd ../..
echo -e "${GREEN}  ✓ SHA256SUMS.txt${NC}"

# List release files
echo ""
echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${GREEN}Release ${VERSION} built successfully!${NC}"
echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
echo "Files in ${RELEASE_DIR}:"
ls -lh "${RELEASE_DIR}"
echo ""

# Show next steps
echo -e "${YELLOW}Next steps:${NC}"
echo "  1. Create git tag:"
echo "     git tag -a ${VERSION} -m \"Release ${VERSION}\""
echo ""
echo "  2. Push tag to remote:"
echo "     git push origin ${VERSION}"
echo ""
echo "  3. Create release on git.mchus.pro:"
echo "     - Go to: https://git.mchus.pro/mchus/QuoteForge/releases"
echo "     - Click 'New Release'"
echo "     - Select tag: ${VERSION}"
echo "     - Upload files from: ${RELEASE_DIR}/"
echo ""
echo -e "${GREEN}Done!${NC}"
