#!/usr/bin/env bash
# Build the theme component from the @dangerousthings/tokens package.
# Generates token CSS files and packages them for distribution.
#
# Environment variables:
#   OUTPUT_DIR         - where to write the tarball (default: ./dist)
#   VERSION            - version string (default: read from VERSION file)
#   DESIGN_SYSTEM_DIR  - path to dt-design-system monorepo
#                        (default: ../dt-design-system relative to workspace)

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
WORKSPACE="${SCRIPT_DIR}/.."
OUTPUT_DIR="${OUTPUT_DIR:-${WORKSPACE}/dist}"
VERSION="${VERSION:-$(cat "${WORKSPACE}/VERSION" 2>/dev/null || echo "0.1.0")}"
DESIGN_SYSTEM_DIR="${DESIGN_SYSTEM_DIR:-$(realpath "${WORKSPACE}/../dt-design-system")}"

echo "=== Dangerous Pi Theme Build ==="
echo "Version:       ${VERSION}"
echo "Design system: ${DESIGN_SYSTEM_DIR}"

if [ ! -d "$DESIGN_SYSTEM_DIR" ]; then
    echo "Error: dt-design-system not found at ${DESIGN_SYSTEM_DIR}"
    echo "Set DESIGN_SYSTEM_DIR to the monorepo path"
    exit 1
fi

# Build tokens to generate CSS
cd "$DESIGN_SYSTEM_DIR"
npm ci --production=false
npm run build:tokens

# Package theme CSS files
STAGING="/tmp/theme-staging/theme"
rm -rf /tmp/theme-staging

BRANDS=("dt" "classic" "supra")
for brand in "${BRANDS[@]}"; do
    CSS_FILE="${DESIGN_SYSTEM_DIR}/packages/tokens/dist/css/${brand}.css"
    if [ -f "$CSS_FILE" ]; then
        mkdir -p "${STAGING}/${brand}"
        cp "$CSS_FILE" "${STAGING}/${brand}/tokens.css"

        # Read brand metadata from the generated CSS or tokens
        cat > "${STAGING}/${brand}/theme.json" << TJEOF
{
  "id": "${brand}",
  "supportsModes": ["dark", "light", "auto"],
  "defaultMode": "dark"
}
TJEOF
    else
        echo "Warning: ${CSS_FILE} not found, skipping ${brand}"
    fi
done

# Add brand metadata from tokens package if available
TOKENS_INDEX="${DESIGN_SYSTEM_DIR}/packages/tokens/dist/index.js"
if [ -f "$TOKENS_INDEX" ]; then
    # Extract brand names/descriptions from the built tokens
    node -e "
const tokens = require('${TOKENS_INDEX}');
const brands = Object.values(tokens.brands || {}).map(b => ({
  id: b.id, name: b.name, description: b.description,
  supportsModes: ['dark', 'light', 'auto'], defaultMode: 'dark'
}));
require('fs').writeFileSync('/tmp/theme-staging/theme/themes.json',
  JSON.stringify({ schema_version: 1, themes: brands }, null, 2));
" 2>/dev/null || echo '{"schema_version": 1, "themes": []}' > "${STAGING}/themes.json"
else
    # Fallback: generate registry from what we packaged
    cat > "${STAGING}/themes.json" << REOF
{
  "schema_version": 1,
  "themes": [
    {"id": "dt", "name": "Dangerous Things", "description": "Official DT brand", "supportsModes": ["dark", "light", "auto"], "defaultMode": "dark"},
    {"id": "classic", "name": "Classic Cyberpunk", "description": "Original dark navy aesthetic", "supportsModes": ["dark", "light", "auto"], "defaultMode": "dark"},
    {"id": "supra", "name": "VivoKey Supra", "description": "Material Design 3 with VivoKey blue", "supportsModes": ["dark", "light", "auto"], "defaultMode": "dark"}
  ]
}
REOF
fi

cat > "${STAGING}/COMPONENT_VERSION" << EOF
{
  "component_id": "theme",
  "version": "${VERSION}",
  "build_date": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")",
  "tokens_package_version": "$(node -p "require('${DESIGN_SYSTEM_DIR}/packages/tokens/package.json').version" 2>/dev/null || echo "unknown")"
}
EOF

mkdir -p "$OUTPUT_DIR"
TARBALL="theme-${VERSION}.tar.gz"
cd /tmp/theme-staging
tar -czf "${OUTPUT_DIR}/${TARBALL}" theme/
echo "✅ Built: ${OUTPUT_DIR}/${TARBALL}"

rm -rf /tmp/theme-staging
