<template>
  <div class="skills-view">
    <a-page-header
      title="Skill 管理"
      sub-title="启用/停用、导入、重载与编辑技能配置"
      class="skills-view__header"
    >
      <template #extra>
        <a-space :size="8">
          <a-button @click="loadSkills" :loading="loading">刷新</a-button>
          <a-button type="primary" @click="openImport">导入 Skill</a-button>
        </a-space>
      </template>
    </a-page-header>

    <a-card class="skills-view__card">
      <a-table
        :columns="columns"
        :data-source="skills"
        :row-key="(record: ISkillInfo) => record.name"
        :loading="loading"
        :pagination="{ pageSize: 20, showSizeChanger: true }"
        size="middle"
      >
        <template #bodyCell="{ column, record }: { column: TableColumnType<ISkillInfo>; record: ISkillInfo }">
          <template v-if="column.key === 'name'">
            <strong>{{ record.name }}</strong>
          </template>
          <template v-else-if="column.key === 'status'">
            <a-tag :color="isDisabled(record) ? 'default' : 'green'">
              {{ isDisabled(record) ? '已停用' : '启用' }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'capabilities'">
            <a-space :size="4" wrap>
              <a-tag v-for="c in record.capabilities ?? []" :key="c" color="blue">{{ c }}</a-tag>
              <span v-if="!record.capabilities || record.capabilities.length === 0">—</span>
            </a-space>
          </template>
          <template v-else-if="column.key === 'actions'">
            <a-space :size="4">
              <a-button
                type="link"
                size="small"
                @click="handleToggle(record)"
              >
                {{ isDisabled(record) ? '启用' : '停用' }}
              </a-button>
              <a-button type="link" size="small" @click="handleReload(record)">重载</a-button>
              <a-button type="link" size="small" @click="openEditConfig(record)">编辑配置</a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- Import skill modal -->
    <a-modal
      v-model:open="importOpen"
      title="导入 Skill"
      :confirm-loading="importing"
      ok-text="导入"
      cancel-text="取消"
      width="640px"
      @ok="handleImport"
    >
      <a-alert
        message="粘贴 Skill 的 YAML 配置内容，导入后将自动注册到技能目录。"
        type="info"
        show-icon
        style="margin-bottom: 16px"
      />
      <a-textarea
        v-model:value="importYaml"
        :rows="14"
        placeholder="name: my-skill&#10;version: 1.0.0&#10;description: ...&#10;..."
        style="font-family: var(--font-mono, monospace)"
      />
    </a-modal>

    <!-- Edit config modal -->
    <a-modal
      v-model:open="configOpen"
      :title="`编辑配置 — ${configTarget}`"
      :confirm-loading="savingConfig"
      ok-text="保存"
      cancel-text="取消"
      width="640px"
      @ok="handleSaveConfig"
    >
      <a-alert
        message="以 JSON 格式编辑技能配置，保存后将自动重载。"
        type="info"
        show-icon
        style="margin-bottom: 16px"
      />
      <a-textarea
        v-model:value="configText"
        :rows="14"
        placeholder='{ "key": "value" }'
        style="font-family: var(--font-mono, monospace)"
      />
    </a-modal>
  </div>
</template>

<script setup lang="ts">
/**
 * Skill management view — list, enable/disable, import, reload, edit config.
 *
 * Uses the existing ``skillsApi`` for listing (``/api/v1/skill-management/skills``)
 * and the admin API for enable/disable/import/reload/update-config.
 */
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import type { TableColumnType } from 'ant-design-vue'
import { skillsApi, type ISkillInfo } from '@/api/skills'
import { adminApi } from '@/api/admin'

const skills = ref<ISkillInfo[]>([])
const loading = ref(false)

const columns: TableColumnType<ISkillInfo>[] = [
  { title: '名称', key: 'name', dataIndex: 'name', width: 200 },
  { title: '版本', key: 'version', dataIndex: 'version', width: 100 },
  { title: '描述', key: 'description', dataIndex: 'description', ellipsis: true },
  { title: '能力', key: 'capabilities', width: 240 },
  { title: '状态', key: 'status', width: 100 },
  { title: '操作', key: 'actions', width: 240, fixed: 'right' },
]

/** A skill is considered disabled when its status is 'disabled'. */
function isDisabled(record: ISkillInfo): boolean {
  return record.status === 'disabled'
}

async function loadSkills(): Promise<void> {
  loading.value = true
  try {
    const res = await skillsApi.listSkills(undefined, 1, 200)
    skills.value = res.skills
  } catch (err) {
    message.error(extractMessage(err, '加载技能列表失败'))
  } finally {
    loading.value = false
  }
}

async function handleToggle(record: ISkillInfo): Promise<void> {
  try {
    if (isDisabled(record)) {
      await adminApi.enableSkill(record.name)
      message.success('技能已启用')
    } else {
      await adminApi.disableSkill(record.name)
      message.success('技能已停用')
    }
    await loadSkills()
  } catch (err) {
    message.error(extractMessage(err, '操作失败'))
  }
}

async function handleReload(record: ISkillInfo): Promise<void> {
  try {
    await adminApi.reloadSkill(record.name)
    message.success(`技能 ${record.name} 已重载`)
    await loadSkills()
  } catch (err) {
    message.error(extractMessage(err, '重载技能失败'))
  }
}

// Import
const importOpen = ref(false)
const importing = ref(false)
const importYaml = ref('')

function openImport(): void {
  importYaml.value = ''
  importOpen.value = true
}

async function handleImport(): Promise<void> {
  if (!importYaml.value.trim()) {
    message.warning('请输入 YAML 内容')
    return
  }
  importing.value = true
  try {
    await adminApi.importSkill(importYaml.value)
    message.success('技能已导入')
    importOpen.value = false
    await loadSkills()
  } catch (err) {
    message.error(extractMessage(err, '导入技能失败'))
  } finally {
    importing.value = false
  }
}

// Edit config
const configOpen = ref(false)
const savingConfig = ref(false)
const configTarget = ref('')
const configText = ref('')

async function openEditConfig(record: ISkillInfo): Promise<void> {
  configTarget.value = record.name
  configOpen.value = true
  try {
    const detail = await skillsApi.getSkillDetail(record.name)
    configText.value = JSON.stringify(detail.config ?? {}, null, 2)
  } catch (err) {
    // If detail fetch fails, start with empty JSON object
    configText.value = '{}'
    message.warning(extractMessage(err, '加载技能配置失败，将以空配置开始'))
  }
}

async function handleSaveConfig(): Promise<void> {
  let parsed: Record<string, unknown>
  try {
    parsed = JSON.parse(configText.value) as Record<string, unknown>
  } catch {
    message.error('JSON 格式错误，请检查')
    return
  }
  savingConfig.value = true
  try {
    await adminApi.updateSkillConfig(configTarget.value, parsed)
    message.success('配置已保存并重载')
    configOpen.value = false
    await loadSkills()
  } catch (err) {
    message.error(extractMessage(err, '保存配置失败'))
  } finally {
    savingConfig.value = false
  }
}

// --- Helpers ---
function extractMessage(err: unknown, fallback: string): string {
  if (err && typeof err === 'object') {
    const obj = err as { detail?: unknown; message?: unknown }
    if (typeof obj.detail === 'string' && obj.detail) return obj.detail
    if (typeof obj.message === 'string' && obj.message) return obj.message
  }
  return fallback
}

onMounted(() => {
  loadSkills()
})
</script>

<style scoped>
.skills-view {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.skills-view__header {
  margin-bottom: 16px;
}

.skills-view__card {
  margin-top: 8px;
}
</style>
