<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { generateQuickOptimization, generateSmartOptimization } from '@/api/modules/optimization'

const router = useRouter()

const activeMode = ref('smart')

const smartInput = ref('')
const smartLoading = ref(false)
const intentDisplay = ref('')
const smartResult = ref('')

const quickInput = ref('')
const quickLoading = ref(false)
const quickResult = ref('')

async function onSmartSubmit() {
  const t = smartInput.value.trim()
  if (!t) {
    ElMessage.warning('请描述您的需求或粘贴待优化的提示词')
    return
  }
  smartLoading.value = true
  intentDisplay.value = ''
  smartResult.value = ''
  try {
    const res = await generateSmartOptimization({ input_text: t })
    if (res.code !== 200 || !res.data) {
      ElMessage.error(res.message || '生成失败')
      return
    }
    intentDisplay.value = JSON.stringify(res.data.intent_analysis, null, 2)
    smartResult.value = res.data.generated_prompt
    ElMessage.success('优化完成（已写入历史）')
  } catch {
    ElMessage.error('请求失败，请确认后端可用')
  } finally {
    smartLoading.value = false
  }
}

async function onQuickSubmit() {
  const t = quickInput.value.trim()
  if (!t) {
    ElMessage.warning('请输入需求描述')
    return
  }
  quickLoading.value = true
  quickResult.value = ''
  try {
    const res = await generateQuickOptimization({ input_text: t })
    if (!res.success || !res.data) {
      ElMessage.error(res.message || '生成失败')
      return
    }
    quickResult.value = res.data.generated_text
    ElMessage.success('优化完成')
  } catch {
    ElMessage.error('请求失败')
  } finally {
    quickLoading.value = false
  }
}

async function copyText(text: string, label: string) {
  if (!text) return
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success(`已复制${label}`)
  } catch {
    ElMessage.error('复制失败')
  }
}
</script>

<template>
  <div class="opt-page">
    <el-page-header class="page-head" @back="router.push({ name: 'home' })">
      <template #content>
        <span class="page-title">提示词优化</span>
      </template>
    </el-page-header>
    <p class="hint">
      <strong>智能优化</strong>对接
      <code>/api/smart-prompt-optimization/generate</code>
      （意图分析 + 专家级输出）；<strong>快速优化</strong>对接
      <code>/api/prompt-optimization/generate</code>
      。
    </p>

    <el-tabs v-model="activeMode" class="tabs">
      <el-tab-pane label="智能优化（两阶段）" name="smart">
        <el-card shadow="never" class="section">
          <el-input
            v-model="smartInput"
            type="textarea"
            :rows="10"
            maxlength="8000"
            show-word-limit
            placeholder="请描述需求，或粘贴一段希望改写成「专家级提示词」的原文…"
          />
          <div class="actions">
            <el-button type="primary" :loading="smartLoading" @click="onSmartSubmit">
              生成专家级提示词
            </el-button>
          </div>
        </el-card>

        <template v-if="intentDisplay || smartResult">
          <el-card v-if="intentDisplay" shadow="never" class="section">
            <template #header>
              <div class="result-head">
                <span>意图分析</span>
                <el-button size="small" @click="copyText(intentDisplay, '意图分析')">复制 JSON</el-button>
              </div>
            </template>
            <pre class="result-pre">{{ intentDisplay }}</pre>
          </el-card>
          <el-card v-if="smartResult" shadow="never" class="section highlight">
            <template #header>
              <div class="result-head">
                <span>专家级提示词</span>
                <el-button type="primary" size="small" @click="copyText(smartResult, '提示词')">
                  复制
                </el-button>
              </div>
            </template>
            <pre class="result-pre">{{ smartResult }}</pre>
          </el-card>
        </template>
      </el-tab-pane>

      <el-tab-pane label="快速优化（通用模板）" name="quick">
        <el-card shadow="never" class="section">
          <el-input
            v-model="quickInput"
            type="textarea"
            :rows="10"
            maxlength="4000"
            show-word-limit
            placeholder="输入简短需求描述，使用站内默认「通用提示词优化」模板生成结构化 Prompt…"
          />
          <div class="actions">
            <el-button type="primary" :loading="quickLoading" @click="onQuickSubmit">快速优化</el-button>
          </div>
        </el-card>
        <el-card v-if="quickResult" shadow="never" class="section highlight">
          <template #header>
            <div class="result-head">
              <span>优化结果</span>
              <el-button type="primary" size="small" @click="copyText(quickResult, '结果')">
                复制
              </el-button>
            </div>
          </template>
          <pre class="result-pre">{{ quickResult }}</pre>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<style scoped lang="scss">
@use '@/assets/styles/variables' as *;

.opt-page {
  .page-head {
    margin-bottom: 0.5rem;
  }

  .page-title {
    font-weight: 600;
    font-size: 1.125rem;
  }

  .hint {
    margin: 0 0 1rem;
    font-size: 0.875rem;
    line-height: 1.55;
    color: $text-secondary;

    code {
      font-size: 0.78em;
      padding: 0.1em 0.35em;
      background: $gray-100;
      border-radius: 4px;
    }
  }

  .tabs {
    margin-top: 0.25rem;
  }

  .section {
    margin-bottom: 1rem;
    border-radius: 12px;
    border: 1px solid $border-color;

    &.highlight {
      border-color: rgba(99, 102, 241, 0.35);
    }
  }

  .actions {
    margin-top: 1rem;
  }

  .result-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
  }

  .result-pre {
    margin: 0;
    white-space: pre-wrap;
    word-break: break-word;
    font-family: ui-monospace, 'Cascadia Code', Consolas, monospace;
    font-size: 0.875rem;
    line-height: 1.55;
    color: $text-color;
  }
}
</style>
