#!/usr/bin/env node
import {spawn } from "child_process";
import { createWriteStream } from "fs";
import open from "open";
import { resolve, dirname } from "path";
import { fileURLToPath } from "url";

const init = () => {
    const args = process.argv.slice(2); 

    // console.log({args})

    const explainCommand = spawn("npm", ["explain", "--json", ...args], {stdio: "pipe"})
    const __dirname = dirname(fileURLToPath(import.meta.url));
    const outputPath = resolve(__dirname, 'build/output.json');

    // console.log({outputPath})

    const outputFile = createWriteStream(outputPath);
    explainCommand.stdout.pipe(outputFile)
    explainCommand.stderr.pipe(process.stderr);

    const packageRoot = resolve(__dirname); // Adjust if cli.js is nested

    explainCommand.on("close", () => {
        const startCommand = spawn("npm", ["run", "start"], { 
            stdio: ["overlapped", "pipe", "pipe"], shell: true,
            cwd: packageRoot
        })
        
        // console.log('running the start command');


        startCommand.stdout.on("data", (data) => {
            const str = data.toString()
            const site = str.match(/https?:\/\/[^\s/]+/)
            if(site) {
                console.log(`🚀 Explained on ${site[0]}.
🔴 CMD + C (CTRL + C on Windows) to stop the server.
                    `)
                open(site[0])
            }
        });

        startCommand.stdout.on("error", () => {
            console.log("some issue");
        })
    })
}

init()