#!/usr/bin/env node
// Reads .env.watch.local at repo root and emits
// targets/watch/Generated/DevAuth.swift with a hardcoded
// (instance, accessToken) pair so Phase A.1 can render real data without
// the WCSession handoff yet existing.
//
// If .env.watch.local is missing, emits an empty stub — the watch app
// renders the "no auth — set up .env.watch.local" empty state. This
// keeps the build green for anyone cloning who hasn't filled in their
// own credentials yet.
//
// .env.watch.local format (gitignored, never commit):
//   INSTANCE=pixelfed.social
//   TOKEN=ya29...
//   ACCOUNT_ID=12345          # numeric Mastodon-compat user id (optional)
//   USERNAME=bko              # optional, for the Account screen
//   ACCOUNT_TYPE=pixelfed     # 'pixelfed' or 'mastodon', default pixelfed

import { existsSync, 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 ENV_FILE = join(REPO_ROOT, '.env.watch.local')
const OUT = join(REPO_ROOT, 'targets', 'watch', 'Generated', 'DevAuth.swift')

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

function parseEnv(text) {
  const out = {}
  for (const raw of text.split('\n')) {
    const line = raw.trim()
    if (!line || line.startsWith('#')) continue
    const eq = line.indexOf('=')
    if (eq < 0) continue
    const key = line.slice(0, eq).trim()
    let value = line.slice(eq + 1).trim()
    if (
      (value.startsWith('"') && value.endsWith('"')) ||
      (value.startsWith("'") && value.endsWith("'"))
    ) {
      value = value.slice(1, -1)
    }
    out[key] = value
  }
  return out
}

export function generate() {
  let env = {}
  let present = false
  if (existsSync(ENV_FILE)) {
    env = parseEnv(readFileSync(ENV_FILE, 'utf8'))
    present = !!(env.INSTANCE && env.TOKEN)
  }

  const swift = `// AUTO-GENERATED — do not edit. Source: .env.watch.local (repo root, gitignored)
// Regenerate via \`node targets/_scripts/gen-watch-devauth.mjs\` (runs at
// prebuild time via plugins/withWatchGenerated.js).
//
// Phase A.1 dev-mode auth shortcut. When WCSession handoff lands in
// Phase B, the watch reads (instance, token) from its keychain instead
// and DevAuth.isPresent returns false in production builds.

import Foundation

enum DevAuth {
    static let isPresent: Bool = ${present ? 'true' : 'false'}
    static let instance: String = "${escapeSwift(env.INSTANCE ?? '')}"
    static let accessToken: String = "${escapeSwift(env.TOKEN ?? '')}"
    static let accountId: String = "${escapeSwift(env.ACCOUNT_ID ?? '')}"
    static let username: String = "${escapeSwift(env.USERNAME ?? '')}"
    static let accountType: String = "${escapeSwift(env.ACCOUNT_TYPE ?? 'pixelfed')}"
}
`
  mkdirSync(dirname(OUT), { recursive: true })
  writeFileSync(OUT, swift)
  return { path: OUT, present }
}

if (import.meta.url === `file://${process.argv[1]}`) {
  const { path, present } = generate()
  console.log(
    `gen-watch-devauth: wrote ${path} (auth ${present ? 'present' : 'absent — empty state'})`
  )
}
