import { readFileSync, existsSync, readdirSync } from 'node:fs';
import { d as dirname, j as join, b as basename } from './ccjk.bQ7Dh1g4.mjs';

const PRIORITY_KEYWORDS = {
  critical: "critical",
  CRITICAL: "critical",
  \u5173\u952E: "critical",
  high: "high",
  HIGH: "high",
  \u9AD8: "high",
  medium: "medium",
  MEDIUM: "medium",
  \u4E2D: "medium",
  low: "low",
  LOW: "low",
  \u4F4E: "low"
};
class SkillParser {
  /**
   * Parse a SKILL.md file
   *
   * @param filePath - Path to SKILL.md file
   * @returns Parsed skill document
   */
  parse(filePath) {
    const content = readFileSync(filePath, "utf-8");
    return this.parseContent(content, dirname(filePath));
  }
  /**
   * Parse SKILL.md content
   *
   * @param content - Raw markdown content
   * @param basePath - Base path for resolving references
   * @returns Parsed skill document
   */
  parseContent(content, basePath) {
    const lines = content.split("\n");
    const title = this.extractTitle(lines);
    const description = this.extractDescription(lines);
    const applicability = this.extractApplicability(content);
    const sections = this.extractSections(content);
    const rules = this.extractRules(content, basePath);
    const examples = this.extractExamples(content);
    return {
      title,
      description,
      applicability,
      sections,
      rules,
      examples,
      rawContent: content
    };
  }
  /**
   * Parse a skill directory (SKILL.md + references/)
   *
   * @param dirPath - Path to skill directory
   * @returns Parsed skill document with references
   */
  parseDirectory(dirPath) {
    const skillPath = join(dirPath, "SKILL.md");
    if (!existsSync(skillPath)) {
      throw new Error(`SKILL.md not found in ${dirPath}`);
    }
    const skill = this.parse(skillPath);
    const references = this.loadReferences(dirPath);
    return {
      ...skill,
      references
    };
  }
  // ==========================================================================
  // Extraction Methods
  // ==========================================================================
  /**
   * Extract title from markdown
   */
  extractTitle(lines) {
    for (const line of lines) {
      const match = line.match(/^#\s+(.+)$/);
      if (match) {
        return match[1].trim();
      }
    }
    return "Untitled Skill";
  }
  /**
   * Extract description from markdown
   */
  extractDescription(lines) {
    let inDescription = false;
    const descLines = [];
    for (const line of lines) {
      if (line.match(/^#\s+/)) {
        inDescription = true;
        continue;
      }
      if (line.match(/^##\s+/)) {
        break;
      }
      if (inDescription && line.trim()) {
        descLines.push(line);
      }
    }
    return descLines.join("\n").trim();
  }
  /**
   * Extract applicability section
   */
  extractApplicability(content) {
    const applicability = {
      taskTypes: [],
      fileTypes: [],
      contexts: []
    };
    const applicabilityMatch = content.match(
      /##\s*(?:When to Apply|Applicability|适用场景|何时使用)[^\n]*\n([\s\S]*?)(?=\n##|\n$|$)/i
    );
    if (applicabilityMatch) {
      const section = applicabilityMatch[1];
      const taskMatches = section.matchAll(/[-*]\s*(.+)/g);
      for (const match of taskMatches) {
        const task = match[1].trim();
        if (task) {
          applicability.taskTypes.push(task);
        }
      }
    }
    const fileTypeMatch = content.match(
      /(?:file types?|文件类型)[:\s]*([^\n]+)/i
    );
    if (fileTypeMatch) {
      applicability.fileTypes = fileTypeMatch[1].split(/[,，]/).map((t) => t.trim()).filter(Boolean);
    }
    return applicability;
  }
  /**
   * Extract sections from markdown
   */
  extractSections(content) {
    const sections = [];
    const lines = content.split("\n");
    let currentSection = null;
    let currentContent = [];
    let currentSubsections = [];
    for (const line of lines) {
      const h2Match = line.match(/^##\s+(.+)$/);
      if (h2Match) {
        if (currentSection) {
          currentSection.content = currentContent.join("\n").trim();
          currentSection.subsections = currentSubsections.length > 0 ? currentSubsections : void 0;
          sections.push(currentSection);
        }
        currentSection = {
          title: h2Match[1].trim(),
          content: "",
          priority: this.detectPriority(h2Match[1])
        };
        currentContent = [];
        currentSubsections = [];
        continue;
      }
      const h3Match = line.match(/^###\s+(.+)$/);
      if (h3Match && currentSection) {
        currentSubsections.push({
          title: h3Match[1].trim(),
          content: "",
          // Will be filled by subsequent lines
          priority: this.detectPriority(h3Match[1])
        });
        continue;
      }
      if (currentSection) {
        currentContent.push(line);
      }
    }
    if (currentSection) {
      currentSection.content = currentContent.join("\n").trim();
      currentSection.subsections = currentSubsections.length > 0 ? currentSubsections : void 0;
      sections.push(currentSection);
    }
    return sections;
  }
  /**
   * Extract rules from markdown
   */
  extractRules(content, basePath) {
    const rules = [];
    const rulePattern = /##?\s*(?:`([a-z]+-\d+)`|(\w+-\d+))[:\s]*(.+?)(?=\n##?|\n##|$)/gs;
    let match;
    while ((match = rulePattern.exec(content)) !== null) {
      const id = match[1] || match[2];
      const titleAndContent = match[3];
      const titleMatch = titleAndContent.match(/^[:\s]*(.+)(?:\n|$)/);
      const title = titleMatch ? titleMatch[1].trim() : id;
      const category = id.split("-")[0];
      const priority = this.detectPriority(titleAndContent);
      const description = titleAndContent.replace(/^[:\s]*(.+)(?:\n|$)/, "").trim();
      let referencePath;
      if (basePath) {
        const refPath = join(basePath, "references", "rules", `${id}.md`);
        if (existsSync(refPath)) {
          referencePath = refPath;
        }
      }
      rules.push({
        id,
        title,
        category,
        priority,
        description,
        referencePath
      });
    }
    const numberedPattern = /(?:^|\n)(\d+)\.\s+\*\*(.+?)\*\*[:\s]*(.+?)(?=\n\d+\.|\n##|$)/gs;
    while ((match = numberedPattern.exec(content)) !== null) {
      const num = match[1];
      const title = match[2].trim();
      const description = match[3].trim();
      const id = `rule-${num.padStart(3, "0")}`;
      rules.push({
        id,
        title,
        category: "general",
        priority: this.detectPriority(description),
        description
      });
    }
    return rules;
  }
  /**
   * Extract code examples from markdown
   */
  extractExamples(content) {
    const examples = [];
    const examplePattern = /##?\s*(?:Example|示例|案例)[:\s]*(.+?)(?=\n##?|\n##|$)/gis;
    let match;
    while ((match = examplePattern.exec(content)) !== null) {
      const exampleContent = match[1];
      const inputMatch = exampleContent.match(/(?:Input|输入)[:\s]*(.+?)(?=Output|输出|$)/is);
      const outputMatch = exampleContent.match(/(?:Output|输出)[:\s]*(.+)$/is);
      if (inputMatch || outputMatch) {
        examples.push({
          title: "Example",
          input: inputMatch ? inputMatch[1].trim() : "",
          output: outputMatch ? outputMatch[1].trim() : ""
        });
      }
    }
    return examples;
  }
  /**
   * Extract code blocks from content
   */
  extractCodeBlocks(content) {
    const blocks = [];
    const codePattern = /```(\w+)?\n([\s\S]*?)```/g;
    let match;
    while ((match = codePattern.exec(content)) !== null) {
      blocks.push({
        language: match[1] || "text",
        code: match[2].trim()
      });
    }
    return blocks;
  }
  /**
   * Load reference documents from references/ directory
   */
  loadReferences(dirPath) {
    const references = [];
    const refsPath = join(dirPath, "references");
    if (!existsSync(refsPath)) {
      return references;
    }
    const loadDir = (dir, prefix = "") => {
      const entries = readdirSync(dir, { withFileTypes: true });
      for (const entry of entries) {
        const fullPath = join(dir, entry.name);
        if (entry.isDirectory()) {
          loadDir(fullPath, `${prefix}${entry.name}/`);
        } else if (entry.name.endsWith(".md")) {
          const content = readFileSync(fullPath, "utf-8");
          const title = this.extractTitle(content.split("\n")) || basename(entry.name, ".md");
          references.push({
            path: `${prefix}${entry.name}`,
            title,
            content
          });
        }
      }
    };
    loadDir(refsPath);
    return references;
  }
  /**
   * Detect priority from text
   */
  detectPriority(text) {
    const lowerText = text.toLowerCase();
    for (const [keyword, priority] of Object.entries(PRIORITY_KEYWORDS)) {
      if (lowerText.includes(keyword.toLowerCase())) {
        return priority;
      }
    }
    return "medium";
  }
}
let parserInstance = null;
function getSkillParser() {
  if (!parserInstance) {
    parserInstance = new SkillParser();
  }
  return parserInstance;
}

export { getSkillParser as g };
