/**
 * Knowledge Sovereignty — 知识主权: drafts/quarantine/core 三级生命周期。
 * R10 advisory: 不 hard block，只产出 advisory 报告。
 *
 * 职责:
 * - quarantineGate: 检查知识条目是否在 quarantine 期
 * - promoteToQuarantine: 从 drafts 晋升到 quarantine（自动）
 * - promoteToCore: 从 quarantine 晋级到 core（需人工确认）
 * - 查询 quarantine 状态
 */
import fs from "node:fs/promises";
import fss from "node:fs";
import path from "node:path";
import matter from "gray-matter";
import { debug } from "../core/logger.js";
/** 默认隔离天数 */
export const DEFAULT_QUARANTINE_DAYS = 7;
/**
 * 检查条目是否在 quarantine 期 — advisory only, 不 hard block。
 * quarantine 期间条目可被引用，但标记为 advisory。
 */
export function quarantineGate(entry) {
    if (entry.tier === "core") {
        return { allowed: true, advisory: "core tier, unrestricted" };
    }
    if (entry.tier === "draft") {
        return {
            allowed: true,
            advisory: "advisory: draft tier, not yet quarantined — reference with caution",
        };
    }
    if (entry.tier === "quarantine") {
        if (!entry.quarantine_expires_at) {
            return { allowed: false, advisory: "quarantine 条目不允许注入（无过期时间），需先提升到 active" };
        }
        const now = Date.now();
        const expires = new Date(entry.quarantine_expires_at).getTime();
        if (now < expires) {
            const daysLeft = Math.ceil((expires - now) / (24 * 60 * 60 * 1000));
            return {
                allowed: false,
                advisory: `quarantine 条目不允许注入（剩余 ${daysLeft} 天隔离期），需先提升到 active`,
            };
        }
        return {
            allowed: false,
            advisory: "quarantine 已过期，需人工审查后放行",
        };
    }
    return { allowed: true, advisory: "unknown tier" };
}
/**
 * 将 drafts 中的条目晋升到 quarantine — 自动，不需要人工确认。
 */
export async function promoteToQuarantine(draftPath, knowledgeDir, quarantineDays = DEFAULT_QUARANTINE_DAYS) {
    if (!fss.existsSync(draftPath))
        return null;
    debug("知识主权", "晋升草稿到 quarantine", draftPath, "隔离期:", quarantineDays, "天");
    const raw = await fs.readFile(draftPath, "utf-8");
    const { data: frontmatter, content: body } = matter(raw);
    const quarantineDir = path.join(knowledgeDir, "quarantine");
    fss.mkdirSync(quarantineDir, { recursive: true });
    const now = new Date();
    const expires = new Date(now.getTime() + quarantineDays * 24 * 60 * 60 * 1000);
    frontmatter.tier = "quarantine";
    frontmatter.quarantined_at = now.toISOString();
    frontmatter.quarantine_expires_at = expires.toISOString();
    const filename = path.basename(draftPath);
    const targetPath = path.join(quarantineDir, filename);
    const updated = matter.stringify(body, frontmatter);
    const tmpPath = `${targetPath}.tmp`;
    await fs.writeFile(tmpPath, updated, "utf-8");
    await fs.rename(tmpPath, targetPath);
    await fs.unlink(draftPath).catch((e) => { debug("知识主权", "清理文件失败", e); });
    return {
        name: frontmatter.name ?? filename,
        file_path: targetPath,
        tier: "quarantine",
        quarantined_at: now.toISOString(),
        quarantine_expires_at: expires.toISOString(),
        can_reference: true,
        advisory: "newly quarantined, reference with caution",
    };
}
/**
 * 将 quarantine 中的条目晋级到 core — 需要人工确认。
 * confirm=false 时只返回预览，不执行晋级。
 */
export async function promoteToCore(quarantinePath, knowledgeDir, confirm) {
    if (!fss.existsSync(quarantinePath)) {
        return {
            success: false,
            target_path: "",
            advisory: `file not found: ${quarantinePath}`,
        };
    }
    if (!confirm.confirmed || !confirm.confirmed_by) {
        return {
            success: false,
            target_path: quarantinePath,
            advisory: "core promotion requires human confirmation (confirmed=true, confirmed_by non-empty)",
        };
    }
    const raw = await fs.readFile(quarantinePath, "utf-8");
    const { data: frontmatter, content: body } = matter(raw);
    // 检查 quarantine 期是否已过期
    if (frontmatter.quarantine_expires_at) {
        const now = Date.now();
        const expires = new Date(frontmatter.quarantine_expires_at).getTime();
        if (now < expires) {
            return {
                success: false,
                target_path: quarantinePath,
                advisory: "quarantine period not yet expired, cannot promote to core",
            };
        }
    }
    const coreDir = path.join(knowledgeDir, "patterns", "core");
    fss.mkdirSync(coreDir, { recursive: true });
    frontmatter.tier = "core";
    debug("知识主权", "晋级 quarantine 到 core", quarantinePath, "确认人:", confirm.confirmed_by);
    frontmatter.promoted_at = new Date().toISOString();
    frontmatter.promoted_by = confirm.confirmed_by;
    frontmatter.promotion_reason = confirm.reason;
    delete frontmatter.quarantine_expires_at;
    delete frontmatter.quarantined_at;
    const filename = path.basename(quarantinePath);
    const targetPath = path.join(coreDir, filename);
    const updated = matter.stringify(body, frontmatter);
    const tmpPath = `${targetPath}.tmp`;
    await fs.writeFile(tmpPath, updated, "utf-8");
    await fs.rename(tmpPath, targetPath);
    await fs.unlink(quarantinePath).catch((e) => { debug("知识主权", "清理文件失败", e); });
    return {
        success: true,
        target_path: targetPath,
        advisory: `promoted to core by ${confirm.confirmed_by}: ${confirm.reason}`,
    };
}
/**
 * 扫描 knowledge 目录，生成主权报告。
 */
export async function generateSovereigntyReport(knowledgeDir) {
    const entries = [];
    const tiers = ["draft", "quarantine", "core"];
    const tierDirs = {
        draft: path.join(knowledgeDir, "drafts"),
        quarantine: path.join(knowledgeDir, "quarantine"),
        core: path.join(knowledgeDir, "patterns", "core"),
    };
    const tierCounts = { draft: 0, quarantine: 0, core: 0 };
    debug("知识主权", "扫描知识目录", knowledgeDir);
    const canPromoteToCore = [];
    for (const tier of tiers) {
        const dir = tierDirs[tier];
        if (!fss.existsSync(dir))
            continue;
        const files = await fs.readdir(dir);
        for (const f of files.filter((f) => f.endsWith(".md"))) {
            const filePath = path.join(dir, f);
            try {
                const raw = await fs.readFile(filePath, "utf-8");
                const { data } = matter(raw);
                const entry = {
                    name: data.name ?? f,
                    file_path: filePath,
                    tier,
                    quarantined_at: data.quarantined_at ?? null,
                    quarantine_expires_at: data.quarantine_expires_at ?? null,
                    can_reference: true,
                    advisory: "",
                };
                tierCounts[tier]++;
                if (tier === "quarantine" && data.quarantine_expires_at) {
                    const expires = new Date(data.quarantine_expires_at).getTime();
                    if (Date.now() >= expires) {
                        canPromoteToCore.push({ name: entry.name, file_path: filePath });
                    }
                }
                entries.push(entry);
            }
            catch (e) {
                debug("知识主权", "知识条目解析失败 —", e);
                // 跳过无法解析的文件
            }
        }
    }
    return {
        total_entries: entries.length,
        by_tier: tierCounts,
        quarantine_entries: entries.filter((e) => e.tier === "quarantine"),
        can_promote_to_core: canPromoteToCore,
        summary: `${entries.length} entries (${tierCounts.draft} drafts, ${tierCounts.quarantine} quarantine, ${tierCounts.core} core)`,
    };
}
//# sourceMappingURL=knowledge_sovereignty.js.map