import _defineProperty from "@babel/runtime/helpers/defineProperty";
// eslint-disable-next-line @atlaskit/platform/prefer-crypto-random-uuid -- Use crypto.randomUUID instead
import uuid from 'uuid';
import { getBaseUrl } from '@atlaskit/linking-common';
import { readStream } from './readStream';
import { ChunkProcessingError } from './types';
import { addPath, getXProductHeaderValue } from './utils';
const CONVO_AI_ENDPOINT = 'assist/api/ai/v2/ai-feature/smartlinksummary/stream';
export class AISummaryService {
  constructor(props) {
    var _getXProductHeaderVal;
    _defineProperty(this, "state", {
      content: '',
      status: 'ready'
    });
    _defineProperty(this, "subscribedStateSetters", new Set());
    _defineProperty(this, "getRequestUrl", (envKey, baseUrlOverride) => {
      if (baseUrlOverride || envKey) {
        const baseUrl = baseUrlOverride || getBaseUrl(envKey);
        return addPath(baseUrl, CONVO_AI_ENDPOINT);
      }
      return addPath('/gateway/api/', CONVO_AI_ENDPOINT);
    });
    _defineProperty(this, "fetchStream", async () => {
      const payload = {
        recipient_agent_named_id: 'smartlink_summary_agent',
        agent_input_context: {
          content_url: this.url,
          content_ari: this.ari,
          prompt_id: 'smart_links',
          summary_output_mimetype: 'text/markdown',
          locale: this.locale
        },
        ...{
          ai_feature_input: {
            content_url: this.url,
            content_ari: this.ari,
            locale: this.locale
          }
        }
      };
      const options = {
        method: 'POST',
        headers: this.config.headers,
        body: JSON.stringify(payload),
        credentials: 'include'
      };
      const response = await fetch(this.config.requestUrl, options);
      if (!response.ok || response.status >= 400) {
        throw new Error(`Status: ${response.status}\n URL: ${this.url}\n StatusText ${response.statusText}`);
      } else {
        return readStream(response);
      }
    });
    this.config = {
      requestUrl: this.getRequestUrl(props.envKey, props.baseUrl),
      headers: {
        'Content-Type': 'application/json;charset=UTF-8',
        'x-experience-id': 'smart-link',
        'x-product': ((_getXProductHeaderVal = getXProductHeaderValue(props.product)) === null || _getXProductHeaderVal === void 0 ? void 0 : _getXProductHeaderVal.toLowerCase()) || 'confluence'
      }
    };
    this.url = props.url;
    this.ari = props.ari;
    this.locale = props.locale;
    this.onStart = props.onStart;
    this.onSuccess = props.onSuccess;
    this.onError = props.onError;
  }
  async summariseUrl() {
    this.state = {
      status: 'loading',
      content: ''
    };
    for (const subscriber of this.subscribedStateSetters) {
      subscriber(this.state);
    }

    // eslint-disable-next-line @atlaskit/platform/prefer-crypto-random-uuid -- Use crypto.randomUUID instead
    const id = uuid();
    try {
      var _this$onStart, _this$onSuccess;
      (_this$onStart = this.onStart) === null || _this$onStart === void 0 ? void 0 : _this$onStart.call(this, id);
      const stream = await this.fetchStream();
      let bufferContent = '';
      for await (const chunk of stream) {
        if (chunk.type === 'ANSWER_PART') {
          bufferContent += chunk.message.content;
          for (const subscriber of this.subscribedStateSetters) {
            subscriber({
              ...this.state,
              content: bufferContent
            });
          }
        }

        //if AI Mate service returns cached summary we get the summary text in one piece as the last message
        if (chunk.type === 'FINAL_RESPONSE') {
          bufferContent = chunk.message.content;
        }
        if (chunk.type === 'ERROR') {
          var _chunk$message;
          throw new ChunkProcessingError(chunk === null || chunk === void 0 ? void 0 : (_chunk$message = chunk.message) === null || _chunk$message === void 0 ? void 0 : _chunk$message.message_template);
        }
      }
      (_this$onSuccess = this.onSuccess) === null || _this$onSuccess === void 0 ? void 0 : _this$onSuccess.call(this, id);
      this.state = {
        status: 'done',
        content: bufferContent
      };
    } catch (err) {
      var _this$onError;
      let message = err instanceof ChunkProcessingError ? err.message : 'UNEXPECTED';
      (_this$onError = this.onError) === null || _this$onError === void 0 ? void 0 : _this$onError.call(this, id, message);
      this.state = {
        status: 'error',
        content: '',
        error: message
      };
    }
    for (const subscriber of this.subscribedStateSetters) {
      subscriber(this.state);
    }
    return this.state;
  }
  subscribe(stateSetter) {
    this.subscribedStateSetters.add(stateSetter);
    return () => {
      this.subscribedStateSetters.delete(stateSetter);
    };
  }
}