#!/usr/bin/env node
'use strict';

var React = require('react');
var ink = require('ink');
var commander = require('commander');
var path = require('node:path');
var promises = require('node:fs/promises');
var useImmer = require('use-immer');
var useStdOutDimensions = require('ink-use-stdout-dimensions');
var Gradient = require('ink-gradient');
var figlet = require('figlet');
var produce = require('immer');
var TextInput = require('ink-text-input');
var crypto = require('crypto');
var simpleGit = require('simple-git');
var Spinner = require('ink-spinner');
var SyntaxHighlight = require('ink-syntax-highlight');
var lookpath = require('lookpath');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
var useStdOutDimensions__default = /*#__PURE__*/_interopDefaultLegacy(useStdOutDimensions);
var Gradient__default = /*#__PURE__*/_interopDefaultLegacy(Gradient);
var figlet__default = /*#__PURE__*/_interopDefaultLegacy(figlet);
var produce__default = /*#__PURE__*/_interopDefaultLegacy(produce);
var TextInput__default = /*#__PURE__*/_interopDefaultLegacy(TextInput);
var crypto__default = /*#__PURE__*/_interopDefaultLegacy(crypto);
var simpleGit__default = /*#__PURE__*/_interopDefaultLegacy(simpleGit);
var Spinner__default = /*#__PURE__*/_interopDefaultLegacy(Spinner);
var SyntaxHighlight__default = /*#__PURE__*/_interopDefaultLegacy(SyntaxHighlight);

var __defProp$3 = Object.defineProperty;
var __defProps$2 = Object.defineProperties;
var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues$3 = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp$3.call(b, prop))
      __defNormalProp$3(a, prop, b[prop]);
  if (__getOwnPropSymbols$3)
    for (var prop of __getOwnPropSymbols$3(b)) {
      if (__propIsEnum$3.call(b, prop))
        __defNormalProp$3(a, prop, b[prop]);
    }
  return a;
};
var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
var __objRest$2 = (source, exclude) => {
  var target = {};
  for (var prop in source)
    if (__hasOwnProp$3.call(source, prop) && exclude.indexOf(prop) < 0)
      target[prop] = source[prop];
  if (source != null && __getOwnPropSymbols$3)
    for (var prop of __getOwnPropSymbols$3(source)) {
      if (exclude.indexOf(prop) < 0 && __propIsEnum$3.call(source, prop))
        target[prop] = source[prop];
    }
  return target;
};
const FullScreenBox = React__default["default"].forwardRef(function FullScreenBox2(_a, ref) {
  var _b = _a, { children } = _b, props = __objRest$2(_b, ["children"]);
  const [width, height] = useStdOutDimensions__default["default"]();
  return (
    // eslint-disable-next-line react/jsx-props-no-spreading
    /* @__PURE__ */ React__default["default"].createElement(ink.Box, __spreadProps$2(__spreadValues$3({ width: Math.min(width, 150), height: Math.min(height - 1, 50) }, props), { ref }), children)
  );
});

const banner = figlet__default["default"].textSync("Learn Card", "Big Money-ne");
const Banner = () => {
  return /* @__PURE__ */ React__default["default"].createElement(ink.Box, { marginBottom: 4 }, /* @__PURE__ */ React__default["default"].createElement(Gradient__default["default"], { colors: ["cyan", "green"] }, /* @__PURE__ */ React__default["default"].createElement(ink.Text, null, banner)));
};

var __defProp$2 = Object.defineProperty;
var __defProps$1 = Object.defineProperties;
var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues$2 = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp$2.call(b, prop))
      __defNormalProp$2(a, prop, b[prop]);
  if (__getOwnPropSymbols$2)
    for (var prop of __getOwnPropSymbols$2(b)) {
      if (__propIsEnum$2.call(b, prop))
        __defNormalProp$2(a, prop, b[prop]);
    }
  return a;
};
var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
function innerImmerOuterImmer(setState, field, value) {
  if (value === void 0) {
    return (innerValue) => {
      setState((oldState) => {
        if (innerValue instanceof Function) innerValue(oldState[field]);
        else oldState[field] = innerValue;
      });
    };
  }
  setState((oldState) => {
    if (value instanceof Function) value(oldState[field]);
    else oldState[field] = value;
  });
}
const curriedInnerImmerOuterImmer = (setState) => (field, value) => innerImmerOuterImmer(setState, field, value);
function innerReactOuterImmer(setState, field, value) {
  if (value === void 0) {
    return (innerValue) => {
      setState((oldState) => {
        if (innerValue instanceof Function) innerValue(oldState[field]);
        else oldState[field] = innerValue;
      });
    };
  }
  setState((oldState) => {
    oldState[field] = typeof value === "function" ? value(oldState[field]) : value;
  });
}
const curriedInnerReactOuterImmer = (setState) => (field, value) => innerReactOuterImmer(setState, field, value);
function innerImmerOuterReact(setState, field, value) {
  if (value === void 0) {
    return (innerValue) => {
      if (innerValue instanceof Function) {
        setState(produce__default["default"]((oldState) => innerValue(oldState[field])));
      } else setState((oldState) => __spreadProps$1(__spreadValues$2({}, oldState), { [field]: innerValue }));
    };
  }
  if (value instanceof Function) {
    setState(produce__default["default"]((oldState) => value(oldState[field])));
  } else setState((oldState) => __spreadProps$1(__spreadValues$2({}, oldState), { [field]: value }));
}
const curriedInnerImmerOuterReact = (setState) => (field, value) => innerImmerOuterReact(setState, field, value);
function innerReactOuterReact(setState, field, value) {
  if (value === void 0) {
    return (innerValue) => {
      setState((oldState) => __spreadProps$1(__spreadValues$2({}, oldState), {
        [field]: innerValue instanceof Function ? innerValue(oldState[field]) : innerValue
      }));
    };
  }
  setState((oldState) => __spreadProps$1(__spreadValues$2({}, oldState), {
    [field]: value instanceof Function ? value(oldState[field]) : value
  }));
}
const curriedInnerReactOuterReact = (setState) => (field, value) => innerReactOuterReact(setState, field, value);
function curriedStateSlice(setState, options) {
  var _a, _b, _c;
  if (((_a = options == null ? void 0 : options.outer) != null ? _a : "immer") === "immer") {
    return ((_b = options == null ? void 0 : options.inner) != null ? _b : "immer") === "immer" ? curriedInnerImmerOuterImmer(setState) : curriedInnerReactOuterImmer(setState);
  }
  return ((_c = options == null ? void 0 : options.inner) != null ? _c : "immer") === "immer" ? curriedInnerImmerOuterReact(setState) : curriedInnerReactOuterReact(setState);
}

var __defProp$1 = Object.defineProperty;
var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues$1 = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp$1.call(b, prop))
      __defNormalProp$1(a, prop, b[prop]);
  if (__getOwnPropSymbols$1)
    for (var prop of __getOwnPropSymbols$1(b)) {
      if (__propIsEnum$1.call(b, prop))
        __defNormalProp$1(a, prop, b[prop]);
    }
  return a;
};
var __objRest$1 = (source, exclude) => {
  var target = {};
  for (var prop in source)
    if (__hasOwnProp$1.call(source, prop) && exclude.indexOf(prop) < 0)
      target[prop] = source[prop];
  if (source != null && __getOwnPropSymbols$1)
    for (var prop of __getOwnPropSymbols$1(source)) {
      if (exclude.indexOf(prop) < 0 && __propIsEnum$1.call(source, prop))
        target[prop] = source[prop];
    }
  return target;
};
const Input = React__default["default"].forwardRef(function Input2(_a, ref) {
  var _b = _a, { disabled = false, autoFocus = false, focusId, prompt, value, onChange, onSubmit } = _b, props = __objRest$1(_b, ["disabled", "autoFocus", "focusId", "prompt", "value", "onChange", "onSubmit"]);
  const { isFocused } = ink.useFocus({ autoFocus, id: focusId, isActive: !disabled });
  return (
    // eslint-disable-next-line react/jsx-props-no-spreading
    /* @__PURE__ */ React__default["default"].createElement(ink.Box, __spreadValues$1({ ref }, props), /* @__PURE__ */ React__default["default"].createElement(ink.Box, { marginRight: 1 }, /* @__PURE__ */ React__default["default"].createElement(ink.Text, { color: "blueBright" }, prompt)), /* @__PURE__ */ React__default["default"].createElement(TextInput__default["default"], { value, onChange, focus: isFocused, onSubmit }))
  );
});

var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp.call(b, prop))
      __defNormalProp(a, prop, b[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b)) {
      if (__propIsEnum.call(b, prop))
        __defNormalProp(a, prop, b[prop]);
    }
  return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __objRest = (source, exclude) => {
  var target = {};
  for (var prop in source)
    if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
      target[prop] = source[prop];
  if (source != null && __getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(source)) {
      if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
        target[prop] = source[prop];
    }
  return target;
};
const RawButton = React__default["default"].forwardRef(function RawButton2(_a, ref) {
  var _b = _a, { children, autoFocus = false, focusId, focusedProps = {}, onClick } = _b, props = __objRest(_b, ["children", "autoFocus", "focusId", "focusedProps", "onClick"]);
  const { focusPrevious, focusNext } = ink.useFocusManager();
  const { isFocused } = ink.useFocus({ autoFocus, id: focusId });
  ink.useInput((input, key) => {
    if (isFocused) {
      if (key.leftArrow || key.upArrow || input === "h" || input === "k") focusPrevious();
      if (key.rightArrow || key.downArrow || input === "l" || input === "j") focusNext();
      if (key.return || input === " ") onClick();
    }
  });
  return (
    // eslint-disable-next-line react/jsx-props-no-spreading
    /* @__PURE__ */ React__default["default"].createElement(ink.Box, __spreadValues(__spreadProps(__spreadValues({}, props), { ref }), isFocused ? focusedProps : {}), children)
  );
});
const Button = React__default["default"].forwardRef(function Button2(_c, ref) {
  var _d = _c, { children } = _d, props = __objRest(_d, ["children"]);
  return /* @__PURE__ */ React__default["default"].createElement(
    RawButton,
    __spreadProps(__spreadValues({
      height: 3,
      width: 15,
      borderStyle: "round",
      justifyContent: "center",
      alignItems: "center",
      focusedProps: {
        borderColor: "cyan"
      }
    }, props), {
      ref
    }),
    /* @__PURE__ */ React__default["default"].createElement(ink.Text, null, children)
  );
});

const generateRandomSeed = () => crypto__default["default"].randomBytes(32).toString("hex");

const Form = ({ state, setState, onSubmit, onCancel }) => {
  const { focus } = ink.useFocusManager();
  const updateSlice = curriedStateSlice(setState);
  return /* @__PURE__ */ React__default["default"].createElement(
    ink.Box,
    {
      flexGrow: 1,
      flexDirection: "column",
      padding: 2,
      borderStyle: "round",
      borderColor: "yellow"
    },
    /* @__PURE__ */ React__default["default"].createElement(ink.Box, { flexGrow: 1, flexDirection: "column", alignItems: "center" }, /* @__PURE__ */ React__default["default"].createElement(ink.Box, { marginBottom: 2, padding: 1, flexDirection: "column", borderStyle: "round" }, /* @__PURE__ */ React__default["default"].createElement(
      Input,
      {
        disabled: true,
        focusId: "name",
        prompt: "Name:",
        value: state.name,
        onChange: updateSlice("name"),
        onSubmit: () => focus("editName")
      }
    ), /* @__PURE__ */ React__default["default"].createElement(
      Input,
      {
        marginTop: 1,
        disabled: true,
        focusId: "seed",
        prompt: "Seed:",
        value: state.seed,
        onChange: updateSlice("seed"),
        onSubmit: () => focus("editSeed")
      }
    )), /* @__PURE__ */ React__default["default"].createElement(Button, { autoFocus: true, focusId: "editName", onClick: () => focus("name"), width: 25 }, "Edit Name"), /* @__PURE__ */ React__default["default"].createElement(Button, { onClick: () => updateSlice("seed", generateRandomSeed()), width: 25 }, "Generate Random Seed"), /* @__PURE__ */ React__default["default"].createElement(
      Button,
      {
        focusId: "editSeed",
        onClick: () => {
          updateSlice("seed", "");
          focus("seed");
        },
        width: 25
      },
      "Enter Custom Seed"
    )),
    /* @__PURE__ */ React__default["default"].createElement(ink.Box, { height: 5, width: "100%", padding: 2, justifyContent: "space-between" }, /* @__PURE__ */ React__default["default"].createElement(Button, { onClick: onSubmit }, "Ok"), /* @__PURE__ */ React__default["default"].createElement(Button, { onClick: onCancel }, "Cancel"))
  );
};

const git = simpleGit__default["default"]();
const Cloning = ({ path, onFinished }) => {
  const app = ink.useApp();
  React.useEffect(() => {
    git.clone("https://github.com/TaylorBeeston/LCHTTPTest", path, ["-q"]).then(onFinished).catch((error) => {
      app.exit();
      console.error(error);
    });
  }, []);
  return /* @__PURE__ */ React__default["default"].createElement(
    ink.Box,
    {
      flexGrow: 1,
      flexDirection: "column",
      justifyContent: "center",
      alignItems: "center",
      padding: 2,
      borderStyle: "round",
      borderColor: "yellow"
    },
    /* @__PURE__ */ React__default["default"].createElement(Gradient__default["default"], { name: "rainbow" }, /* @__PURE__ */ React__default["default"].createElement(ink.Text, null, /* @__PURE__ */ React__default["default"].createElement(Spinner__default["default"], { type: "material" }))),
    /* @__PURE__ */ React__default["default"].createElement(ink.Text, null, "Cloning into ", path, "..."),
    /* @__PURE__ */ React__default["default"].createElement(Gradient__default["default"], { name: "rainbow" }, /* @__PURE__ */ React__default["default"].createElement(ink.Text, null, /* @__PURE__ */ React__default["default"].createElement(Spinner__default["default"], { type: "material" })))
  );
};

const Info = ({ path }) => {
  const [pnpm, setPnpm] = React.useState(true);
  const [aws, setAws] = React.useState(true);
  React.useEffect(() => {
    const checkForBinaries = async () => {
      setPnpm(!!await lookpath.lookpath("pnpm"));
      setAws(!!await lookpath.lookpath("aws"));
    };
    checkForBinaries();
  }, []);
  return /* @__PURE__ */ React__default["default"].createElement(
    ink.Box,
    {
      flexGrow: 1,
      flexDirection: "column",
      justifyContent: "center",
      alignItems: "center",
      padding: 2,
      borderStyle: "round",
      borderColor: "yellow"
    },
    /* @__PURE__ */ React__default["default"].createElement(ink.Text, null, "Success!"),
    /* @__PURE__ */ React__default["default"].createElement(ink.Text, null, "Your new Learn Card HTTP Bridge is ready to deploy!"),
    aws ? /* @__PURE__ */ React__default["default"].createElement(ink.Text, null, "To deploy, run the following commands:") : /* @__PURE__ */ React__default["default"].createElement(React__default["default"].Fragment, null, /* @__PURE__ */ React__default["default"].createElement(ink.Text, null, "It looks like you might not have serverless/AWS set up yet!"), /* @__PURE__ */ React__default["default"].createElement(ink.Text, null, "Please review the instructions at https://www.serverless.com/framework/docs/tutorial if you have any issues deploying the Learn Card HTTP Bridge!"), /* @__PURE__ */ React__default["default"].createElement(ink.Text, null, "After you're all set up, run the following commands to deploy the Learn Card HTTP Bridge!")),
    /* @__PURE__ */ React__default["default"].createElement(ink.Box, { borderStyle: "round", flexDirection: "column" }, !pnpm && /* @__PURE__ */ React__default["default"].createElement(ink.Text, null, /* @__PURE__ */ React__default["default"].createElement(ink.Text, { color: "green" }, "$ "), /* @__PURE__ */ React__default["default"].createElement(SyntaxHighlight__default["default"], { code: "npm i -g pnpm # must use pnpm!", language: "bash" })), /* @__PURE__ */ React__default["default"].createElement(ink.Text, null, /* @__PURE__ */ React__default["default"].createElement(ink.Text, { color: "green" }, "$ "), /* @__PURE__ */ React__default["default"].createElement(
      SyntaxHighlight__default["default"],
      {
        code: `cd ${path}/packages/learn-card-bridge-http`,
        language: "bash"
      }
    )), /* @__PURE__ */ React__default["default"].createElement(ink.Text, null, /* @__PURE__ */ React__default["default"].createElement(ink.Text, { color: "green" }, "$ "), /* @__PURE__ */ React__default["default"].createElement(SyntaxHighlight__default["default"], { code: "pnpm i", language: "bash" })), /* @__PURE__ */ React__default["default"].createElement(ink.Text, null, /* @__PURE__ */ React__default["default"].createElement(ink.Text, { color: "green" }, "$ "), /* @__PURE__ */ React__default["default"].createElement(SyntaxHighlight__default["default"], { code: "pnpm serverless-deploy", language: "bash" })))
  );
};

const randomSeed = generateRandomSeed();
const App = ({ name = "LearnCardHTTPBridge" }) => {
  const app = ink.useApp();
  const [step, setStep] = React.useState("form");
  const [state, setState] = useImmer.useImmer({
    name,
    seed: randomSeed
  });
  const postClone = async () => {
    await promises.writeFile(
      path__default["default"].join(process.cwd(), `${state.name}/packages/learn-card-bridge-http`, ".env"),
      `WALLET_SEED=${state.seed}`
    );
    setStep("info");
  };
  const COMPONENTS = {
    form: /* @__PURE__ */ React__default["default"].createElement(
      Form,
      {
        state,
        setState,
        onSubmit: () => setStep("cloning"),
        onCancel: () => app.exit()
      }
    ),
    cloning: /* @__PURE__ */ React__default["default"].createElement(Cloning, { path: state.name, onFinished: postClone }),
    info: /* @__PURE__ */ React__default["default"].createElement(Info, { path: state.name })
  };
  return /* @__PURE__ */ React__default["default"].createElement(
    FullScreenBox,
    {
      flexDirection: "column",
      justifyContent: "center",
      alignItems: "center",
      borderStyle: "double",
      borderColor: "green"
    },
    /* @__PURE__ */ React__default["default"].createElement(ink.Box, { flexDirection: "column", padding: 2, height: "100%" }, /* @__PURE__ */ React__default["default"].createElement(Banner, null), COMPONENTS[step])
  );
};

var name = "@learncard/create-http-bridge";
var version = "1.1.166";
var description = "Instantly create and deploy a Learn Card Bridge HTTP API via AWS Lambda!";
var main = "dist/index.js";
var bin = "dist/index.js";
var scripts = {
	"serverless-deploy": "shx cp ../learn-card-core/src/didkit/pkg/didkit_wasm_bg.wasm src/didkit_wasm_bg.wasm && serverless deploy",
	start: "rollup -c && node dist/index.js",
	build: "rollup -c"
};
var author = "Learning Economy Foundation (www.learningeconomy.io)";
var license = "MIT";
var dependencies = {
	"@learncard/init": "workspace:*",
	"@learncard/types": "workspace:*",
	"@rollup/plugin-json": "^4.1.0",
	commander: "^9.3.0",
	cors: "^2.8.5",
	express: "~4.21.0",
	figlet: "^1.5.2",
	immer: "^9.0.15",
	ink: "^3.2.0",
	"ink-gradient": "^2.0.0",
	"ink-spinner": "^4.0.3",
	"ink-syntax-highlight": "^1.0.1",
	"ink-text-input": "^4.0.3",
	"ink-use-stdout-dimensions": "^1.0.5",
	inquirer: "^8.2.4",
	lookpath: "^1.2.2",
	react: "^18.2.0",
	rollup: "^2.71.1",
	"rollup-plugin-esbuild": "^4.9.1",
	"serverless-esbuild": "^1.25.0",
	"serverless-http": "^3.0.1",
	"serverless-plugin-warmup": "^8.1.0",
	"simple-git": "^3.9.0",
	"use-immer": "^0.7.0"
};
var devDependencies = {
	"@types/aws-lambda": "^8.10.106",
	"@types/cors": "^2.8.12",
	"@types/express": "^4.17.13",
	"@types/figlet": "^1.5.4",
	"@types/ink-gradient": "^2.0.1",
	"@types/inquirer": "^8.2.1",
	"@types/node": "^18.0.0",
	"@types/react": "^17.0.2",
	nodemon: "^2.0.16",
	"serverless-plugin-typescript": "^2.1.0",
	shx: "^0.3.4",
	"ts-node": "^10.8.1"
};
var packageJson = {
	name: name,
	version: version,
	description: description,
	main: main,
	bin: bin,
	scripts: scripts,
	author: author,
	license: license,
	dependencies: dependencies,
	devDependencies: devDependencies
};

commander.program.version(packageJson.version).argument("[name]").action(async (name) => {
  console.clear();
  ink.render(/* @__PURE__ */ React__default["default"].createElement(App, { name }));
}).parse(process.argv);
