import {
  ClientDatatableComponent
} from "./chunk-3RTU34A3.js";
import {
  OpenaiService
} from "./chunk-TIV2UYBT.js";
import "./chunk-YWQICJL7.js";
import "./chunk-BP5JJWGC.js";
import "./chunk-IGGXREIH.js";
import {
  LoaderComponent
} from "./chunk-X5XWBDVM.js";
import {
  require_sweetalert2_all
} from "./chunk-KLTWPXW2.js";
import {
  MenuMapService
} from "./chunk-3FLJCSSF.js";
import {
  ToastrService
} from "./chunk-2YLAF7RI.js";
import {
  CommonSharedModule,
  NgxTippyDirective
} from "./chunk-7NQGM4EA.js";
import {
  DefaultValueAccessor,
  FormBuilder,
  FormControlName,
  FormGroupDirective,
  FormsModule,
  NgControlStatus,
  NgControlStatusGroup,
  ReactiveFormsModule,
  TranslatePipe,
  TranslateService,
  Validators,
  ɵNgNoValidate
} from "./chunk-NLYGDKUR.js";
import "./chunk-ZEL7H2AL.js";
import {
  ActivatedRoute,
  GridApiService,
  LocalStorageService
} from "./chunk-P7K2QEDI.js";
import {
  CommonModule,
  DatePipe,
  EventEmitter,
  NgClass,
  NgForOf,
  NgIf,
  ɵsetClassDebugInfo,
  ɵɵNgOnChangesFeature,
  ɵɵProvidersFeature,
  ɵɵStandaloneFeature,
  ɵɵadvance,
  ɵɵconditional,
  ɵɵdefineComponent,
  ɵɵdirectiveInject,
  ɵɵelement,
  ɵɵelementEnd,
  ɵɵelementStart,
  ɵɵgetCurrentView,
  ɵɵlistener,
  ɵɵnextContext,
  ɵɵpipe,
  ɵɵpipeBind1,
  ɵɵproperty,
  ɵɵpureFunction1,
  ɵɵresetView,
  ɵɵrestoreView,
  ɵɵstyleProp,
  ɵɵtemplate,
  ɵɵtext,
  ɵɵtextInterpolate,
  ɵɵtextInterpolate1
} from "./chunk-GKZIWABI.js";
import {
  __async,
  __toESM
} from "./chunk-CVWHNZRK.js";

// src/app/@lcp-framework/components/autocomplete/autocomplete.component.ts
function AutocompleteComponent_ul_5_li_1_Template(rf, ctx) {
  if (rf & 1) {
    const _r1 = \u0275\u0275getCurrentView();
    \u0275\u0275elementStart(0, "li", 5);
    \u0275\u0275listener("mousedown", function AutocompleteComponent_ul_5_li_1_Template_li_mousedown_0_listener() {
      const item_r2 = \u0275\u0275restoreView(_r1).$implicit;
      const ctx_r2 = \u0275\u0275nextContext(2);
      return \u0275\u0275resetView(ctx_r2.selectItem(item_r2));
    });
    \u0275\u0275text(1);
    \u0275\u0275elementEnd();
  }
  if (rf & 2) {
    const item_r2 = ctx.$implicit;
    \u0275\u0275advance();
    \u0275\u0275textInterpolate1(" ", item_r2.name, " ");
  }
}
function AutocompleteComponent_ul_5_Template(rf, ctx) {
  if (rf & 1) {
    \u0275\u0275elementStart(0, "ul", 3);
    \u0275\u0275template(1, AutocompleteComponent_ul_5_li_1_Template, 2, 1, "li", 4);
    \u0275\u0275elementEnd();
  }
  if (rf & 2) {
    const ctx_r2 = \u0275\u0275nextContext();
    \u0275\u0275advance();
    \u0275\u0275property("ngForOf", ctx_r2.filteredItems);
  }
}
var _AutocompleteComponent = class _AutocompleteComponent {
  constructor() {
    this.label = "";
    this.placeholder = "";
    this.items = [];
    this.fieldName = "";
    this.dispLabel = null;
    this.width = null;
    this.itemSelected = new EventEmitter();
    this.filteredItems = [];
    this.showDropdown = false;
  }
  ngOnInit() {
    if (this.value) {
    }
  }
  ngOnChanges() {
    this.filteredItems = this.items;
    if (this.value) {
      this.items.forEach((each) => {
        if (each.id === this.value) {
          this.dispLabel = each.name;
        }
      });
    } else {
      this.dispLabel = null;
    }
  }
  showDropdowndisp() {
    this.showDropdown = true;
  }
  filterItems(event) {
    const term = event.target.value ?? "";
    const searchTerm = term.toLowerCase();
    this.filteredItems = this.items.filter((item) => item.name.toLowerCase().includes(searchTerm));
    this.showDropdown = this.filteredItems.length > 0;
  }
  selectItem(item) {
    this.value = item.id;
    this.dispLabel = item.name;
    this.itemSelected.emit(item);
    this.showDropdown = false;
  }
  hideDropdown() {
    setTimeout(() => {
      this.showDropdown = false;
    }, 200);
  }
};
_AutocompleteComponent.\u0275fac = function AutocompleteComponent_Factory(t) {
  return new (t || _AutocompleteComponent)();
};
_AutocompleteComponent.\u0275cmp = /* @__PURE__ */ \u0275\u0275defineComponent({ type: _AutocompleteComponent, selectors: [["app-autocomplete"]], inputs: { value: "value", label: "label", placeholder: "placeholder", items: "items", fieldName: "fieldName", width: "width" }, outputs: { itemSelected: "itemSelected" }, standalone: true, features: [\u0275\u0275NgOnChangesFeature, \u0275\u0275StandaloneFeature], decls: 6, vars: 8, consts: [[1, "relative", "flex", "flex-col", "gap-1"], ["type", "text", 1, "w-max-80", "form-input", "w-full", "rounded", "border", "border-gray-300", "py-1", "text-xs", "text-gray-600", "placeholder:text-white-dark", "focus:outline-none", "focus:ring-2", "focus:ring-blue-500", 3, "focus", "blur", "input", "placeholder", "value"], ["class", "absolute top-full z-10 mt-1 max-h-60 w-full overflow-y-auto rounded border border-gray-300 bg-white text-xs shadow", 4, "ngIf"], [1, "absolute", "top-full", "z-10", "mt-1", "max-h-60", "w-full", "overflow-y-auto", "rounded", "border", "border-gray-300", "bg-white", "text-xs", "shadow"], ["class", "cursor-pointer px-3 py-1 hover:bg-blue-100", 3, "mousedown", 4, "ngFor", "ngForOf"], [1, "cursor-pointer", "px-3", "py-1", "hover:bg-blue-100", 3, "mousedown"]], template: function AutocompleteComponent_Template(rf, ctx) {
  if (rf & 1) {
    \u0275\u0275elementStart(0, "div", 0)(1, "label");
    \u0275\u0275text(2);
    \u0275\u0275pipe(3, "translate");
    \u0275\u0275elementEnd();
    \u0275\u0275elementStart(4, "input", 1);
    \u0275\u0275listener("focus", function AutocompleteComponent_Template_input_focus_4_listener() {
      return ctx.showDropdowndisp();
    })("blur", function AutocompleteComponent_Template_input_blur_4_listener() {
      return ctx.hideDropdown();
    })("input", function AutocompleteComponent_Template_input_input_4_listener($event) {
      return ctx.filterItems($event);
    });
    \u0275\u0275elementEnd();
    \u0275\u0275template(5, AutocompleteComponent_ul_5_Template, 2, 1, "ul", 2);
    \u0275\u0275elementEnd();
  }
  if (rf & 2) {
    \u0275\u0275advance(2);
    \u0275\u0275textInterpolate(\u0275\u0275pipeBind1(3, 6, ctx.label));
    \u0275\u0275advance(2);
    \u0275\u0275styleProp("width", ctx.width);
    \u0275\u0275property("placeholder", ctx.placeholder)("value", ctx.dispLabel);
    \u0275\u0275advance();
    \u0275\u0275property("ngIf", ctx.showDropdown && ctx.filteredItems.length);
  }
}, dependencies: [CommonModule, NgForOf, NgIf, ReactiveFormsModule, FormsModule, CommonSharedModule, TranslatePipe], styles: ["\n\n.w-max-80[_ngcontent-%COMP%] {\n  max-width: 80vw;\n}\n/*# sourceMappingURL=autocomplete.component.css.map */"] });
var AutocompleteComponent = _AutocompleteComponent;
(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && \u0275setClassDebugInfo(AutocompleteComponent, { className: "AutocompleteComponent", filePath: "src\\app\\@lcp-framework\\components\\autocomplete\\autocomplete.component.ts", lineNumber: 13 });
})();

// src/app/@lcp-framework/pages/ai-playground/ai-playground.component.ts
var import_sweetalert2 = __toESM(require_sweetalert2_all());
var _c0 = (a0) => ({ "disabled-input": a0 });
function AiPlaygroundComponent_Conditional_6_Template(rf, ctx) {
  if (rf & 1) {
    const _r1 = \u0275\u0275getCurrentView();
    \u0275\u0275elementStart(0, "div", 4)(1, "div", 10)(2, "app-autocomplete", 11);
    \u0275\u0275listener("itemSelected", function AiPlaygroundComponent_Conditional_6_Template_app_autocomplete_itemSelected_2_listener($event) {
      \u0275\u0275restoreView(_r1);
      const ctx_r1 = \u0275\u0275nextContext();
      return \u0275\u0275resetView(ctx_r1.onQuerySelected($event));
    });
    \u0275\u0275elementEnd();
    \u0275\u0275elementStart(3, "div", 12)(4, "a", 13);
    \u0275\u0275listener("click", function AiPlaygroundComponent_Conditional_6_Template_a_click_4_listener() {
      \u0275\u0275restoreView(_r1);
      const ctx_r1 = \u0275\u0275nextContext();
      return \u0275\u0275resetView(ctx_r1.deleteQuery());
    });
    \u0275\u0275element(5, "i", 14);
    \u0275\u0275elementEnd();
    \u0275\u0275elementStart(6, "a", 15);
    \u0275\u0275listener("click", function AiPlaygroundComponent_Conditional_6_Template_a_click_6_listener() {
      \u0275\u0275restoreView(_r1);
      const ctx_r1 = \u0275\u0275nextContext();
      return \u0275\u0275resetView(ctx_r1.editQuery());
    });
    \u0275\u0275element(7, "i", 16);
    \u0275\u0275elementEnd();
    \u0275\u0275elementStart(8, "a", 17);
    \u0275\u0275listener("click", function AiPlaygroundComponent_Conditional_6_Template_a_click_8_listener() {
      \u0275\u0275restoreView(_r1);
      const ctx_r1 = \u0275\u0275nextContext();
      return \u0275\u0275resetView(ctx_r1.executeQuery());
    });
    \u0275\u0275element(9, "i", 18);
    \u0275\u0275elementEnd()()()();
  }
  if (rf & 2) {
    const ctx_r1 = \u0275\u0275nextContext();
    \u0275\u0275advance(2);
    \u0275\u0275property("items", ctx_r1.queryList)("label", "previous_queries")("value", ctx_r1.form.controls["query_id"].value)("width", "800px");
    \u0275\u0275advance(2);
    \u0275\u0275property("ngClass", \u0275\u0275pureFunction1(7, _c0, !ctx_r1.selectedPrompt));
    \u0275\u0275advance(2);
    \u0275\u0275property("ngClass", \u0275\u0275pureFunction1(9, _c0, !ctx_r1.selectedPrompt));
    \u0275\u0275advance(2);
    \u0275\u0275property("ngClass", \u0275\u0275pureFunction1(11, _c0, !ctx_r1.selectedPrompt));
  }
}
function AiPlaygroundComponent_Conditional_16_Template(rf, ctx) {
  if (rf & 1) {
    const _r3 = \u0275\u0275getCurrentView();
    \u0275\u0275elementStart(0, "div", 8)(1, "div", 19)(2, "app-client-datatable", 20);
    \u0275\u0275listener("dataChange", function AiPlaygroundComponent_Conditional_16_Template_app_client_datatable_dataChange_2_listener($event) {
      \u0275\u0275restoreView(_r3);
      const ctx_r1 = \u0275\u0275nextContext();
      return \u0275\u0275resetView(ctx_r1.onQueryDataChange($event));
    })("sortChange", function AiPlaygroundComponent_Conditional_16_Template_app_client_datatable_sortChange_2_listener($event) {
      \u0275\u0275restoreView(_r3);
      const ctx_r1 = \u0275\u0275nextContext();
      return \u0275\u0275resetView(ctx_r1.onQuerySortChange($event));
    });
    \u0275\u0275elementEnd()()();
  }
  if (rf & 2) {
    const ctx_r1 = \u0275\u0275nextContext();
    \u0275\u0275advance(2);
    \u0275\u0275property("data", ctx_r1.tempTableResponse)("config", ctx_r1.aiResultTableConfig);
  }
}
function AiPlaygroundComponent_app_loader_17_Template(rf, ctx) {
  if (rf & 1) {
    \u0275\u0275element(0, "app-loader");
  }
}
var _AiPlaygroundComponent = class _AiPlaygroundComponent {
  constructor(toastr, fb, openaiService, route, translate, commonService, gridApiService, localStorageService) {
    this.toastr = toastr;
    this.fb = fb;
    this.openaiService = openaiService;
    this.route = route;
    this.translate = translate;
    this.commonService = commonService;
    this.gridApiService = gridApiService;
    this.localStorageService = localStorageService;
    this.tableResponse = [];
    this.tempTableResponse = [];
    this.title = "Query Result";
    this.aiResultTableConfig = {
      columns: [],
      pageSizes: [5, 10, 25, 50],
      defaultPageSize: 5,
      searchable: true,
      headerConfig: {
        showHeader: true,
        addButton: void 0,
        enableFilter: true,
        enableColumnSelector: true,
        enableExport: true
      }
    };
    this.column = "";
    this.loading = false;
    this.isTableShow = false;
    this.userId = 0;
    this.queryHistory = [];
    this.queryList = [];
    this.idQueryMapping = {};
    this.selectedPrompt = null;
    this.form = this.fb.group({
      query_id: [null],
      prompt: [null, Validators.required]
    });
  }
  ngOnInit() {
    this.getLogHistory();
    this.userId = this.localStorageService.getData("user_data") && JSON.parse(this.localStorageService.getData("user_data")).main.id;
  }
  getLogHistory() {
    let payload = {
      company_id: 1,
      search_all: [
        {
          value: "3",
          operator: "!=",
          column_name: "openai_usage_logs.status_id"
        }
      ],
      search_any: [],
      limit_range: 1,
      print_query: true,
      start_index: 0,
      primary_table: "openai_usage_logs",
      select_columns: [["openai_usage_logs.id"], ["openai_usage_logs.prompt"], ["openai_usage_logs.generated_sql"]]
    };
    this.commonService.getCommonList(payload).subscribe({
      next: (res) => {
        if (res.status && res.data.records.length) {
          this.queryHistory = [];
          this.queryList = [];
          this.idQueryMapping = {};
          this.queryHistory = res.data.records;
          for (const each of this.queryHistory) {
            this.queryList.push({
              id: each.id,
              name: each.prompt
            });
            this.idQueryMapping[each.id] = each.generated_sql;
          }
        }
      },
      error: (err) => {
        console.log("err", err);
      }
    });
  }
  onQuerySelected(event) {
    this.form.patchValue({
      query_id: event.id
    });
    this.selectedPrompt = event.name;
  }
  deleteQuery() {
    import_sweetalert2.default.fire({
      icon: "info",
      title: "Are you sure you want to delete this query?",
      text: "once deleted, this query will be deleted from the history",
      showCancelButton: true,
      confirmButtonText: "Submit",
      padding: "2em"
    }).then((result) => __async(this, null, function* () {
      if (result.value) {
        this.loading = true;
        const payload = {
          data: {
            table2: [
              {
                status_id: 3,
                deleted_at: /* @__PURE__ */ new Date(),
                deleted_by: this.userId
              }
            ]
          },
          table: ["openai_usage_logs", "openai_usage_logs"],
          action: ["select", "update"],
          columns: {
            table1: ["id"]
          },
          conditions: {
            table1: [
              {
                id: this.form.value.query_id
              }
            ],
            table2: [
              {
                id: "@table1.id"
              }
            ]
          },
          table_mapping: ["table1", "table2"]
        };
        this.gridApiService.executeRecords(payload).subscribe({
          next: (response) => {
            this.loading = false;
            if (response.code === 200 && response.status) {
              this.toastr.success("Query deleted successfully", "Success");
              this.getLogHistory();
              this.selectedPrompt = null;
              this.form.patchValue({
                query_id: null
              });
            }
          },
          error: (err) => {
            this.loading = false;
            this.toastr.error("Failed to delete query", "Error");
          }
        });
      }
    }));
  }
  editQuery() {
    this.form.patchValue({
      prompt: this.selectedPrompt
    });
  }
  executeQuery() {
    this.loading = true;
    this.openaiService.getResultFromQuery({ sql: this.idQueryMapping[this.form.value.query_id] }).subscribe({
      next: (res) => {
        this.loading = false;
        this.populateTableSchema(res.data);
      },
      error: (err) => {
        this.loading = false;
        this.toastr.error("Failed to execute query", "Error");
      }
    });
  }
  submit() {
    this.form.markAllAsTouched();
    if (this.form.valid) {
      this.loading = true;
      this.openaiService.generateAiQuery({ prompt: this.form.value.prompt }).subscribe({
        next: (res) => {
          this.loading = false;
          this.populateTableSchema(res.data.result);
        },
        error: (err) => {
          this.loading = false;
          this.toastr.error("Failed to generate query", "Error");
        }
      });
    } else {
      this.loading = false;
      this.toastr.error("Please enter a prompt", "Error");
    }
  }
  populateTableSchema(result) {
    if (result.length) {
      let firstColumn = result[0];
      this.aiResultTableConfig.columns = Object.keys(firstColumn).map((key) => ({
        key,
        label: key,
        sortable: true,
        searchable: true
      }));
      this.getLogHistory();
    }
    this.tableResponse = [];
    this.tableResponse = result;
    this.tempTableResponse = this.tableResponse;
    this.isTableShow = true;
  }
  onQueryDataChange(data) {
    const itemsToUse = !data || data.length === 0 ? this.tableResponse : data;
    this.tempTableResponse = [...itemsToUse];
  }
  onQuerySortChange(sort) {
    const items = [...this.tempTableResponse];
    items.sort((a, b) => {
      const aVal = a[sort.column];
      const bVal = b[sort.column];
      return sort.direction === "asc" ? aVal > bVal ? 1 : -1 : aVal < bVal ? 1 : -1;
    });
    this.onQueryDataChange(items);
  }
};
_AiPlaygroundComponent.\u0275fac = function AiPlaygroundComponent_Factory(t) {
  return new (t || _AiPlaygroundComponent)(\u0275\u0275directiveInject(ToastrService), \u0275\u0275directiveInject(FormBuilder), \u0275\u0275directiveInject(OpenaiService), \u0275\u0275directiveInject(ActivatedRoute), \u0275\u0275directiveInject(TranslateService), \u0275\u0275directiveInject(MenuMapService), \u0275\u0275directiveInject(GridApiService), \u0275\u0275directiveInject(LocalStorageService));
};
_AiPlaygroundComponent.\u0275cmp = /* @__PURE__ */ \u0275\u0275defineComponent({ type: _AiPlaygroundComponent, selectors: [["app-ai-playground"]], standalone: true, features: [\u0275\u0275ProvidersFeature([DatePipe]), \u0275\u0275StandaloneFeature], decls: 18, vars: 13, consts: [[1, "panel", "mb-3"], [3, "formGroup"], [1, "mb-3", "flex", "items-start", "justify-between", "gap-2", "lg:flex-row", "lg:items-center"], [1, "text-lg", "font-semibold", "dark:text-white-light"], [1, "mb-3", "grid", "grid-cols-1"], ["formControlName", "prompt", 1, "h-200", "form-input", "w-full", "p-1", "text-xs", "text-gray-600", "placeholder:text-white-dark"], [1, "mb-3"], ["type", "submit", 1, "w-30", "btn", "btn-success", "text-xs", 3, "click"], [1, "panel", "mt-3"], [4, "ngIf"], [1, "justify-content-between", "flex", "flex-wrap", "items-end", "gap-5"], ["fieldName", "query_id", "placeholder", "Select previous query", 3, "itemSelected", "items", "label", "value", "width"], [1, "flex", "items-center", "gap-2"], ["href", "javascript:void(0);", "ngxTippy", "", "data-tippy-content", "Delete Query", 1, "btn-par", "hover:text-primary", 3, "click", "ngClass"], [1, "fa", "fa-trash", "text-red-500"], ["href", "javascript:void(0);", "ngxTippy", "", "data-tippy-content", "Edit Query", 1, "btn-par", "hover:text-primary", 3, "click", "ngClass"], [1, "fa", "fa-pen-to-square", "fa-regular"], ["href", "javascript:void(0);", "ngxTippy", "", "data-tippy-content", "Execute Query", 1, "btn-par", "hover:text-primary", 3, "click", "ngClass"], [1, "fa", "fa-arrows-rotate", "fa-solid"], [1, "panel-body"], [3, "dataChange", "sortChange", "data", "config"]], template: function AiPlaygroundComponent_Template(rf, ctx) {
  if (rf & 1) {
    \u0275\u0275elementStart(0, "div", 0)(1, "form", 1)(2, "div", 2)(3, "h5", 3);
    \u0275\u0275text(4);
    \u0275\u0275pipe(5, "translate");
    \u0275\u0275elementEnd()();
    \u0275\u0275template(6, AiPlaygroundComponent_Conditional_6_Template, 10, 13, "div", 4);
    \u0275\u0275elementStart(7, "div", 4)(8, "label");
    \u0275\u0275text(9);
    \u0275\u0275pipe(10, "translate");
    \u0275\u0275elementEnd();
    \u0275\u0275element(11, "textarea", 5);
    \u0275\u0275elementEnd();
    \u0275\u0275elementStart(12, "div", 6)(13, "button", 7);
    \u0275\u0275listener("click", function AiPlaygroundComponent_Template_button_click_13_listener() {
      return ctx.submit();
    });
    \u0275\u0275text(14);
    \u0275\u0275pipe(15, "translate");
    \u0275\u0275elementEnd()()()();
    \u0275\u0275template(16, AiPlaygroundComponent_Conditional_16_Template, 3, 2, "div", 8)(17, AiPlaygroundComponent_app_loader_17_Template, 1, 0, "app-loader", 9);
  }
  if (rf & 2) {
    \u0275\u0275advance();
    \u0275\u0275property("formGroup", ctx.form);
    \u0275\u0275advance(3);
    \u0275\u0275textInterpolate1(" ", \u0275\u0275pipeBind1(5, 7, "ai_playground_form"), " ");
    \u0275\u0275advance(2);
    \u0275\u0275conditional(6, ctx.queryList.length ? 6 : -1);
    \u0275\u0275advance(3);
    \u0275\u0275textInterpolate(\u0275\u0275pipeBind1(10, 9, "prompt"));
    \u0275\u0275advance(5);
    \u0275\u0275textInterpolate1(" ", \u0275\u0275pipeBind1(15, 11, "submit"), " ");
    \u0275\u0275advance(2);
    \u0275\u0275conditional(16, ctx.isTableShow ? 16 : -1);
    \u0275\u0275advance();
    \u0275\u0275property("ngIf", ctx.loading);
  }
}, dependencies: [CommonModule, NgClass, NgIf, CommonSharedModule, \u0275NgNoValidate, DefaultValueAccessor, NgControlStatus, NgControlStatusGroup, NgxTippyDirective, TranslatePipe, FormsModule, ReactiveFormsModule, FormGroupDirective, FormControlName, ClientDatatableComponent, LoaderComponent, AutocompleteComponent], styles: ["\n\n.h-200[_ngcontent-%COMP%] {\n  height: 200px;\n}\n.btn-par[_ngcontent-%COMP%] {\n  padding: 0.2rem;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n}\n.btn-par[_ngcontent-%COMP%]   i[_ngcontent-%COMP%] {\n  font-size: 20px;\n}\n/*# sourceMappingURL=ai-playground.component.css.map */"] });
var AiPlaygroundComponent = _AiPlaygroundComponent;
(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && \u0275setClassDebugInfo(AiPlaygroundComponent, { className: "AiPlaygroundComponent", filePath: "src\\app\\@lcp-framework\\pages\\ai-playground\\ai-playground.component.ts", lineNumber: 24 });
})();
export {
  AiPlaygroundComponent
};
//# sourceMappingURL=chunk-6G7OEA4P.js.map
