import { postJSON } from './http.js';
import { SkimlyError } from './errors.js';
import { sha256Hex, cacheGetBlobId, cacheSetBlobId } from './utils.js';
export * from './types.js';
export * from './verify.js';
export class SkimlyClient {
    constructor(opts) {
        const base = (opts.base ?? 'http://localhost:3000').replace(/\/$/, '');
        if (!opts.key)
            throw new SkimlyError('SKIMLY key required', 401);
        this.http = {
            base,
            key: opts.key,
            timeoutMs: opts.timeoutMs ?? 30000,
            retries: opts.retries ?? 2,
        };
    }
    /** Upload large context once; returns { blob_id } */
    async createBlob(content, mime_type = 'text/plain') {
        return postJSON('/api/blobs', { content, mime_type }, this.http);
    }
    /** In-process dedupe: avoid re-uploading identical content this process has already sent */
    async createBlobIfNew(content, mime_type = 'text/plain') {
        const hash = sha256Hex(content);
        const cached = cacheGetBlobId(hash);
        if (cached)
            return { blob_id: cached };
        const res = await this.createBlob(content, mime_type);
        cacheSetBlobId(hash, res.blob_id);
        return res;
    }
    /** Chat with provider; messages may be string or array of parts ({type:'text'|'pointer', ...}) */
    async chat(req) {
        return postJSON('/api/chat', req, this.http);
    }
}
export function fromEnv() {
    const base = process.env.SKIMLY_BASE || 'http://localhost:3000';
    const key = process.env.SKIMLY_KEY;
    if (!key)
        throw new SkimlyError('SKIMLY_KEY missing', 401);
    return new SkimlyClient({ base, key });
}
