import { Input } from '@cliffy/prompt'
import type { Template } from '../types.ts'
import type { JSX } from 'preact'

const decoder = new TextDecoder()

export async function promptProps<
	Builder extends (props: Props) => JSX.Element,
	Props extends Record<string, unknown>,
>(template: Template<Builder, Props>): Promise<Props> {
	const props: Partial<Props> = {}

	for (const prop of template.props) {
		if (prop.multiline) {
			console.log(
				`%c?%c ${prop.description} %c[end input with "!EOF" on a new line] %c›`,
				'color: yellow;',
				'font-weight: bold',
				'color: white',
				'color: blue',
			)

			for await (const chunk of Deno.stdin.readable) {
				const text = decoder.decode(chunk)
				if ((/^!EOF\r?\n$/.test(text))) {
					break
				}
				//@ts-ignore TODO fix type inference
				props[prop.tag] += text
			}

			//@ts-ignore TODO fix type inference
			if (props[prop.tag].startsWith('undefined')) {
				//@ts-ignore TODO fix type inference
				props[prop.tag] = props[prop.tag].slice('undefined'.length)
			}
		} else {
			const value = await Input.prompt({
				message: prop.description,
			})

			//@ts-ignore TODO fix type inference
			props[prop.tag] = value
		}
	}

	return props as Props
}