/**
 * Trace hooks — HTML export of session traces after each query.
 *
 * Always active (not dev-gated). The composition root (main.ts) calls
 * getTraceHooks() once and wires the returned hooks into the mode options.
 */
import { exec } from 'child_process';
import { basename } from 'path';
import { pathToFileURL } from 'url';
import { exportDevTraces, exportTraceArtifacts } from './trace-export.js';
import { packageTraceExports } from './trace-package.js';
import { uploadTraceShare } from './trace-share-upload.js';
/** Open the given local file in the user's default browser using the platform open command. */
function openInBrowser(filePath) {
    const targetUrl = `${pathToFileURL(filePath).href}?v=${Date.now()}`;
    const cmd = process.platform === 'win32'
        ? `start "" "${targetUrl}"`
        : process.platform === 'darwin'
            ? `open "${targetUrl}"`
            : `xdg-open "${targetUrl}"`;
    exec(cmd, () => { });
}
const TRACE_COMMAND_USAGE = 'Usage: /trace | /trace download | /trace share [team|public]';
/** Parse a `/trace ...` slash command into an action descriptor, or null if invalid. */
function parseTraceCommand(command) {
    const parts = command.trim().split(/\s+/);
    if (parts.length === 1 && parts[0] === '/trace')
        return { action: 'open' };
    if (parts.length === 2 && parts[0] === '/trace' && parts[1] === 'download') {
        return { action: 'download' };
    }
    if (parts[0] === '/trace' && parts[1] === 'share') {
        if (parts.length === 2)
            return { action: 'share', visibility: 'team' };
        if (parts.length === 3 && ['team', 'public'].includes(parts[2])) {
            return { action: 'share', visibility: parts[2] };
        }
    }
    return null;
}
/** Build the trace hooks (post-turn export and `/trace` command handler) used by the shell layer. */
export function getTraceHooks(session, options = {}) {
    const onAgentEnd = () => {
        void exportDevTraces(session)
            .then(() => { })
            .catch((err) => {
            console.debug('[dev] trace export failed:', err);
        });
    };
    const onCommand = (command, showStatus) => {
        const action = parseTraceCommand(command);
        if (!action) {
            const normalized = command.trim();
            if (normalized === '/trace' || normalized.startsWith('/trace ')) {
                showStatus(TRACE_COMMAND_USAGE);
                return true;
            }
            return false;
        }
        if (action.action === 'download') {
            showStatus('Exporting traces…');
            void exportDevTraces(session)
                .then((paths) => {
                if (paths.length === 0) {
                    showStatus('No traces to export');
                    return;
                }
                return packageTraceExports(paths)
                    .then((packagePath) => {
                    showStatus(`Created trace package: ${packagePath}`);
                })
                    .catch(() => {
                    showStatus('Trace packaging failed');
                });
            })
                .catch(() => {
                showStatus('Trace export failed');
            });
            return true;
        }
        if (action.action === 'share') {
            const accessToken = options.getAccessToken?.();
            if (!accessToken) {
                showStatus('Trace sharing requires Shortcut login');
                return true;
            }
            showStatus('Exporting traces…');
            void exportTraceArtifacts(session)
                .then((artifacts) => {
                if (artifacts.length === 0) {
                    showStatus('No traces to export');
                    return;
                }
                const rootArtifact = artifacts.find((artifact) => artifact.isRoot);
                const title = rootArtifact ? basename(rootArtifact.fileName, '.html') : 'Session Trace';
                return uploadTraceShare({
                    accessToken,
                    title,
                    visibility: action.visibility ?? 'team',
                    artifacts,
                    baseUrl: options.shareBaseUrl
                })
                    .then((result) => {
                    showStatus(`Trace share ready: ${result.rootHtmlDownloadUrl}`);
                })
                    .catch((error) => {
                    const detail = error instanceof Error ? error.message : String(error);
                    showStatus(`Trace share failed: ${detail}`);
                });
            })
                .catch(() => {
                showStatus('Trace export failed');
            });
            return true;
        }
        showStatus('Exporting traces…');
        void exportDevTraces(session)
            .then((paths) => {
            if (paths.length === 0) {
                showStatus('No traces to export');
                return;
            }
            for (const p of paths)
                openInBrowser(p);
            showStatus(`Opened ${paths.length} trace(s) in browser`);
        })
            .catch(() => {
            showStatus('Trace export failed');
        });
        return true;
    };
    return {
        onAgentEnd,
        onCommand
    };
}
//# sourceMappingURL=index.js.map