<template>
  <el-drawer v-model="visible" :title="skill?.label || skill?.name || 'Skill 详情'" size="500px">
    <template v-if="skill">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="基本信息" name="info" lazy>
          <div class="detail-section">
            <div class="detail-label">基本信息</div>
            <div class="detail-row">
              <span>名称：</span><span>{{ skill.name }}</span>
            </div>
            <div class="detail-row">
              <span>类型：</span><el-tag size="small">{{ skill.skillType || '-' }}</el-tag>
              <el-tag v-if="skill.classification" size="small" :type="skill.classification === 'compute-entry' ? 'success' : skill.classification === 'compute-toolkit' ? 'primary' : 'info'" style="margin-left: 4px">
                {{ skill.classification }}
              </el-tag>
            </div>
            <div class="detail-row">
              <span>来源：</span><el-tag size="small" :type="skill.source === 'github' ? 'warning' : 'success'">{{ skill.source || 'local' }}</el-tag>
            </div>
            <div v-if="skill.sourceUrl" class="detail-row">
              <span>URL：</span><a :href="skill.sourceUrl" target="_blank">{{ skill.sourceUrl }}</a>
            </div>
            <div v-if="skill.version" class="detail-row">
              <span>版本：</span><span>{{ skill.version }}</span>
            </div>
            <div v-if="skill.installedAt" class="detail-row">
              <span>安装时间：</span><span>{{ skill.installedAt }}</span>
            </div>
          </div>

          <div class="detail-section">
            <div class="detail-label">SKILL.md 内容</div>
            <div v-if="skillContent" class="skill-content" v-html="renderedContent" />
            <el-button v-else size="small" @click="loadContent">加载内容</el-button>
          </div>

          <div v-if="skill.metadata?.install" class="detail-section">
            <div class="detail-label">依赖</div>
            <div v-for="dep in (skill.metadata.install as any[])" :key="dep.id" class="detail-row">
              <el-tag size="small" type="info">{{ dep.kind }}</el-tag>
              <span style="margin-left: 8px">{{ dep.package || dep.label }}</span>
            </div>
            <el-button size="small" style="margin-top: 8px" @click="handleInstallDeps">安装依赖</el-button>
          </div>

          <div v-if="skill.metadata?.conditions" class="detail-section">
            <div class="detail-label">条件激活</div>
            <div v-if="skill.metadata.conditions.requires_tools" class="detail-row">
              <span>需要工具：</span>
              <el-tag v-for="t in skill.metadata.conditions.requires_tools" :key="t" size="small" style="margin: 2px">{{ t }}</el-tag>
            </div>
            <div v-if="skill.metadata.conditions.fallback_for_tools" class="detail-row">
              <span>替代工具：</span>
              <el-tag v-for="t in skill.metadata.conditions.fallback_for_tools" :key="t" size="small" style="margin: 2px">{{ t }}</el-tag>
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="配置" name="config" lazy>
          <div v-if="envSchema.length === 0" class="empty-hint">此 Skill 无需配置环境变量</div>
          <div v-else>
            <div v-for="item in envSchema" :key="item.name" class="env-row">
              <div class="env-label">
                <span>{{ item.name }}</span>
                <el-tag v-if="item.required" size="small" type="danger">必填</el-tag>
                <el-tag v-if="getConfiguredStatus(item.name)" size="small" type="success">已配置</el-tag>
              </div>
              <div v-if="item.description" class="env-desc">{{ item.description }}</div>
              <el-input
                v-model="secretValues[item.name]"
                :placeholder="getConfiguredStatus(item.name) ? '已配置（留空则不修改）' : item.default || '请输入'"
                show-password
              />
            </div>
            <el-button type="primary" style="margin-top: 16px" @click="handleSaveSecrets">保存配置</el-button>
          </div>
        </el-tab-pane>

        <el-tab-pane label="诊断" name="diagnostics" lazy>
          <div v-if="skillDiagnostics.length === 0" class="empty-hint">无诊断信息</div>
          <div v-else>
            <div v-for="(d, i) in skillDiagnostics" :key="i" class="diag-item">
              <el-tag :type="d.level === 'error' ? 'danger' : d.level === 'warning' ? 'warning' : 'info'" size="small">
                {{ d.code }}
              </el-tag>
              <span>{{ d.message }}</span>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { useCool } from '/@/cool';

const props = defineProps<{ skill: any }>();
defineEmits(['updated']);
const visible = defineModel<boolean>();
const { service } = useCool();

const activeTab = ref('info');
const skillContent = ref('');
const envSchema = ref<any[]>([]);
const configuredKeys = ref<any[]>([]);
const secretValues = ref<Record<string, string>>({});
const skillDiagnostics = ref<any[]>([]);

const renderedContent = computed(() => {
  return skillContent.value
    .replace(/^### (.+)$/gm, '<h4>$1</h4>')
    .replace(/^## (.+)$/gm, '<h3>$1</h3>')
    .replace(/^# (.+)$/gm, '<h2>$1</h2>')
    .replace(/\n/g, '<br/>');
});

function getConfiguredStatus(name: string): boolean {
  return configuredKeys.value.find((k: any) => k.name === name)?.hasValue || false;
}

watch(() => props.skill, () => {
  activeTab.value = 'info';
  skillContent.value = '';
  secretValues.value = {};
  loadEnvSchema();
  loadSkillDiagnostics();
});

async function loadContent() {
  try {
    const res = await service.request({
      url: '/admin/netaclaw/skill/content',
      params: { name: props.skill.name },
    });
    skillContent.value = res?.content || '(无内容)';
  } catch {
    ElMessage.error('加载失败');
  }
}

async function handleInstallDeps() {
  try {
    await service.request({
      url: '/admin/netaclaw/skill/installDeps',
      method: 'POST',
      data: { name: props.skill.name },
    });
    ElMessage.success('依赖安装完成');
  } catch (e: any) {
    ElMessage.error(e.message || '安装失败');
  }
}

async function loadEnvSchema() {
  if (!props.skill?.name) return;
  try {
    const res = await service.request({
      url: '/admin/netaclaw/skill/envSchema',
      params: { name: props.skill.name },
    });
    envSchema.value = res?.schema || [];
    configuredKeys.value = res?.configured || [];
  } catch { /* ignore */ }
}

async function handleSaveSecrets() {
  const nonEmpty = Object.fromEntries(
    Object.entries(secretValues.value).filter(([_, v]) => v.trim())
  );
  if (Object.keys(nonEmpty).length === 0) {
    ElMessage.warning('请至少填写一个配置项');
    return;
  }
  try {
    await service.request({
      url: '/admin/netaclaw/skill/secrets',
      method: 'POST',
      data: { name: props.skill.name, secrets: nonEmpty },
    });
    ElMessage.success('配置已保存');
    secretValues.value = {};
    await loadEnvSchema();
  } catch (e: any) {
    ElMessage.error(e.message || '保存失败');
  }
}

async function loadSkillDiagnostics() {
  if (!props.skill?.name) return;
  try {
    const res = await service.request({ url: '/admin/netaclaw/skill/diagnostics' });
    skillDiagnostics.value = (res || []).filter((d: any) => d.skillName === props.skill.name);
  } catch { /* ignore */ }
}
</script>

<style scoped>
.detail-section { margin-bottom: 24px; }
.detail-label { font-weight: 600; font-size: 14px; margin-bottom: 8px; color: #303133; }
.detail-row { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; font-size: 13px; color: #606266; }
.skill-content { background: #f5f7fa; border-radius: 6px; padding: 16px; font-size: 13px; line-height: 1.6; max-height: 400px; overflow-y: auto; }
.empty-hint { color: #909399; font-size: 13px; padding: 20px 0; text-align: center; }
.env-row { margin-bottom: 16px; }
.env-label { display: flex; align-items: center; gap: 8px; margin-bottom: 4px; font-weight: 500; font-size: 13px; }
.env-desc { font-size: 12px; color: #909399; margin-bottom: 4px; }
.diag-item { display: flex; align-items: center; gap: 8px; padding: 8px 0; font-size: 13px; border-bottom: 1px solid #f0f0f0; }
</style>
