/**
 * 模板 Schema 加载器 — 从模板 frontmatter 中解析 artifact_schema 和 process_rules。
 *
 * 职责：
 * 1. 解析模板文件 YAML frontmatter 中的 artifact_schema 字段
 * 2. 解析模板文件 YAML frontmatter 中的 process_rules 字段
 * 3. 提供运行时重载能力（开发时修改模板立即生效）
 *
 * 设计决策：
 * - 模板 frontmatter 中的 schema 定义会覆盖 registry 中的硬编码数据
 * - 无 frontmatter 的模板不报错，使用 registry 默认值
 * - 解析失败时 fallback 到 registry，不阻断流程
 */
import fs from "node:fs";
import path from "node:path";
import { debug } from "../core/logger.js";
// ── 解析函数 ──
/**
 * 解析模板文件的 YAML frontmatter。
 *
 * @returns frontmatter 文本（不含 --- 分隔符），无 frontmatter 时返回 null
 */
export function extractFrontmatter(content) {
    const match = content.match(/^---\n([\s\S]*?)\n---/);
    return match ? match[1] : null;
}
/**
 * 从 YAML frontmatter 中解析 artifact_schema 字段。
 *
 * 使用简单的行解析（不依赖 yaml 库），适用于我们控制的结构化格式。
 */
export function parseArtifactSchemaFromFrontmatter(frontmatter) {
    // 查找 artifact_schema: 块
    const schemaStart = frontmatter.indexOf("artifact_schema:");
    if (schemaStart === -1)
        return null;
    // 提取 artifact_schema 块（到下一个顶层 key 或末尾）
    const afterSchema = frontmatter.slice(schemaStart);
    const lines = afterSchema.split("\n");
    const schemaLines = [];
    let inSchema = false;
    for (const line of lines) {
        // 顶层 key（非缩进）且不是 artifact_schema 本身 → 结束
        if (inSchema && line.length > 0 && line[0] !== " " && line[0] !== "\t" && !line.startsWith("#")) {
            break;
        }
        if (line.startsWith("artifact_schema:")) {
            inSchema = true;
            schemaLines.push(line);
        }
        else if (inSchema) {
            schemaLines.push(line);
        }
    }
    const schemaText = schemaLines.join("\n");
    return parseSchemaBlock(schemaText);
}
/**
 * 解析 artifact_schema 块的内部结构。
 */
function parseSchemaBlock(text) {
    let kind = "";
    const sections = [];
    const tables = [];
    const fields = {};
    const artifacts = [];
    const gaps = [];
    const lines = text.split("\n");
    let currentListTarget = null;
    let currentFieldsTable = null;
    let currentFieldNames = [];
    for (const rawLine of lines) {
        const line = rawLine.trim();
        // kind 字段值
        if (line.startsWith("kind:")) {
            kind = line.replace("kind:", "").trim().replace(/['"]/g, "");
            currentListTarget = null;
            continue;
        }
        // 必填章节
        if (line.startsWith("required_sections:")) {
            currentListTarget = sections;
            currentFieldsTable = null;
            continue;
        }
        // 必填表格
        if (line.startsWith("required_tables:")) {
            currentListTarget = tables;
            currentFieldsTable = null;
            continue;
        }
        // 必填附属产物
        if (line.startsWith("required_artifacts:")) {
            currentListTarget = artifacts;
            currentFieldsTable = null;
            continue;
        }
        // 禁止空白
        if (line.startsWith("forbidden_gaps:")) {
            currentListTarget = gaps;
            currentFieldsTable = null;
            continue;
        }
        // 必填字段块
        if (line.startsWith("required_fields:")) {
            currentListTarget = null;
            currentFieldsTable = null;
            continue;
        }
        // 列表项（- value）
        if (line.startsWith("- ") && currentListTarget !== null) {
            const value = line.slice(2).trim().replace(/['"]/g, "");
            currentListTarget.push(value);
            continue;
        }
        // required_fields 子项：tableName:
        // 缩进的 key → 字段表名
        if (rawLine.match(/^\s{4,6}\S+:\s*$/) && !line.startsWith("-")) {
            // 先保存上一个字段表
            if (currentFieldsTable && currentFieldNames.length > 0) {
                fields[currentFieldsTable] = currentFieldNames;
            }
            currentFieldsTable = line.replace(":", "").trim();
            currentFieldNames = [];
            continue;
        }
        // 字段表的列表项
        if (line.startsWith("- ") && currentFieldsTable !== null) {
            const value = line.slice(2).trim().replace(/['"]/g, "");
            currentFieldNames.push(value);
            continue;
        }
    }
    // 保存最后一个字段表
    if (currentFieldsTable && currentFieldNames.length > 0) {
        fields[currentFieldsTable] = currentFieldNames;
    }
    if (!kind)
        return null;
    const result = { kind };
    if (sections.length > 0)
        result.required_sections = sections;
    if (tables.length > 0)
        result.required_tables = tables;
    if (Object.keys(fields).length > 0)
        result.required_fields = fields;
    if (artifacts.length > 0)
        result.required_artifacts = artifacts;
    if (gaps.length > 0)
        result.forbidden_gaps = gaps;
    return result;
}
/**
 * 从 YAML frontmatter 中解析 process_rules 字段。
 */
export function parseProcessRulesFromFrontmatter(frontmatter) {
    const rulesStart = frontmatter.indexOf("process_rules:");
    if (rulesStart === -1)
        return null;
    const afterRules = frontmatter.slice(rulesStart);
    const lines = afterRules.split("\n");
    const result = {};
    let currentOp = null;
    let currentField = null;
    for (const rawLine of lines) {
        const line = rawLine.trim();
        // 新顶层 key → 结束
        if (line.length > 0 && rawLine.match(/^\S/) && !line.startsWith("process_rules:")) {
            break;
        }
        // 操作类型（extract/review/fix/iterate:）
        const opMatch = line.match(/^(extract|review|fix|iterate):$/);
        if (opMatch) {
            currentOp = opMatch[1];
            result[currentOp] = { instructions: [], constraints: [], input_materials: [] };
            currentField = null;
            continue;
        }
        // 执行指令字段
        if (line === "instructions:" && currentOp) {
            currentField = "instructions";
            continue;
        }
        // 约束字段
        if (line === "constraints:" && currentOp) {
            currentField = "constraints";
            continue;
        }
        // 输入材料字段
        if (line === "input_materials:" && currentOp) {
            currentField = "input_materials";
            continue;
        }
        // 列表项
        if (line.startsWith("- ") && currentOp && currentField) {
            const value = line.slice(2).trim().replace(/^['"]|['"]$/g, "");
            result[currentOp][currentField].push(value);
        }
    }
    return Object.keys(result).length > 0 ? result : null;
}
/**
 * 解析单个模板文件的 schema 和 process_rules。
 */
export function parseTemplateFile(templatePath) {
    if (!fs.existsSync(templatePath))
        return null;
    try {
        const content = fs.readFileSync(templatePath, "utf-8");
        const frontmatter = extractFrontmatter(content);
        const fileName = path.basename(templatePath);
        // 从现有 frontmatter 提取 kind
        const kindMatch = frontmatter?.match(/name:\s*(\S+)/);
        if (!kindMatch)
            return null;
        const kindName = kindMatch[1];
        // 尝试映射到 ArtifactKind（需要从模板 id 或 name 推断）
        const mappedKind = mapTemplateNameToKind(kindName, fileName);
        if (!mappedKind)
            return null;
        let artifactSchema = null;
        let processRules = null;
        if (frontmatter) {
            artifactSchema = parseArtifactSchemaFromFrontmatter(frontmatter);
            processRules = parseProcessRulesFromFrontmatter(frontmatter);
        }
        return {
            template_file: fileName,
            kind: mappedKind,
            artifact_schema: artifactSchema,
            process_rules: processRules,
        };
    }
    catch (e) {
        debug(`template_schema_loader: 解析模板失败 ${templatePath}: ${e}`);
        return null;
    }
}
/**
 * 批量加载目录下所有模板的 schema。
 */
export function loadTemplateSchemas(templatesDir) {
    if (!fs.existsSync(templatesDir))
        return [];
    const results = [];
    const entries = fs.readdirSync(templatesDir);
    for (const entry of entries) {
        if (!entry.endsWith(".md"))
            continue;
        const fullPath = path.join(templatesDir, entry);
        const parsed = parseTemplateFile(fullPath);
        if (parsed)
            results.push(parsed);
    }
    debug(`template_schema_loader: 从 ${templatesDir} 加载 ${results.length} 个模板 schema`);
    return results;
}
/**
 * 将 ArtifactSchema 转换为可注册到 registry 的格式。
 */
export function toArtifactSchema(parsed) {
    if (!parsed.artifact_schema)
        return null;
    const schema = parsed.artifact_schema;
    return {
        kind: parsed.kind,
        required_sections: schema.required_sections ?? [],
        required_tables: schema.required_tables ?? [],
        required_fields: schema.required_fields,
        required_artifacts: schema.required_artifacts,
        forbidden_gaps: schema.forbidden_gaps,
        template_file: parsed.template_file,
    };
}
// ── 模板名 → ArtifactKind 映射 ──
const TEMPLATE_NAME_MAP = {
    "原型说明模版.md": "prototype_spec",
    "架构设计模版.md": "design_doc",
    "API接口规格文档模版.md": "api_spec",
    "设计一致性验收报告模版.md": "verification_report",
    "详细设计模版.md": "detailed_design",
    "接口对接方案模版.md": "api_design",
    "需求分析模版.md": "requirement_analysis",
    "测试计划模版.md": "test_plan",
    "切片计划模版.md": "task_breakdown",
    "Bug分析模版.md": "root_cause",
    "故障复盘模版.md": "incident_review",
    "代码审查报告模版.md": "review_report",
    "ADR模版.md": "tech_decision_record",
    "迁移评估模版.md": "migration_plan",
    "通用质量验收清单.md": "acceptance_checklist",
    "OOD设计摘要模版.md": "domain_model",
};
function mapTemplateNameToKind(_templateName, fileName) {
    // 先用文件名精确匹配
    if (fileName in TEMPLATE_NAME_MAP)
        return TEMPLATE_NAME_MAP[fileName];
    // 再用 name 字段模糊匹配
    return undefined;
}
//# sourceMappingURL=template_schema_loader.js.map