import { readFileSync } from 'fs';
import { SHORTCUT_API_URL } from '../../constants.js';
import { SHORTCUT_API_ENDPOINTS } from '../../endpoints.js';
export async function uploadTraceShare(params) {
    const baseUrl = params.baseUrl ?? SHORTCUT_API_URL;
    const rootArtifact = params.artifacts.find((artifact) => artifact.isRoot);
    if (!rootArtifact) {
        throw new Error('Root trace artifact is required');
    }
    const files = params.artifacts.flatMap((artifact) => {
        const htmlFile = {
            fileName: artifact.fileName,
            content: readFileSync(artifact.htmlPath, 'utf-8'),
            contentType: 'text/html'
        };
        if (!artifact.jsonlPath)
            return [htmlFile];
        return [
            htmlFile,
            {
                fileName: artifact.fileName.replace(/\.html$/i, '.jsonl'),
                content: readFileSync(artifact.jsonlPath, 'utf-8'),
                contentType: 'application/x-ndjson'
            }
        ];
    });
    const rootJsonlFileName = rootArtifact.jsonlPath
        ? rootArtifact.fileName.replace(/\.html$/i, '.jsonl')
        : null;
    const response = await fetch(`${baseUrl}${SHORTCUT_API_ENDPOINTS.traceShares}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${params.accessToken}`
        },
        body: JSON.stringify({
            title: params.title,
            visibility: params.visibility,
            rootHtmlFileName: rootArtifact.fileName,
            rootJsonlFileName,
            files
        })
    });
    const data = (await response.json().catch(() => null));
    if (!response.ok || !data?.rootHtmlDownloadUrl) {
        throw new Error(data?.error || `Trace share upload failed with status ${response.status}`);
    }
    return {
        rootHtmlDownloadUrl: new URL(data.rootHtmlDownloadUrl, `${baseUrl}/`).toString()
    };
}
//# sourceMappingURL=trace-share-upload.js.map