import{d as te}from"./datatables-I6jthWPb.js";import{g as m,r as h}from"./api-DZ3cXm1m.js";import{s as l,a as ne}from"./toastr-helper-Wdj0mZjX.js";import{i as se}from"./tooltip-manager-D9RaGGY4.js";import"./bootstrap.esm-Bb7dPm-H.js";import"./datatables-Bo82YvhT.js";/* empty css                                  */document.addEventListener("DOMContentLoaded",function(){const{routes:u,translations:n,permissions:A}=window,b=document.getElementById("trainingDatasetEditForm");b&&b.addEventListener("submit",function(s){var e;if(!K())return s.preventDefault(),!1;const t=b.querySelector('button[type="submit"]')||document.querySelector(`button[type="submit"][form="${b.id}"]`);return t&&(t.disabled=!0,t.innerHTML='<i class="fas fa-spinner fa-spin me-2"></i>'+(((e=n.buttons)==null?void 0:e.saving)||"Saving...")),T=!1,!0});function K(){var e;let s=!0;const t=document.getElementById("name");return t&&!t.value.trim()?(t.classList.add("is-invalid"),j(t,((e=n.validation)==null?void 0:e.name_required)||"Dataset name is required."),s=!1):t&&(t.classList.remove("is-invalid"),v(t)),s}function j(s,t){v(s);const e=document.createElement("div");e.className="invalid-feedback",e.textContent=t,s.parentNode.appendChild(e)}function v(s){const t=s.parentNode.querySelector(".invalid-feedback");t&&t.remove()}let T=!1;b&&(b.addEventListener("input",function(){T=!0}),b.addEventListener("change",function(){T=!0})),window.addEventListener("beforeunload",function(s){var t;T&&(s.preventDefault(),s.returnValue=((t=n.messages)==null?void 0:t.unsaved_changes)||"You have unsaved changes. Are you sure you want to leave?")});const w=document.getElementById("name");w&&(w.addEventListener("blur",function(){var s;this.value.trim()?(this.classList.remove("is-invalid"),v(this)):(this.classList.add("is-invalid"),j(this,((s=n.validation)==null?void 0:s.name_required)||"Dataset name is required."))}),w.addEventListener("input",function(){this.value.trim()&&(this.classList.remove("is-invalid"),v(this))}));let g;function Q(){var t;const s=document.getElementById("trainingItemsTable");!s||!((t=u.items)!=null&&t.records)||(g=$(s).DataTable({...te.getDefaultConfig(),serverSide:!0,dom:'<"d-flex justify-content-between align-items-center mb-3"<"d-flex align-items-center"l><"d-flex align-items-center"f>>t<"d-flex justify-content-between align-items-center mt-3"<"d-flex align-items-center"i><"d-flex align-items-center"p>>',ajax:{url:u.items.records,type:"GET",beforeSend:function(e){e.setRequestHeader("Authorization",`Bearer ${m()}`)},error:async function(e){e.status===401&&await h()&&g.ajax.reload()}},columns:[{data:"system_prompt",name:"system_prompt",render:function(e){if(!e)return"-";const r=e.length>80?e.substring(0,80)+"...":e;return`<span data-bs-toggle="tooltip" title="${e.replace(/"/g,"&quot;")}">${r}</span>`}},{data:"user_message",name:"user_message",render:function(e){if(!e)return"-";const r=e.length>80?e.substring(0,80)+"...":e;return`<span data-bs-toggle="tooltip" title="${e.replace(/"/g,"&quot;")}">${r}</span>`}},{data:"assistant_response",name:"assistant_response",render:function(e){if(!e)return"-";const r=e.length>80?e.substring(0,80)+"...":e;return`<span data-bs-toggle="tooltip" title="${e.replace(/"/g,"&quot;")}">${r}</span>`}},{data:"is_approved",name:"is_approved",className:"text-center",render:function(e,r,a){return`<div class="form-check form-switch d-flex justify-content-center mb-0">
                            <input class="form-check-input toggle-approved" type="checkbox" ${e?"checked":""}
                                   data-id="${a.id}" style="cursor: pointer;">
                        </div>`}},{data:"id",name:"actions",orderable:!1,searchable:!1,className:"text-end",render:function(e){var a,i,c,o;const r=[];return(a=A.aiTraining)!=null&&a.update&&r.push(`
                                <button type="button"
                                        class="btn btn-sm btn-outline-primary d-inline-flex align-items-center justify-content-center edit-item-btn"
                                        style="width: 32px; height: 32px;"
                                        data-id="${e}"
                                        data-bs-toggle="tooltip"
                                        title="${((i=n.buttons)==null?void 0:i.edit)||"Edit"}">
                                    <i class="fas fa-edit"></i>
                                </button>`),(c=A.aiTraining)!=null&&c.delete&&r.push(`
                                <button type="button"
                                        class="btn btn-sm btn-outline-danger d-inline-flex align-items-center justify-content-center ms-1 delete-item-btn"
                                        style="width: 32px; height: 32px;"
                                        data-id="${e}"
                                        data-bs-toggle="tooltip"
                                        title="${((o=n.buttons)==null?void 0:o.delete)||"Delete"}">
                                    <i class="fas fa-trash"></i>
                                </button>`),r.length===0?'<span class="text-muted">-</span>':`<div class="d-inline-flex justify-content-end">${r.join("")}</div>`}}],drawCallback:function(){se()}}))}Q();const B=document.getElementById("addTrainingItemBtn");B&&B.addEventListener("click",function(){L()});function L(s){var d,p,f,E,I,C,S,M,z,q,H;const t=!!s,e=`trainingItemModal_${Date.now()}`,r=`
            <div class="modal fade" id="${e}" tabindex="-1" aria-hidden="true">
                <div class="modal-dialog modal-lg modal-dialog-centered">
                    <div class="modal-content">
                        <div class="modal-header border-0">
                            <h5 class="modal-title">${t?((d=n.items)==null?void 0:d.edit_title)||"Edit Training Item":((p=n.items)==null?void 0:p.add_title)||"Add Training Item"}</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <div class="mb-3">
                                <label class="form-label">${((f=n.items)==null?void 0:f.system_prompt)||"System Prompt"}</label>
                                <textarea id="${e}_system" class="form-control" rows="3"
                                    placeholder="${((E=n.items)==null?void 0:E.system_prompt_placeholder)||"Enter system prompt..."}">${(s==null?void 0:s.system_prompt)||""}</textarea>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">${((I=n.items)==null?void 0:I.user_message)||"User Message"} <span class="text-danger">*</span></label>
                                <textarea id="${e}_user" class="form-control" rows="3"
                                    placeholder="${((C=n.items)==null?void 0:C.user_message_placeholder)||"Enter user message..."}">${(s==null?void 0:s.user_message)||""}</textarea>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">${((S=n.items)==null?void 0:S.assistant_response)||"Assistant Response"} <span class="text-danger">*</span></label>
                                <textarea id="${e}_assistant" class="form-control" rows="3"
                                    placeholder="${((M=n.items)==null?void 0:M.assistant_response_placeholder)||"Enter assistant response..."}">${(s==null?void 0:s.assistant_response)||""}</textarea>
                            </div>
                        </div>
                        <div class="modal-footer border-0">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">${((z=n.buttons)==null?void 0:z.cancel)||"Cancel"}</button>
                            <button type="button" class="btn btn-primary" id="${e}_save">
                                ${t?((q=n.buttons)==null?void 0:q.update)||"Update":((H=n.buttons)==null?void 0:H.save)||"Save"}
                            </button>
                        </div>
                    </div>
                </div>
            </div>`,a=document.createElement("div");a.innerHTML=r,document.body.appendChild(a.firstElementChild);const i=new window.bootstrap.Modal(document.getElementById(e)),c=document.getElementById(`${e}_save`),o=document.getElementById(e);c.addEventListener("click",async function(){var U,D,G,R,V,Y;const ee=document.getElementById(`${e}_system`).value.trim(),F=document.getElementById(`${e}_user`).value.trim(),O=document.getElementById(`${e}_assistant`).value.trim();if(!F){l("error",((U=n.validation)==null?void 0:U.user_message_required)||"User message is required.");return}if(!O){l("error",((D=n.validation)==null?void 0:D.assistant_response_required)||"Assistant response is required.");return}const J={system_prompt:ee,user_message:F,assistant_response:O},N=t?u.items.update.replace(":id",s.id):u.items.store,P=t?"PUT":"POST";try{let y=await fetch(N,{method:P,headers:{Authorization:`Bearer ${m()}`,Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(J)});y.status===401&&await h()&&(y=await fetch(N,{method:P,headers:{Authorization:`Bearer ${m()}`,Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(J)}));const _=await y.json();_.success?(l("success",_.message||(t?((G=n.items)==null?void 0:G.updated)||"Training item updated.":((R=n.items)==null?void 0:R.added)||"Training item added.")),i.hide(),g&&g.ajax.reload(null,!1)):l("error",_.message||((V=n.messages)==null?void 0:V.error)||"An error occurred.")}catch(y){console.error("Save item error:",y),l("error",((Y=n.messages)==null?void 0:Y.error)||"An error occurred.")}}),o.addEventListener("hidden.bs.modal",()=>{o.remove()}),i.show()}document.addEventListener("change",async function(s){var a,i,c;const t=s.target.closest(".toggle-approved");if(!t)return;const e=t.getAttribute("data-id"),r=u.items.toggleApproved.replace(":id",e);try{let o=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${m()}`,Accept:"application/json","Content-Type":"application/json"}});o.status===401&&await h()&&(o=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${m()}`,Accept:"application/json","Content-Type":"application/json"}}));const d=await o.json();d.success?l("success",d.message||((a=n.items)==null?void 0:a.approved_toggled)||"Approval status updated."):(l("error",d.message||((i=n.messages)==null?void 0:i.error)||"An error occurred."),t.checked=!t.checked)}catch(o){console.error("Toggle approved error:",o),l("error",((c=n.messages)==null?void 0:c.error)||"An error occurred."),t.checked=!t.checked}}),document.addEventListener("click",async function(s){const t=s.target.closest(".edit-item-btn");if(t){const r=t.getAttribute("data-id");await W(r)}const e=s.target.closest(".delete-item-btn");if(e){const r=e.getAttribute("data-id");await X(r)}});async function W(s){var e,r;const t=u.items.show.replace(":id",s);try{let a=await fetch(t,{method:"GET",headers:{Authorization:`Bearer ${m()}`,Accept:"application/json"}});a.status===401&&await h()&&(a=await fetch(t,{method:"GET",headers:{Authorization:`Bearer ${m()}`,Accept:"application/json"}}));const i=await a.json();i.success?L(i.data):l("error",i.message||((e=n.messages)==null?void 0:e.error)||"Failed to load item.")}catch(a){console.error("Load item error:",a),l("error",((r=n.messages)==null?void 0:r.error)||"An error occurred.")}}async function X(s){var r,a,i,c,o,d;if(!await ne(((r=n.items)==null?void 0:r.confirm_delete)||"Are you sure you want to delete this training item?",{confirmClass:"btn-danger",confirmText:((a=n.buttons)==null?void 0:a.confirm)||"Confirm",cancelText:((i=n.buttons)==null?void 0:i.cancel)||"Cancel"}))return;const e=u.items.destroy.replace(":id",s);try{let p=await fetch(e,{method:"DELETE",headers:{Authorization:`Bearer ${m()}`,Accept:"application/json"}});p.status===401&&await h()&&(p=await fetch(e,{method:"DELETE",headers:{Authorization:`Bearer ${m()}`,Accept:"application/json"}}));const f=await p.json();f.success?(l("success",f.message||((c=n.items)==null?void 0:c.deleted)||"Training item deleted."),g&&g.ajax.reload(null,!1)):l("error",f.message||((o=n.messages)==null?void 0:o.error)||"An error occurred.")}catch(p){console.error("Delete item error:",p),l("error",((d=n.messages)==null?void 0:d.error)||"An error occurred.")}}document.querySelectorAll(".import-data-btn").forEach(function(s){s.addEventListener("click",async function(){var r,a,i,c,o;const t=this.getAttribute("data-source");if(!t||!((r=u.items)!=null&&r.import))return;this.disabled=!0;const e=this.innerHTML;this.innerHTML='<i class="fas fa-spinner fa-spin me-1"></i>'+(((a=n.buttons)==null?void 0:a.importing)||"Importing...");try{let d=await fetch(u.items.import,{method:"POST",headers:{Authorization:`Bearer ${m()}`,Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({source:t})});d.status===401&&await h()&&(d=await fetch(u.items.import,{method:"POST",headers:{Authorization:`Bearer ${m()}`,Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({source:t})}));const p=await d.json();p.success?(l("success",p.message||((i=n.items)==null?void 0:i.imported)||"Data imported successfully."),g&&g.ajax.reload(null,!1)):l("error",p.message||((c=n.messages)==null?void 0:c.error)||"Import failed.")}catch(d){console.error("Import error:",d),l("error",((o=n.messages)==null?void 0:o.error)||"An error occurred.")}finally{this.disabled=!1,this.innerHTML=e}})});const k=document.getElementById("startFineTuneBtn");k&&k.addEventListener("click",async function(){var t,e,r,a,i;if(!((t=u.fineTune)!=null&&t.start))return;this.disabled=!0;const s=this.innerHTML;this.innerHTML='<i class="fas fa-spinner fa-spin me-1"></i>'+(((e=n.fine_tune)==null?void 0:e.starting)||"Starting...");try{let c=await fetch(u.fineTune.start,{method:"POST",headers:{Authorization:`Bearer ${m()}`,Accept:"application/json","Content-Type":"application/json"}});c.status===401&&await h()&&(c=await fetch(u.fineTune.start,{method:"POST",headers:{Authorization:`Bearer ${m()}`,Accept:"application/json","Content-Type":"application/json"}}));const o=await c.json();o.success?(l("success",o.message||((r=n.fine_tune)==null?void 0:r.started)||"Fine-tuning job started."),x()):l("error",o.message||((a=n.messages)==null?void 0:a.error)||"Failed to start fine-tuning.")}catch(c){console.error("Fine-tune start error:",c),l("error",((i=n.messages)==null?void 0:i.error)||"An error occurred.")}finally{this.disabled=!1,this.innerHTML=s}});async function x(){var t;if(!(!document.getElementById("fineTuneJobsContainer")||!((t=u.fineTune)!=null&&t.jobs)))try{let e=await fetch(u.fineTune.jobs,{method:"GET",headers:{Authorization:`Bearer ${m()}`,Accept:"application/json"}});e.status===401&&await h()&&(e=await fetch(u.fineTune.jobs,{method:"GET",headers:{Authorization:`Bearer ${m()}`,Accept:"application/json"}}));const r=await e.json();r.success&&Z(r.data||[])}catch(e){console.error("Load fine-tune jobs error:",e)}}function Z(s){var r,a,i,c,o;const t=document.getElementById("fineTuneJobsContainer");if(!t)return;if(s.length===0){t.innerHTML=`<p class="text-muted mb-0">${((r=n.fine_tune)==null?void 0:r.no_jobs)||"No fine-tuning jobs yet."}</p>`;return}let e=`
            <table class="table table-sm mb-0">
                <thead>
                    <tr>
                        <th>${((a=n.fine_tune)==null?void 0:a.job_id)||"Job ID"}</th>
                        <th>${((i=n.fine_tune)==null?void 0:i.status)||"Status"}</th>
                        <th>${((c=n.fine_tune)==null?void 0:c.model)||"Model"}</th>
                        <th>${((o=n.fine_tune)==null?void 0:o.created_at)||"Created"}</th>
                    </tr>
                </thead>
                <tbody>`;s.forEach(function(d){const f={pending:"bg-secondary",running:"bg-warning",succeeded:"bg-success",failed:"bg-danger",cancelled:"bg-secondary"}[d.status]||"bg-secondary";e+=`
                <tr>
                    <td><code>${d.job_id||d.id||"-"}</code></td>
                    <td><span class="badge ${f}">${d.status||"-"}</span></td>
                    <td>${d.model||"-"}</td>
                    <td><small>${d.created_at||"-"}</small></td>
                </tr>`}),e+="</tbody></table>",t.innerHTML=e}document.getElementById("fineTuneJobsContainer")&&x()});
