import { z } from 'zod';
import { config } from '../../config.js';
import { detectProject, resolvePackage } from '../../lib/frameworks/detect.js';
import { resolveTarget } from '../../lib/frameworks/resolve.js';
import { processManager } from '../../lib/processManager.js';
import { errorResult, jsonResult, packageSchema, targetSchema, toErrorMessage } from '../shared.js';
export function registerStartDevServerTool(server) {
    server.registerTool('start_dev_server', {
        title: 'Start Dev Server',
        description: 'Start the project dev server as a tracked background process and wait for its ready signal. ' +
            'Laravel uses `vendor/bin/sail up` (or docker compose up) when Sail is present; otherwise php artisan serve / spark / Vite/CRA/Next. ' +
            'Returns a processId for get_process_logs/stop_process. Optional `package` scopes to a monorepo package.',
        inputSchema: {
            target: targetSchema,
            package: packageSchema,
            timeoutMs: z
                .number()
                .int()
                .positive()
                .optional()
                .describe('How long to wait for the ready signal before returning anyway. Defaults to 30s.'),
        },
    }, async ({ target, package: packageName, timeoutMs }) => {
        try {
            const root = packageName
                ? resolvePackage(config.workspaceRoot, packageName).pkg.absolutePath
                : config.workspaceRoot;
            const detected = detectProject(root);
            const { adapter, target: resolvedTarget } = resolveTarget(detected, target, 'frontend');
            const cmd = adapter.devCommand();
            const info = processManager.start({
                label: `dev-server:${adapter.kind}`,
                command: cmd.command,
                args: cmd.args,
                cwd: cmd.cwd,
            });
            const { matchedLine, timedOut } = await processManager.waitForLog(info.id, adapter.readyPattern(), timeoutMs ?? config.defaultReadyTimeoutMs);
            const urlMatch = matchedLine?.match(/https?:\/\/\S+/i);
            return jsonResult({
                processId: info.id,
                target: resolvedTarget,
                package: packageName ?? null,
                adapter: adapter.label,
                ready: Boolean(matchedLine),
                timedOut,
                readyLine: matchedLine,
                url: urlMatch ? urlMatch[0].replace(/[.,)\]]+$/, '') : null,
                hint: timedOut
                    ? 'No ready signal seen within the timeout; the server may still be starting (or failed). Check get_process_logs.'
                    : 'Use get_process_logs to tail output and stop_process to shut it down when done.',
            });
        }
        catch (error) {
            return errorResult(toErrorMessage(error));
        }
    });
}
//# sourceMappingURL=startDevServer.js.map