/* eslint-disable no-console */
const fs = require('fs-extra');
const path = require('path');

// 配置 - 相对于组件库源码目录
const ROOT_DIR = path.resolve(__dirname, '..');
const COMPONENTS_DIR = path.join(ROOT_DIR, 'components');
const OUTPUT_DIR = path.join(ROOT_DIR, 'skills', 'antdv');
const COMPONENTS_OUTPUT_DIR = path.join(OUTPUT_DIR, 'components');

// 主函数
async function generate() {
  console.log('开始生成antdv skill...');

  // 清空输出目录
  await fs.remove(OUTPUT_DIR);
  await fs.ensureDir(OUTPUT_DIR);
  await fs.ensureDir(COMPONENTS_OUTPUT_DIR);

  // 获取所有组件目录
  const items = await fs.readdir(COMPONENTS_DIR);
  const components = [];

  for (const item of items) {
    const itemPath = path.join(COMPONENTS_DIR, item);
    const stat = await fs.stat(itemPath);

    // 只处理目录，忽略vc-开头的目录
    if (stat.isDirectory() && !item.startsWith('vc-')) {
      // 检查是否有index.zh-CN.md文件
      const indexFile = path.join(itemPath, 'index.zh-CN.md');
      if (await fs.exists(indexFile)) {
        components.push({
          name: item,
          path: itemPath,
          indexFile,
        });
      }
    }
  }

  console.log(`找到 ${components.length} 个组件`);

  // 处理每个组件
  const componentList = [];

  for (const component of components) {
    console.log(`处理组件: ${component.name}`);

    // 创建组件输出目录
    const componentOutputDir = path.join(COMPONENTS_OUTPUT_DIR, component.name);
    await fs.ensureDir(componentOutputDir);

    // 创建demos子目录
    const demosOutputDir = path.join(componentOutputDir, 'demos');
    await fs.ensureDir(demosOutputDir);

    // 复制index.zh-CN.md
    const indexContent = await fs.readFile(component.indexFile, 'utf8');
    await fs.writeFile(path.join(componentOutputDir, 'index.zh-CN.md'), indexContent);

    // 处理demo目录
    const demoDir = path.join(component.path, 'demo');
    const demos = [];

    if (await fs.exists(demoDir)) {
      const demoFiles = await fs.readdir(demoDir);

      for (const demoFile of demoFiles) {
        // 忽略index.vue
        if (demoFile === 'index.vue') continue;

        const demoPath = path.join(demoDir, demoFile);
        const demoStat = await fs.stat(demoPath);

        // 只处理.vue文件
        if (demoStat.isFile() && demoFile.endsWith('.vue')) {
          const demoName = path.basename(demoFile, '.vue');
          const demoContent = await fs.readFile(demoPath, 'utf8');

          // 转换.vue为.md
          const mdContent = convertVueToMd(demoName, demoContent);

          // 写入.md文件到demos目录
          await fs.writeFile(path.join(demosOutputDir, `${demoName}.md`), mdContent);

          demos.push({
            name: demoName,
            file: `demos/${demoName}.md`,
          });
        }
      }
    }

    // 提取组件信息
    const componentInfo = extractComponentInfo(indexContent);

    componentList.push({
      name: component.name,
      title: componentInfo.title,
      subtitle: componentInfo.subtitle,
      description: componentInfo.description,
      demos,
      indexFile: `components/${component.name}/index.zh-CN.md`,
    });
  }

  // 生成SKILL.md
  await generateSkillMd(componentList);

  console.log('生成完成！');
  console.log(`输出目录: ${OUTPUT_DIR}`);
}

// 将.vue文件转换为.md格式
function convertVueToMd(name, content) {
  let description = '';
  let template = '';
  let script = '';
  let style = '';

  // 提取docs部分
  const docsMatch = content.match(/<docs>([\s\S]*?)<\/docs>/);
  if (docsMatch) {
    const docsContent = docsMatch[1];

    // 提取中文描述
    const zhCnMatch = docsContent.match(/## zh-CN\s*\n([\s\S]*?)(?=\n## en-US|$)/);
    if (zhCnMatch) {
      description = zhCnMatch[1].trim();
    }
  }

  // 提取template部分
  const templateMatch = content.match(/<template>([\s\S]*?)<\/template>/);
  if (templateMatch) {
    template = templateMatch[1].trim();
  }

  // 提取script部分
  const scriptMatch = content.match(/<script[^>]*>([\s\S]*?)<\/script>/);
  if (scriptMatch) {
    script = scriptMatch[1].trim();
  }

  // 提取style部分
  const styleMatch = content.match(/<style[^>]*>([\s\S]*?)<\/style>/);
  if (styleMatch) {
    style = styleMatch[1].trim();
  }

  // 生成md内容
  let mdContent = `## ${name}\n\n`;

  if (description) {
    mdContent += `${description}\n\n`;
  }

  mdContent += '```vue\n';

  if (template) {
    mdContent += `<template>\n${template}\n</template>\n\n`;
  }

  if (script) {
    mdContent += `<script>\n${script}\n</script>\n\n`;
  }

  if (style) {
    mdContent += `<style>\n${style}\n</style>\n`;
  }

  mdContent += '```\n';

  return mdContent;
}

// 提取组件信息
function extractComponentInfo(content) {
  const info = {
    title: '',
    subtitle: '',
    description: '',
  };

  // 提取frontmatter
  const frontmatterMatch = content.match(/---\n([\s\S]*?)\n---/);
  if (frontmatterMatch) {
    const frontmatter = frontmatterMatch[1];

    // 提取title
    const titleMatch = frontmatter.match(/title:\s*(.*)/);
    if (titleMatch) {
      info.title = titleMatch[1].trim();
    }

    // 提取subtitle
    const subtitleMatch = frontmatter.match(/subtitle:\s*(.*)/);
    if (subtitleMatch) {
      info.subtitle = subtitleMatch[1].trim();
    }
  }

  // 提取描述（第一个段落）
  const descMatch = content.match(/---\n[\s\S]*?\n---\n\n([\s\S]*?)(?=\n##|$)/);
  if (descMatch) {
    info.description = descMatch[1].trim();
  }

  return info;
}

// 生成SKILL.md文件
async function generateSkillMd(componentList) {
  const today = new Date().toISOString().split('T')[0];

  let content = `---
name: antdv
description: Use when the user's task involves @aplus-frontend/antdv components — writing antdv component code, querying API/props/events/slots, finding usage demos, checking component availability, or referencing component documentation. Triggers on '@aplus-frontend/antdv' imports or explicit antdv component questions.
metadata:
  author: Antdv team
  version: "${today}"
  source: Generated from @aplus-frontend/antdv components
---

# Antdv

> The skill is based on Antdv docs and demos, generated at ${today}.

Language: zh-CN

Docs and demos are copied into \`components/\` for offline use.

## Components

| Component | Doc | Demos |
|-----------|-----|-------|
`;

  // 添加组件表格
  for (const component of componentList) {
    const demoCount = component.demos.length;
    content += `| ${component.name} | components/${component.name}/index.zh-CN.md | components/${component.name}/demos/ (${demoCount}) |\n`;
  }

  content += `
## Generate / Update

\`\`\`bash
node scripts/generate-antdv-skill.js
\`\`\`
`;

  await fs.writeFile(path.join(OUTPUT_DIR, 'SKILL.md'), content);
}

// 运行生成
generate().catch(console.error);
