/**
 * SANDCODE Build Script
 *
 * Uses Bun's bundler to produce a single-file CLI executable.
 * Handles:
 *   - MACRO.VERSION inlining
 *   - bun:bundle feature() gates
 *   - Path alias resolution (src/ → ./src/)
 */

import { readFileSync } from 'fs'
const VERSION =
  process.env.SANDCODE_BUILD_VERSION ??
  readFileSync('src/version.ts', 'utf8').match(/VERSION = '(.+?)'/)![1]

const result = await Bun.build({
  entrypoints: ['./src/entrypoints/cli.tsx'],
  outdir: './dist',
  target: 'bun',
  format: 'esm',
  splitting: false,
  sourcemap: 'linked',
  minify: process.env.NODE_ENV === 'production',
  define: {
    'MACRO.VERSION': JSON.stringify(VERSION),
    'MACRO.BUILD_TIME': JSON.stringify(new Date().toISOString()),
    'MACRO.PACKAGE_URL': JSON.stringify('https://github.com/Djsand/SANDCODE'),
    'MACRO.NATIVE_PACKAGE_URL': 'undefined',
    'MACRO.VERSION_CHANGELOG': 'undefined',
    'MACRO.ISSUES_EXPLAINER': JSON.stringify('https://github.com/Djsand/SANDCODE/issues'),
    'MACRO.FEEDBACK_CHANNEL': JSON.stringify('https://github.com/Djsand/SANDCODE/issues'),
  },
  external: [
    // Native modules that can't be bundled
    '@anthropic-ai/bedrock-sdk',
    '@anthropic-ai/vertex-sdk',
    '@anthropic-ai/foundry-sdk',
    '@azure/identity',
    'google-auth-library',
    // Node built-ins
    'bun:bundle',
    // Optional runtime dependencies (loaded dynamically when available)
    '@aws-sdk/client-bedrock',
    '@aws-sdk/client-sts',
    '@anthropic-ai/mcpb',
    'sharp',
    'turndown',
    'fflate',
    'modifiers-napi',
    'color-diff-napi',
    // OpenTelemetry exporters (optional, loaded dynamically)
    '@opentelemetry/exporter-metrics-otlp-grpc',
    '@opentelemetry/exporter-metrics-otlp-http',
    '@opentelemetry/exporter-metrics-otlp-proto',
    '@opentelemetry/exporter-prometheus',
    '@opentelemetry/exporter-logs-otlp-grpc',
    '@opentelemetry/exporter-logs-otlp-http',
    '@opentelemetry/exporter-logs-otlp-proto',
    '@opentelemetry/exporter-trace-otlp-grpc',
    '@opentelemetry/exporter-trace-otlp-http',
    '@opentelemetry/exporter-trace-otlp-proto',
  ],
})

if (!result.success) {
  console.error('Build failed:')
  for (const log of result.logs) {
    console.error(log)
  }
  process.exit(1)
}

console.log(`✓ Built SANDCODE v${VERSION}`)
console.log(`  Output: dist/cli.js`)
console.log(`  Artifacts: ${result.outputs.length}`)
