import { existsSync } from 'node:fs';
import { detectDesktopEnv, hasDesktopDisplay, printDesktopEnvStatus, printLinuxVirtualDisplayHint } from './desktop-env.js';
import { BROWSER_USE_GUIDE, REMOTE_BROWSER_GUIDE } from './guides.js';
import { ensureLinuxVirtualDisplay } from './linux-virtual-display.js';
import { getToolPythonRuntimePaths, installToolPythonRuntime, runInheritedCommand, printToolPythonRuntimeDoctor, removeToolPythonRuntime, } from './python-runtime.js';
const MAX_AGENT_CONTEXT_SNIPPET_LENGTH = 480;
const INSTALLED_TOOLS_CONTEXT_PATH = '.pibo/context/installed-pibo-tools.md';
const REGISTRY = [
    {
        name: 'browser-use',
        description: 'Browser automation CLI for web interaction, screenshots, and extraction.',
        runtime: {
            packageName: 'browser-use[cli]==0.12.6',
            executableName: 'browser-use',
            pythonVersion: '3.12',
            homeEnvVar: 'BROWSER_USE_HOME',
        },
        guides: [BROWSER_USE_GUIDE, REMOTE_BROWSER_GUIDE],
        notes: [
            'Installed on demand into an isolated Python virtual environment.',
            'Pinned to browser-use 0.12.6 so the CLI surface matches the bundled guides.',
            'The tool uses BROWSER_USE_HOME under the pibo tool runtime directory.',
            'The pibo tool environment wraps browser-use so new browser sessions default to Pibo-managed persistent PIBo Chrome via CDP; pass --fresh-profile for a temporary profile.',
            'Use pibo tools browser-use lease acquire for isolated authenticated browser slots when multiple agents need Chat Web App access.',
            'Guides are available through pibo tools guide and are not loaded into pibo profiles automatically.',
        ],
        agentContextSnippet: [
            'Browser automation CLI for frontend development and web testing.',
            'Start in one persistent shell with `eval "$(npm run --silent dev -- tools env browser-use)"`.',
            'For authenticated Pibo Chat Web App testing, prefer `eval "$(npm run --silent dev -- tools browser-use lease acquire --app pibo-chat --owner "$USER")"`.',
            'Discover details with `npm run dev -- tools show browser-use` and `npm run dev -- tools guide browser-use browser-use`.',
        ].join('\n'),
    },
];
for (const entry of REGISTRY) {
    const snippet = entry.agentContextSnippet.trim();
    if (snippet.length === 0) {
        throw new Error(`CLI tool "${entry.name}" is missing agentContextSnippet`);
    }
    if (snippet.length > MAX_AGENT_CONTEXT_SNIPPET_LENGTH) {
        throw new Error(`CLI tool "${entry.name}" agentContextSnippet exceeds ${MAX_AGENT_CONTEXT_SNIPPET_LENGTH} characters`);
    }
}
export function listCliToolEntries() {
    return REGISTRY;
}
export function findCliToolEntry(name) {
    return REGISTRY.find((entry) => entry.name === name);
}
export function getCliToolStatus(entry) {
    const paths = getToolPythonRuntimePaths(entry.name, entry.runtime);
    return {
        entry,
        installed: existsSync(paths.executablePath),
        executablePath: paths.executablePath,
        rootDir: paths.rootDir,
        homeDir: paths.homeDir,
    };
}
export function findToolGuide(entry, guideName) {
    return entry.guides.find((guide) => guide.name === guideName);
}
export function listInstalledCliToolAgentContexts() {
    return REGISTRY
        .filter((entry) => getCliToolStatus(entry).installed)
        .map((entry) => ({
        name: entry.name,
        description: entry.description,
        snippet: entry.agentContextSnippet,
    }));
}
export function getInstalledCliToolContextFile() {
    const installedEntries = listInstalledCliToolAgentContexts();
    if (installedEntries.length === 0)
        return undefined;
    const sections = installedEntries.flatMap((entry) => [
        `## ${entry.name}`,
        entry.snippet,
        '',
    ]);
    return {
        path: INSTALLED_TOOLS_CONTEXT_PATH,
        content: [
            '# Installed Pibo Tools',
            '',
            'These curated CLI tools are installed in this environment. The CLI remains the source of truth; use the referenced commands to discover each workflow step by step.',
            '',
            ...sections,
        ].join('\n').trimEnd(),
    };
}
export async function installCliTool(entry, runSetup) {
    if (runSetup) {
        if (entry.name === 'browser-use') {
            await ensureLinuxVirtualDisplay({ runInherited: runInheritedCommand });
        }
        await installToolPythonRuntime(entry.name, entry.runtime);
    }
    const status = getCliToolStatus(entry);
    console.log(`${runSetup ? 'Installed' : 'Install target'} ${entry.name}`);
    console.log(`  executable: ${status.executablePath}`);
    console.log(`  home: ${status.homeDir}`);
    printDesktopEnvStatus('  ');
    if (entry.name === 'browser-use' && process.platform === 'linux' && !hasDesktopDisplay(detectDesktopEnv())) {
        printLinuxVirtualDisplayHint('  ');
    }
    console.log(`  env: pibo tools env ${entry.name}`);
}
export async function removeCliTool(entry) {
    await removeToolPythonRuntime(entry.name, entry.runtime);
}
export async function doctorCliTool(entry) {
    await printToolPythonRuntimeDoctor(entry.name, entry.runtime);
}
