/**
 * Generate TypeScript types from Zod schemas.
 *
 * Reads coreSchemas.ts and controlSchemas.ts, extracts all `export const XSchema = lazySchema(...)`
 * declarations, and generates `z.infer<>` type exports.
 *
 * Usage: bun scripts/generate-sdk-types.ts
 */

import { readFileSync, writeFileSync } from 'fs'
import { resolve } from 'path'

const ROOT = resolve(import.meta.dirname, '..')
const SDK_DIR = resolve(ROOT, 'src/entrypoints/sdk')

function extractSchemaNames(filePath: string): string[] {
  const content = readFileSync(filePath, 'utf8')
  const regex = /^export const (\w+Schema) = lazySchema\(/gm
  const names: string[] = []
  let match: RegExpExecArray | null
  while ((match = regex.exec(content)) !== null) {
    names.push(match[1])
  }
  return names
}

function stripSchemaSuffix(name: string): string {
  return name.replace(/Schema$/, '')
}

function generateFile(schemasFile: string, schemaImportPath: string, outputPath: string): void {
  const names = extractSchemaNames(schemasFile)
  const typeName = (s: string) => stripSchemaSuffix(s)

  const lines = [
    '// AUTO-GENERATED — do not edit. Run: bun scripts/generate-sdk-types.ts',
    "import type { z } from 'zod/v4'",
    `import type * as S from '${schemaImportPath}'`,
    '',
    ...names.map((s) => `export type ${typeName(s)} = z.infer<ReturnType<typeof S.${s}>>`),
    '',
  ]

  writeFileSync(outputPath, lines.join('\n'))
  console.log(`  ${outputPath} — ${names.length} types`)
}

console.log('Generating SDK types...')

generateFile(
  resolve(SDK_DIR, 'coreSchemas.ts'),
  './coreSchemas.js',
  resolve(SDK_DIR, 'coreTypes.generated.ts'),
)

generateFile(
  resolve(SDK_DIR, 'controlSchemas.ts'),
  './controlSchemas.js',
  resolve(SDK_DIR, 'controlTypes.ts'),
)

console.log('Done.')
