export class PlatformClient {
    baseUrl;
    token;
    constructor(creds) {
        this.baseUrl = creds.platformUrl.replace(/\/+$/, '');
        this.token = creds.token;
    }
    async fetch(path, opts = {}) {
        const isApiKey = this.token.startsWith('fw_');
        const headers = {
            'Content-Type': 'application/json',
            ...(isApiKey
                ? { 'X-API-Key': this.token }
                : { Authorization: `Bearer ${this.token}` }),
            ...(opts.headers ?? {}),
        };
        return fetch(`${this.baseUrl}${path}`, { ...opts, headers });
    }
    // Auth
    async getUser() {
        const resp = await this.fetch('/auth/me');
        if (!resp.ok)
            throw new Error(`Auth failed: ${resp.status}`);
        const data = await resp.json();
        return data.user;
    }
    // Workflows
    async pushWorkflow(name, source) {
        // Try update first, then create
        const slug = name.toLowerCase().replace(/[^a-z0-9-]/g, '-').replace(/-+/g, '-');
        let resp = await this.fetch(`/workflows/${slug}`, {
            method: 'PUT',
            body: JSON.stringify({ source, name }),
        });
        if (resp.status === 404) {
            resp = await this.fetch('/workflows', {
                method: 'POST',
                body: JSON.stringify({ source, name }),
            });
        }
        if (!resp.ok) {
            const err = await resp.json().catch(() => ({ error: resp.statusText }));
            throw new Error(err.error ?? `Push failed: ${resp.status}`);
        }
        const data = await resp.json();
        return data.workflow;
    }
    async deploy(slug) {
        const resp = await this.fetch(`/workflows/${slug}/deploy`, { method: 'POST' });
        if (!resp.ok) {
            const err = await resp.json().catch(() => ({ error: resp.statusText }));
            throw new Error(err.error ?? `Deploy failed: ${resp.status}`);
        }
        const data = await resp.json();
        return data.deployment;
    }
    async undeploy(slug) {
        const resp = await this.fetch(`/deployments/${slug}`, { method: 'DELETE' });
        if (!resp.ok && resp.status !== 404)
            throw new Error(`Undeploy failed: ${resp.status}`);
    }
    async listDeployments() {
        const resp = await this.fetch('/deployments');
        if (!resp.ok)
            throw new Error(`List failed: ${resp.status}`);
        const data = await resp.json();
        return data.deployments;
    }
    // Usage
    async getUsage() {
        const resp = await this.fetch('/monitoring/usage');
        if (!resp.ok)
            return { executions: 0, aiCalls: 0, plan: 'unknown' };
        return await resp.json();
    }
    // AI Chat streaming
    async *streamChat(message, conversationId) {
        const resp = await this.fetch('/ai-chat/stream', {
            method: 'POST',
            body: JSON.stringify({ message, conversationId }),
        });
        if (!resp.ok) {
            const err = await resp.text();
            throw new Error(`AI chat failed: ${resp.status} ${err.slice(0, 200)}`);
        }
        if (!resp.body)
            return;
        const reader = resp.body.getReader();
        const decoder = new TextDecoder();
        let buffer = '';
        while (true) {
            const { done, value } = await reader.read();
            if (done)
                break;
            buffer += decoder.decode(value, { stream: true });
            const lines = buffer.split('\n');
            buffer = lines.pop() || '';
            for (const line of lines) {
                if (!line.startsWith('data: '))
                    continue;
                try {
                    yield JSON.parse(line.slice(6));
                }
                catch { /* skip non-JSON */ }
            }
        }
    }
    // Validate connection
    async validate() {
        try {
            const resp = await this.fetch('/ready');
            return resp.ok;
        }
        catch {
            return false;
        }
    }
}
export function createPlatformClient(creds) {
    return new PlatformClient(creds);
}
//# sourceMappingURL=platform-client.js.map