import { ref } from "vue";
import { Schema } from "effect";
import { ai as $ai } from "../utils/ai/index.js";
const SingleTranslation = Schema.Struct({
  message: Schema.String
}).annotations({ identifier: "LocaleSingleTranslation" });
const TARGET_LANG_LABEL = {
  ja: "Japanese",
  en: "English",
  ko: "Korean"
};
function buildSystem(target, hint) {
  const surface = hint ?? "a UI label";
  const lang = TARGET_LANG_LABEL[target];
  return [
    "You are a UI string translator for an enterprise admin console.",
    `Translate the Chinese source into ${lang} for ${surface}.`,
    "Output must be terse, idiomatic, and stylistically appropriate for the surface.",
    "Preserve placeholders (e.g. {name}, %s), punctuation density, and casing conventions of the target language.",
    "Never translate brand names, product names, or technical identifiers."
  ].join(" ");
}
export function useTranslateLocale(options = {}) {
  const inFlight = ref(/* @__PURE__ */ new Set());
  function isTranslating(target) {
    return inFlight.value.has(target);
  }
  function canTranslate(current, target) {
    if (!$ai.available.value) return false;
    if (!current) return false;
    const zh = current.find((item) => item.locale === "zh");
    if (!zh || !zh.message.trim()) return false;
    const row = current.find((item) => item.locale === target);
    if (!row) return false;
    if (row.message.trim().length > 0) return false;
    return true;
  }
  async function translate(current, target) {
    const zh = current.find((item) => item.locale === "zh");
    if (!zh || !zh.message.trim()) {
      throw new Error("\u9700\u8981\u5148\u586B\u5199\u4E2D\u6587\u6587\u672C\u4F5C\u4E3A\u7FFB\u8BD1\u6765\u6E90");
    }
    const start = new Set(inFlight.value);
    start.add(target);
    inFlight.value = start;
    try {
      const result = await $ai.generateObject({
        prompt: zh.message,
        system: buildSystem(target, options.hint),
        schema: SingleTranslation,
        objectName: "translation"
      });
      return current.map((item) => {
        if (item.locale !== target) return item;
        if (item.message.trim().length > 0) return item;
        return { locale: item.locale, message: result.message };
      });
    } finally {
      const end = new Set(inFlight.value);
      end.delete(target);
      inFlight.value = end;
    }
  }
  return { isTranslating, canTranslate, translate };
}
