import { Clipboard, showHUD } from "@raycast/api";

function sleep(ms: number) {
    return new Promise((resolve) => setTimeout(resolve, ms));
}

function splitSequentialItems(text: string) {
    return text
        .replace(/\r\n/g, "\n")
        .split("\n")
        .map((item) => item.trim())
        .filter(Boolean);
}

async function setClipboard(text: string) {
    await Clipboard.copy(text);
    await sleep(120);
}

export default async function Command() {
    const clipboardText = await Clipboard.readText();

    if (!clipboardText?.trim()) {
        await showHUD("Clipboard is empty");
        return;
    }

    const items = splitSequentialItems(clipboardText);

    if (items.length === 0) {
        await showHUD("No copyable items found");
        return;
    }

    for (const item of items) {
        await setClipboard(item);
    }

    await showHUD(`Found ${items.length} lines, and converted them in ${items.length} separate instances`);
}
