#!/usr/bin/env bun

import * as p from "@clack/prompts";
import { initRenderer } from '@gregorlohaus/tdir'
import { z } from 'zod'
import path from "node:path";

p.intro(`create-glstack ${process.env.GLSTACK_DEV && 'isDev'}`);

const project = await p.group(
  {
    name: () =>
      p.text({
        message: "What would you like to name your project?",
        placeholder: "glstack-test",
        defaultValue: "glstack-test",
        validate: (value) => {
          return undefined
        },
      }),
    frontend: async () =>
      await p.select({
        message: 'Pick a frontend framework.',
        options: [
          { value: "svelte-kit", label: "SvelteKit" },
          { value: "solid-start", label: "SolidStart" },
          { value: "none", label: "None" }
        ]
      })
    ,
    mobile: async () =>
      await p.select({
        message: 'Pick a mobile framework.',
        options: [
          { value: "expo", label: "ReactNative + Expo" },
          { value: "none", label: "None" }
        ]
      })
    ,
    goprefix: () =>
      p.text({
        message: "What would you like to use as a go package prefix?",
        placeholder: "github.com/glstack-test",
        defaultValue: "github.com/glstack-test",
        validate: (value) => {
          return undefined
        },
      }),
    installDeps: async () => {
      return await p.confirm({message: "Install dependencies?", })
    }
  },
  {
    onCancel: () => {
      p.cancel("Operation cancelled.");
      process.exit(0);
    },
  }
);

const templateDir = (process.env.GLSTACK_DEV == 'true' ? './template' : path.join(import.meta.dir, '..', 'template'))
const createRenderer = initRenderer(templateDir)
const render = createRenderer(z.object({
  project: z.object({
    name: z.string(),
    goprefix: z.string(),
    frontend: z.string(),
    mobile: z.string()
  })
}))
const destDir = path.join("./", project.name);
render(destDir, { project }, { reverseMap: true })

const s = p.spinner();
if (project.installDeps) {
  s.start("Installing dependencies");
  await Bun.$`bun install`.cwd(path.join(destDir)).quiet();
  s.stop("Dependencies installed.");
}

p.outro("You're all set!");
