import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
import _createClass from "@babel/runtime/helpers/createClass";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
import _regeneratorRuntime from "@babel/runtime/regenerator";
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _asyncIterator(r) { var n, t, o, e = 2; for ("undefined" != typeof Symbol && (t = Symbol.asyncIterator, o = Symbol.iterator); e--;) { if (t && null != (n = r[t])) return n.call(r); if (o && null != (n = r[o])) return new AsyncFromSyncIterator(n.call(r)); t = "@@asyncIterator", o = "@@iterator"; } throw new TypeError("Object is not async iterable"); }
function AsyncFromSyncIterator(r) { function AsyncFromSyncIteratorContinuation(r) { if (Object(r) !== r) return Promise.reject(new TypeError(r + " is not an object.")); var n = r.done; return Promise.resolve(r.value).then(function (r) { return { value: r, done: n }; }); } return AsyncFromSyncIterator = function AsyncFromSyncIterator(r) { this.s = r, this.n = r.next; }, AsyncFromSyncIterator.prototype = { s: null, n: null, next: function next() { return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments)); }, return: function _return(r) { var n = this.s.return; return void 0 === n ? Promise.resolve({ value: r, done: !0 }) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments)); }, throw: function _throw(r) { var n = this.s.return; return void 0 === n ? Promise.reject(r) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments)); } }, new AsyncFromSyncIterator(r); }
// 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';
var CONVO_AI_ENDPOINT = 'assist/api/ai/v2/ai-feature/smartlinksummary/stream';
export var AISummaryService = /*#__PURE__*/function () {
  function AISummaryService(props) {
    var _this = this,
      _getXProductHeaderVal;
    _classCallCheck(this, AISummaryService);
    _defineProperty(this, "state", {
      content: '',
      status: 'ready'
    });
    _defineProperty(this, "subscribedStateSetters", new Set());
    _defineProperty(this, "getRequestUrl", function (envKey, baseUrlOverride) {
      if (baseUrlOverride || envKey) {
        var baseUrl = baseUrlOverride || getBaseUrl(envKey);
        return addPath(baseUrl, CONVO_AI_ENDPOINT);
      }
      return addPath('/gateway/api/', CONVO_AI_ENDPOINT);
    });
    _defineProperty(this, "fetchStream", /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
      var payload, options, response;
      return _regeneratorRuntime.wrap(function (_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            payload = _objectSpread({
              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
              }
            });
            options = {
              method: 'POST',
              headers: _this.config.headers,
              body: JSON.stringify(payload),
              credentials: 'include'
            };
            _context.next = 1;
            return fetch(_this.config.requestUrl, options);
          case 1:
            response = _context.sent;
            if (!(!response.ok || response.status >= 400)) {
              _context.next = 2;
              break;
            }
            throw new Error("Status: ".concat(response.status, "\n URL: ").concat(_this.url, "\n StatusText ").concat(response.statusText));
          case 2:
            return _context.abrupt("return", readStream(response));
          case 3:
          case "end":
            return _context.stop();
        }
      }, _callee);
    })));
    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;
  }
  return _createClass(AISummaryService, [{
    key: "summariseUrl",
    value: function () {
      var _summariseUrl = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
        var _iterator2, _step2, _subscriber, id, _this$onStart, _this$onSuccess, stream, bufferContent, _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, chunk, _iterator3, _step3, subscriber, _chunk$message, _this$onError, message, _iterator4, _step4, _subscriber2, _t, _t2;
        return _regeneratorRuntime.wrap(function (_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              this.state = {
                status: 'loading',
                content: ''
              };
              _iterator2 = _createForOfIteratorHelper(this.subscribedStateSetters);
              try {
                for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
                  _subscriber = _step2.value;
                  _subscriber(this.state);
                }

                // eslint-disable-next-line @atlaskit/platform/prefer-crypto-random-uuid -- Use crypto.randomUUID instead
              } catch (err) {
                _iterator2.e(err);
              } finally {
                _iterator2.f();
              }
              id = uuid();
              _context2.prev = 1;
              (_this$onStart = this.onStart) === null || _this$onStart === void 0 || _this$onStart.call(this, id);
              _context2.next = 2;
              return this.fetchStream();
            case 2:
              stream = _context2.sent;
              bufferContent = '';
              _iteratorAbruptCompletion = false;
              _didIteratorError = false;
              _context2.prev = 3;
              _iterator = _asyncIterator(stream);
            case 4:
              _context2.next = 5;
              return _iterator.next();
            case 5:
              if (!(_iteratorAbruptCompletion = !(_step = _context2.sent).done)) {
                _context2.next = 7;
                break;
              }
              chunk = _step.value;
              if (chunk.type === 'ANSWER_PART') {
                bufferContent += chunk.message.content;
                _iterator3 = _createForOfIteratorHelper(this.subscribedStateSetters);
                try {
                  for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
                    subscriber = _step3.value;
                    subscriber(_objectSpread(_objectSpread({}, this.state), {}, {
                      content: bufferContent
                    }));
                  }
                } catch (err) {
                  _iterator3.e(err);
                } finally {
                  _iterator3.f();
                }
              }

              //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')) {
                _context2.next = 6;
                break;
              }
              throw new ChunkProcessingError(chunk === null || chunk === void 0 || (_chunk$message = chunk.message) === null || _chunk$message === void 0 ? void 0 : _chunk$message.message_template);
            case 6:
              _iteratorAbruptCompletion = false;
              _context2.next = 4;
              break;
            case 7:
              _context2.next = 9;
              break;
            case 8:
              _context2.prev = 8;
              _t = _context2["catch"](3);
              _didIteratorError = true;
              _iteratorError = _t;
            case 9:
              _context2.prev = 9;
              _context2.prev = 10;
              if (!(_iteratorAbruptCompletion && _iterator.return != null)) {
                _context2.next = 11;
                break;
              }
              _context2.next = 11;
              return _iterator.return();
            case 11:
              _context2.prev = 11;
              if (!_didIteratorError) {
                _context2.next = 12;
                break;
              }
              throw _iteratorError;
            case 12:
              return _context2.finish(11);
            case 13:
              return _context2.finish(9);
            case 14:
              (_this$onSuccess = this.onSuccess) === null || _this$onSuccess === void 0 || _this$onSuccess.call(this, id);
              this.state = {
                status: 'done',
                content: bufferContent
              };
              _context2.next = 16;
              break;
            case 15:
              _context2.prev = 15;
              _t2 = _context2["catch"](1);
              message = _t2 instanceof ChunkProcessingError ? _t2.message : 'UNEXPECTED';
              (_this$onError = this.onError) === null || _this$onError === void 0 || _this$onError.call(this, id, message);
              this.state = {
                status: 'error',
                content: '',
                error: message
              };
            case 16:
              _iterator4 = _createForOfIteratorHelper(this.subscribedStateSetters);
              try {
                for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
                  _subscriber2 = _step4.value;
                  _subscriber2(this.state);
                }
              } catch (err) {
                _iterator4.e(err);
              } finally {
                _iterator4.f();
              }
              return _context2.abrupt("return", this.state);
            case 17:
            case "end":
              return _context2.stop();
          }
        }, _callee2, this, [[1, 15], [3, 8, 9, 14], [10,, 11, 13]]);
      }));
      function summariseUrl() {
        return _summariseUrl.apply(this, arguments);
      }
      return summariseUrl;
    }()
  }, {
    key: "subscribe",
    value: function subscribe(stateSetter) {
      var _this2 = this;
      this.subscribedStateSetters.add(stateSetter);
      return function () {
        _this2.subscribedStateSetters.delete(stateSetter);
      };
    }
  }]);
}();