// 파일 ✨/mnt/d/D/_NR_/__AIWK_COMM_St/aiwk/AIWK_COMMON/domains/chatgpt.com/g/call.js
// ChatGPT /g/ 고정 액션 파일. 도메인 특수 파일명 금지 원칙에 따라 call.js에 수용한다.
(function(){
  "use strict";
  function findPrompt(){
    return document.querySelector("#prompt-textarea") || document.querySelector("textarea") || document.querySelector("[contenteditable='true']");
  }
  function appendPrompt(text){
    const target = findPrompt();
    if(!target) return {ok:0, code:"CHATGPT_PROMPT_NOT_FOUND", selector:"#prompt-textarea"};
    const value = String(text || "");
    const sep = "\n\n";
    target.focus();
    if(target.tagName === "TEXTAREA" || target.tagName === "INPUT"){
      const oldValue = String(target.value || "");
      target.value = oldValue ? oldValue.replace(/\s*$/, "") + sep + value : value;
      target.selectionStart = target.selectionEnd = target.value.length;
      target.dispatchEvent(new Event("input", {bubbles:true}));
      target.dispatchEvent(new Event("change", {bubbles:true}));
      return {ok:1, code:"CHATGPT_PROMPT_APPENDED", len:target.value.length};
    }
    const oldText = String(target.innerText || target.textContent || "");
    const insertValue = oldText ? sep + value : value;
    try{
      const sel = window.getSelection ? window.getSelection() : null;
      const range = document.createRange();
      range.selectNodeContents(target); range.collapse(false);
      if(sel){ sel.removeAllRanges(); sel.addRange(range); }
      if(document.execCommand) document.execCommand("insertText", false, insertValue);
      else target.textContent = oldText + insertValue;
    }catch(e){ target.textContent = oldText + insertValue; }
    try{ target.dispatchEvent(new InputEvent("input", {bubbles:true, inputType:"insertText", data:insertValue})); }catch(e){ target.dispatchEvent(new Event("input", {bubbles:true})); }
    return {ok:1, code:"CHATGPT_PROMPT_APPENDED", len:String(target.innerText || target.textContent || "").length};
  }
  window.AIWK_DOMAIN_CALL = window.AIWK_DOMAIN_CALL || {};
  window.AIWK_DOMAIN_CALL["chatgpt.com/g"] = function(action, payload){
    payload = payload || {};
    if(action === "prompt_append" || action === "diagnostic_append") return appendPrompt(payload.text || payload.prompt || "");
    return {ok:0, code:"UNKNOWN_CHATGPT_G_ACTION", action:action || ""};
  };
}());
