import { spawn } from 'node:child_process';
import { resolve, dirname, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
import { existsSync } from 'node:fs';
import pc from 'picocolors';
import { intro, note } from '@clack/prompts';
export async function runDev(opts = {}) {
    intro(pc.bgGreen(pc.black(' seo-toolkit dev ')));
    const port = opts.port ?? '4001';
    const __dirname = dirname(fileURLToPath(import.meta.url));
    // packages/cli/dist/commands → packages/cli
    const cliRoot = resolve(__dirname, '../..');
    // Standalone build (npm install): server.js lives inside the monorepo-structured standalone output
    const standaloneServer = resolve(cliRoot, 'dashboard-dist/packages/dashboard/server.js');
    // Monorepo fallback (development): packages/dashboard/
    const monorepoPath = resolve(cliRoot, '../dashboard');
    note(`Starting dashboard on ${pc.cyan(`http://localhost:${port}`)}\n` +
        `Reading from: ${pc.dim('.seo-toolkit/audit-report.json')}`, 'Dashboard');
    const projectCwd = process.cwd();
    const cliDistPath = resolve(cliRoot, 'dist/index.js');
    const env = {
        ...process.env,
        PORT: port,
        HOSTNAME: '0.0.0.0',
        SEO_TOOLKIT_CWD: projectCwd,
        // Tells API routes where the CLI binary is — works for both npm install and monorepo
        SEO_TOOLKIT_CLI_PATH: cliDistPath,
    };
    if (existsSync(standaloneServer)) {
        // ── Installed via npm: serve pre-built standalone Next.js server ──────
        // node_modules were renamed to _nm during bundling to survive npm publish.
        // Point NODE_PATH at both locations so require('next') etc. resolve correctly.
        const serverDir = dirname(standaloneServer);
        const nmPaths = [
            resolve(serverDir, '../../_nm'), // standalone root _nm
            resolve(serverDir, '_nm'), // dashboard-level _nm
        ].filter(existsSync);
        const nodePath = nmPaths.join(sep === '\\' ? ';' : ':');
        const child = spawn('node', [standaloneServer], {
            cwd: serverDir,
            stdio: 'inherit',
            env: { ...env, ...(nodePath && { NODE_PATH: nodePath }) },
        });
        child.on('exit', (code) => process.exit(code ?? 0));
    }
    else if (existsSync(monorepoPath)) {
        // ── Monorepo: run Next.js dev server ─────────────────────────────────
        const child = spawn('pnpm', ['dev', '--port', port], {
            cwd: monorepoPath,
            stdio: 'inherit',
            env,
        });
        child.on('exit', (code) => process.exit(code ?? 0));
    }
    else {
        console.error(pc.red('Dashboard not found.'));
        console.error('Run `pnpm build:dashboard-standalone` to build it, or clone the full repo.');
        process.exit(1);
    }
}
//# sourceMappingURL=dev.js.map