#!/usr/bin/env ts-node

import * as dotenv from 'dotenv';

dotenv.config({ path: '.env' });

import colors from 'colors';
import OpenAI from 'openai';
import { join } from 'path';

if (process.cwd() !== join(__dirname, '../..')) {
    console.error(colors.red(`CWD must be root of the project`));
    process.exit(1);
}

playground()
    .catch((error) => {
        console.error(colors.bgRed(error.name || 'NamelessError'));
        console.error(error);
        process.exit(1);
    })
    .then(() => {
        process.exit(0);
    });

async function playground() {
    console.info(`🧸  Playground`);

    // Do here stuff you want to test
    //========================================>

    const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

    const stream = await openai.chat.completions.create({
        // model: 'gpt-4o-mini',
        model: 'gpt-4.1',
        messages: [
            {
                role: 'system',
                content: 'You are a Pavol Hejný, author of Promptbook',
            },
            {
                role: 'user',
                content: 'Who are you?',
            },
        ],
        temperature: 0.7,
        top_p: 0.9,
        stream: true,
    });

    let fullResponse = '';
    for await (const chunk of stream) {
        const content = chunk.choices[0]?.delta?.content || '';
        fullResponse += content;

        // process.stdout.clearLine(0);
        process.stdout.cursorTo(0);
        process.stdout.write(colors.grey(fullResponse));
    }

    console.info('\n---\n');
    console.info(colors.green(fullResponse));

    //========================================/
}

/** Note: [⚫] Code for archived playground [playground-openai-streaming.ts](src/playground/backup/playground-openai-streaming.ts.txt) should never be published in any package */
