#!/usr/bin/env node
// Reads src/lib/branding.json and emits a Swift mirror under
// targets/watch/Generated/Branding.swift. Run via `withWatchGenerated`
// at prebuild time, or directly: `node targets/_scripts/gen-watch-branding.mjs`.
//
// The watch target has no JS runtime, so it can't read branding.json
// itself. Mirroring at build-time keeps brand strings in lock-step with
// app.config.ts and src/lib/branding.ts (both also read the same JSON)
// without a manual edit-two-places ritual.

import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'

const HERE = dirname(fileURLToPath(import.meta.url))
const REPO_ROOT = join(HERE, '..', '..')
const BRANDING_JSON = join(REPO_ROOT, 'src', 'lib', 'branding.json')
const OUT = join(REPO_ROOT, 'targets', 'watch', 'Generated', 'Branding.swift')

function escapeSwift(s) {
  return String(s).replace(/\\/g, '\\\\').replace(/"/g, '\\"')
}

export function generate() {
  const branding = JSON.parse(readFileSync(BRANDING_JSON, 'utf8'))
  const required = [
    'name',
    'slug',
    'scheme',
    'description',
    'website',
    'iosBundleId',
    'appGroupId',
    'serverSoftwareName',
    'serverSoftwareDisplayName',
  ]
  for (const k of required) {
    if (typeof branding[k] !== 'string' || branding[k].length === 0) {
      throw new Error(`gen-watch-branding: branding.json missing string "${k}"`)
    }
  }
  const swift = `// AUTO-GENERATED — do not edit. Source: src/lib/branding.json
// Regenerate via \`node targets/_scripts/gen-watch-branding.mjs\` (runs at
// prebuild time via plugins/withWatchGenerated.js).

import Foundation

enum Branding {
    static let name = "${escapeSwift(branding.name)}"
    static let slug = "${escapeSwift(branding.slug)}"
    static let scheme = "${escapeSwift(branding.scheme)}"
    static let description = "${escapeSwift(branding.description)}"
    static let website = "${escapeSwift(branding.website)}"
    static let iosBundleId = "${escapeSwift(branding.iosBundleId)}"
    static let appGroupId = "${escapeSwift(branding.appGroupId)}"
    static let serverSoftwareName = "${escapeSwift(branding.serverSoftwareName)}"
    static let serverSoftwareDisplayName = "${escapeSwift(branding.serverSoftwareDisplayName)}"
    static let watchBundleId = "${escapeSwift(branding.iosBundleId)}.watchkitapp"
    static let watchComplicationBundleId = "${escapeSwift(branding.iosBundleId)}.watchkitapp.complication"
    static let userAgent = "\\(name)/Watch (CFNetwork)"
}
`
  mkdirSync(dirname(OUT), { recursive: true })
  writeFileSync(OUT, swift)
  return OUT
}

if (import.meta.url === `file://${process.argv[1]}`) {
  const out = generate()
  console.log(`gen-watch-branding: wrote ${out}`)
}
