import { DEFAULT_EMOJI } from '@types'

import { BINARY, TEMPLATES } from './templates.data'

export type TemplateType = 'ssr' | 'bare' | 'spa'

export type AppTemplates = Record<string, string | Uint8Array>

interface TemplateOptions {
  tool?: boolean
}

interface TemplateVars {
  APP_EMOJI: string
  APP_NAME: string
}

export function generateTemplates(appName: string, template: TemplateType = 'ssr', options: TemplateOptions = {}): AppTemplates {
  const vars: TemplateVars = {
    APP_EMOJI: DEFAULT_EMOJI,
    APP_NAME: appName,
  }

  const result: AppTemplates = {}

  // Text files (shared + template-specific, merged at embed time)
  for (const [filename, content] of Object.entries(TEMPLATES[template] ?? {})) {
    let processed = replaceVars(content, vars)

    if (filename === 'package.json' && options.tool) {
      const pkg = JSON.parse(processed)
      pkg.toes.tool = true
      processed = JSON.stringify(pkg, null, 2) + '\n'
    }

    result[filename] = processed
  }

  // Binary files (base64 encoded)
  for (const [filename, base64] of Object.entries(BINARY[template] ?? {})) {
    result[filename] = Buffer.from(base64, 'base64')
  }

  return result
}

function replaceVars(content: string, vars: TemplateVars): string {
  return content
    .replace(/\$\$APP_NAME\$\$/g, vars.APP_NAME)
    .replace(/\$\$APP_EMOJI\$\$/g, vars.APP_EMOJI)
}
