import { debug } from "./core/logger.js";
const INDUSTRY_BENCHMARKS = [
    {
        keywords: ["分布式锁", "锁", "并发控制", "distributed lock", "互斥"],
        domain: "分布式锁",
        solutions: [
            {
                name: "Redis SETNX + 过期",
                description: "基于 Redis 单节点的分布式锁实现，SET key NX EX timeout",
                ratings: { dev_cost: 4, performance: 5, scalability: 3, maintainability: 4 },
                fatal_weakness: "Redis 主从切换时锁可能丢失，非严格互斥",
                best_for: "低争用场景，容忍极短暂时竞态（如幂等操作）",
                worst_for: "金融级严格互斥、强一致性要求的场景",
            },
            {
                name: "Redisson 看门狗",
                description: "Redisson 框架提供的可重入锁 + 自动续期看门狗",
                ratings: { dev_cost: 5, performance: 4, scalability: 3, maintainability: 3 },
                fatal_weakness: "依赖单 Redis 节点，主从切换仍有丢失风险",
                best_for: "Java 项目中快速集成，需要可重入和自动续期",
                worst_for: "跨数据中心、Redis 集群模式下的严格互斥",
            },
            {
                name: "ZooKeeper 临时节点",
                description: "基于 ZooKeeper 临时顺序节点实现的分布式锁",
                ratings: { dev_cost: 2, performance: 2, scalability: 5, maintainability: 2 },
                fatal_weakness: "性能差（每次加锁需多次网络通信），运维复杂度高",
                best_for: "强一致性要求、已有 ZK 基础设施",
                worst_for: "高频加锁场景（TPS > 1000）",
            },
        ],
    },
    {
        keywords: ["流式处理", "流处理", "stream", "实时计算", "消息流", "事件流"],
        domain: "流式处理",
        solutions: [
            {
                name: "Spring WebFlux / Reactor",
                description: "基于 Reactor 的响应式流处理，JVM 内置背压支持",
                ratings: { dev_cost: 3, performance: 4, scalability: 4, maintainability: 3 },
                fatal_weakness: "调试困难，错误栈难以追踪，团队学习曲线陡峭",
                best_for: "高并发 I/O 密集型微服务，已有 Spring 生态",
                worst_for: "CPU 密集型计算、团队无响应式编程经验",
            },
            {
                name: "Kafka Streams",
                description: "Apache Kafka 内置的流处理库，Exactly-Once 语义",
                ratings: { dev_cost: 3, performance: 5, scalability: 5, maintainability: 3 },
                fatal_weakness: "强依赖 Kafka 生态，状态存储需 Kafka 内部 topic",
                best_for: "大规模事件驱动架构，需要 Exactly-Once 语义",
                worst_for: "小规模项目、非 Kafka 消息队列",
            },
            {
                name: "分页查询 + 轮询",
                description: "传统 RDBMS 分页查询 + 定时轮询，简单直接",
                ratings: { dev_cost: 5, performance: 1, scalability: 1, maintainability: 5 },
                fatal_weakness: "实时性差（延迟 = 轮询间隔），大数据量下性能崩溃",
                best_for: "低频数据同步（分钟级可接受），极小规模",
                worst_for: "实时监控、秒级告警、大数据量流处理",
            },
        ],
    },
    {
        keywords: ["表单", "复杂表单", "表单状态", "动态表单", "form", "表单验证"],
        domain: "复杂表单状态管理",
        solutions: [
            {
                name: "React Hook Form",
                description: "非受控表单库，基于 ref 的轻量级表单管理",
                ratings: { dev_cost: 5, performance: 5, scalability: 3, maintainability: 4 },
                fatal_weakness: "深度嵌套动态表单场景下性能退化，自定义校验逻辑分散",
                best_for: "标准 CRUD 表单，中低复杂度，追求性能",
                worst_for: "高度动态表单（字段联动、条件显隐、跨表单依赖）",
            },
            {
                name: "Formily (Alibaba)",
                description: "阿里巴巴出品的 JSON Schema 驱动表单方案",
                ratings: { dev_cost: 2, performance: 4, scalability: 5, maintainability: 2 },
                fatal_weakness: "学习曲线陡峭，概念密度高（JSON Schema + Path 系统 + 响应式）",
                best_for: "企业级低代码平台、高度动态的复杂表单",
                worst_for: "快速迭代的中小项目、团队无 Formily 经验",
            },
            {
                name: "Zustand + 手动状态机",
                description: "Zustand 做全局状态 + 手写状态机管理表单联动",
                ratings: { dev_cost: 3, performance: 4, scalability: 4, maintainability: 3 },
                fatal_weakness: "无内置表单校验和异步校验，需自行封装",
                best_for: "需要完全控制表单行为、团队有状态机经验",
                worst_for: "标准表单场景（杀鸡用牛刀）、快速原型",
            },
        ],
    },
    {
        keywords: ["缓存", "cache", "本地缓存", "分布式缓存", "缓存策略", "缓存穿透"],
        domain: "缓存策略",
        solutions: [
            {
                name: "Spring Cache + Redis",
                description: "Spring Cache 抽象 + Redis 作为分布式缓存",
                ratings: { dev_cost: 5, performance: 4, scalability: 4, maintainability: 4 },
                fatal_weakness: "默认无本地缓存层，每次请求都走网络，缓存雪崩无防护",
                best_for: "标准 CRUD 读取缓存，Spring Boot 项目",
                worst_for: "超高 QPS（>10 万）、需要多级缓存的场景",
            },
            {
                name: "Caffeine + Redis 二级缓存",
                description: "L1 本地缓存 (Caffeine) + L2 分布式缓存 (Redis)",
                ratings: { dev_cost: 3, performance: 5, scalability: 4, maintainability: 3 },
                fatal_weakness: "L1/L2 一致性维护复杂，需处理缓存失效广播",
                best_for: "超高 QPS 读场景（>5 万），数据变化频率低",
                worst_for: "数据频繁变更、一致性要求严格的场景",
            },
            {
                name: "手动缓存 + TTL + 布隆过滤器",
                description: "手动管理缓存键/值/TTL，布隆过滤器防穿透",
                ratings: { dev_cost: 2, performance: 4, scalability: 3, maintainability: 2 },
                fatal_weakness: "大量样板代码，缓存键管理容易出 bug，无统一失效策略",
                best_for: "特殊缓存需求（复杂过期策略、多键联动）",
                worst_for: "团队规模小、缓存键种类多、追求可维护性",
            },
        ],
    },
    {
        keywords: ["定时任务", "调度", "scheduled", "cron", "分布式调度", "任务调度"],
        domain: "分布式任务调度",
        solutions: [
            {
                name: "Spring @Scheduled",
                description: "Spring 内置的 @Scheduled 注解，单机调度",
                ratings: { dev_cost: 5, performance: 3, scalability: 1, maintainability: 5 },
                fatal_weakness: "单机执行，多实例会重复执行，无分片能力",
                best_for: "单实例部署、低频简单任务（如每天统计）",
                worst_for: "多实例部署、需要分片/失败重试/依赖任务链",
            },
            {
                name: "XXL-Job",
                description: "大众点评开源的分布式任务调度平台",
                ratings: { dev_cost: 3, performance: 4, scalability: 5, maintainability: 4 },
                fatal_weakness: "需要独立部署调度中心，增加运维负担",
                best_for: "中大规模项目，需要可视化管理、分片、失败重试",
                worst_for: "极小项目、不想额外部署服务",
            },
            {
                name: "Quartz 集群",
                description: "Quartz 调度器 + 数据库锁实现集群调度",
                ratings: { dev_cost: 3, performance: 3, scalability: 3, maintainability: 3 },
                fatal_weakness: "数据库行锁争用，高并发调度性能差，无分片能力",
                best_for: "已有 Quartz 经验、中小规模集群",
                worst_for: "大规模分片任务（>100 分片）",
            },
        ],
    },
    {
        keywords: ["文件存储", "对象存储", "文件上传", "oss", "s3", "minio", "文件管理"],
        domain: "文件存储",
        solutions: [
            {
                name: "MinIO / S3 对象存储",
                description: "S3 兼容的对象存储服务，统一管理文件",
                ratings: { dev_cost: 4, performance: 5, scalability: 5, maintainability: 4 },
                fatal_weakness: "大文件上传需要分片逻辑，跨区域同步需额外方案",
                best_for: "标准文件上传/下载，需要可扩展存储",
                worst_for: "需要文件实时协作编辑、文件系统语义",
            },
            {
                name: "本地文件系统 + Nginx",
                description: "本地磁盘存储 + Nginx 静态文件服务",
                ratings: { dev_cost: 5, performance: 4, scalability: 1, maintainability: 3 },
                fatal_weakness: "无法水平扩展，磁盘满即服务不可用",
                best_for: "单机部署、小规模文件存储",
                worst_for: "多实例部署、大文件量、需要高可用",
            },
            {
                name: "数据库 BLOB 存储",
                description: "将文件内容直接存入数据库 BLOB 字段",
                ratings: { dev_cost: 5, performance: 1, scalability: 1, maintainability: 2 },
                fatal_weakness: "数据库膨胀、备份恢复慢、无法 CDN 加速",
                best_for: "极小文件（<100KB）且需要事务一致性",
                worst_for: "任何超过 1MB 的文件、高频读写场景",
            },
        ],
    },
    {
        keywords: ["认证", "鉴权", "登录", "权限", "auth", "JWT", "OAuth", "SSO"],
        domain: "认证鉴权",
        solutions: [
            {
                name: "Spring Security + JWT",
                description: "Spring Security 框架 + 无状态 JWT Token",
                ratings: { dev_cost: 3, performance: 5, scalability: 5, maintainability: 3 },
                fatal_weakness: "JWT 无法主动失效（除非引入黑名单），Token 泄露窗口期风险",
                best_for: "无状态微服务、前后端分离、不需要即时踢人",
                worst_for: "需要即时会话管理、Token 细粒度控制",
            },
            {
                name: "Spring Security + Redis Session",
                description: "Spring Security + Redis 集中式 Session 管理",
                ratings: { dev_cost: 3, performance: 3, scalability: 3, maintainability: 4 },
                fatal_weakness: "每次请求都查 Redis，Redis 故障 = 全局无法登录",
                best_for: "需要即时会话管理、踢人、并发登录控制",
                worst_for: "超高 QPS（Redis 成为瓶颈）、纯无状态架构",
            },
            {
                name: "OAuth 2.0 + OIDC (Keycloak)",
                description: "标准 OAuth 2.0 / OIDC 协议 + Keycloak 作为 IdP",
                ratings: { dev_cost: 2, performance: 3, scalability: 4, maintainability: 3 },
                fatal_weakness: "Keycloak 学习曲线陡峭，定制化困难，部署复杂",
                best_for: "多系统 SSO、第三方登录、企业级 IAM",
                worst_for: "单系统简单登录、快速上线需求",
            },
        ],
    },
];
// ── 核心逻辑 ──
/**
 * 执行自主技术选型与方案证伪。
 * @param params - 输入参数
 * @returns 探索结果，包含行业基准、对比矩阵、推荐方案、证伪报告和 A/B 决策
 */
export function exploreSolutions(params) {
    debug("探索模块", `开始探索领域「${params.domain_query}」`);
    const { domain_query, projectConfig, knowledgeIndex } = params;
    // 1. 检索行业基准 + 知识库匹配
    const benchmarks = retrieveBenchmarks(domain_query, knowledgeIndex);
    debug("探索模块", `检索到 ${benchmarks.length} 个候选方案`);
    if (benchmarks.length === 0) {
        throw new Error(`探索模块: 未找到「${domain_query}」领域的候选方案，至少需要 1 个基准`);
    }
    // 2. 构建对比矩阵
    const matrix = buildComparisonMatrix(benchmarks);
    // 3. 最优解宣誓
    const recommendation = declareArchitectRecommendation(benchmarks, projectConfig);
    debug("探索模块", `架构师推荐方案「${recommendation.recommended}」`);
    // 4. 证伪循环
    const falsifications = benchmarks.map((b) => performFalsification(b));
    // 5. A/B 决策诱导
    const decisionOptions = generateDecisionOptions(benchmarks, recommendation);
    // 6. 方案边界声明汇总
    const boundarySummary = falsifications
        .map((f) => `【${f.solution_name}】${f.boundary_declaration}`)
        .join("\n");
    // 时效性标注
    const timeliness = computeTimeliness(benchmarks);
    if (timeliness.stale_warning) {
        debug("探索模块", `${timeliness.message}`);
    }
    // 环境感知提示
    const envHints = computeEnvironmentHints(projectConfig, benchmarks);
    // 契约字段: local_constraints
    const localConstraints = buildLocalConstraints(projectConfig);
    // 契约字段: evidence_sources
    const evidenceSources = buildEvidenceSources(benchmarks, knowledgeIndex);
    // 契约字段: rejected_options
    const rejectedOptions = buildRejectedOptions(benchmarks, recommendation);
    // 契约字段: freshness_risk
    const freshnessRisk = buildFreshnessRisk(timeliness, benchmarks);
    // 契约字段: adoption_risk
    const adoptionRisk = buildAdoptionRisk(recommendation, benchmarks);
    // 契约字段: validation_plan
    const validationPlan = buildValidationPlan(recommendation, benchmarks);
    // 契约字段: decision_expiry
    const decisionExpiry = buildDecisionExpiry(timeliness);
    // 默认决策输出契约
    const recommendedSolution = benchmarks.find((b) => b.name === recommendation.recommended) ?? benchmarks[0];
    const recommendedFalsification = falsifications.find((f) => f.solution_name === recommendation.recommended);
    debug("探索模块", `探索完成，推荐「${recommendation.recommended}」`);
    return {
        domain: benchmarks[0]?.name || domain_query,
        benchmarks,
        comparison_matrix: matrix,
        architect_recommendation: recommendation,
        falsification_report: falsifications,
        decision_options: decisionOptions,
        boundary_summary: boundarySummary + (envHints ? "\n" + envHints : ""),
        timeliness,
        local_constraints: localConstraints,
        evidence_sources: evidenceSources,
        rejected_options: rejectedOptions,
        freshness_risk: freshnessRisk,
        adoption_risk: adoptionRisk,
        validation_plan: validationPlan,
        decision_expiry: decisionExpiry,
        // 默认决策契约 10 字段
        recommended_option: recommendation.recommended,
        why_this: recommendation.reason + "；规避了: " + recommendation.fatal_weakness_mitigation,
        rejected_decision_options: rejectedOptions.map((r) => `${r.name}: ${r.reason}`),
        steelman_alternatives: rejectedOptions.map((r) => r.steelman).join("；"),
        attack_recommended_option: recommendedFalsification?.self_destruct_scenarios.join("；") ?? "无已知自毁场景",
        falsification_tests: recommendedFalsification?.ceiling_description ?? "未设置天花板测试",
        execution_plan: decisionOptions[0].reason + "；" + decisionOptions[0].suitable_for,
        verification_plan: validationPlan,
        rollback_plan: `移除「${recommendedSolution.name}」相关代码和配置即可恢复原状`,
        human_confirmation_required: recommendedSolution.source === "heuristic",
    };
}
// ── 行业基准检索 ──
/**
 * 检索行业基准方案。优先匹配内置行业库，辅以知识库查询。
 * 禁止凭空捏造 — 必须返回至少 1 个有据可查的标准方案。
 * @param domainQuery - 领域查询关键词
 * @param knowledgeIndex - 可选的知识索引管理器
 * @returns 候选方案列表
 */
function retrieveBenchmarks(domainQuery, knowledgeIndex) {
    const solutions = [];
    // 1. 匹配内置行业基准库
    const queryLower = domainQuery.toLowerCase();
    for (const benchmark of INDUSTRY_BENCHMARKS) {
        const matched = benchmark.keywords.some((kw) => queryLower.includes(kw.toLowerCase()) || kw.toLowerCase().includes(queryLower));
        if (matched) {
            for (const sol of benchmark.solutions) {
                solutions.push({ ...sol, source: "industry" });
            }
            break; // 匹配到第一个领域就停止
        }
    }
    // 2. 补充知识库匹配
    if (knowledgeIndex && solutions.length === 0) {
        const entries = knowledgeIndex.query({
            keywords: domainQuery.split(/[\s,，、]+/).filter((w) => w.length >= 2),
            limit: 3,
        });
        for (const entry of entries) {
            if (entry.body) {
                solutions.push({
                    name: entry.name,
                    source: "knowledge",
                    description: entry.when,
                    ratings: { dev_cost: 3, performance: 3, scalability: 3, maintainability: 3 },
                    fatal_weakness: "从知识库匹配，需人工确认致命缺点",
                    best_for: entry.scope.join(", "),
                    worst_for: "超出知识库记录范围",
                });
            }
        }
    }
    // 3. 兜底: 启发式通用方案框架
    if (solutions.length === 0) {
        solutions.push({
            name: "轻量级方案（最小实现）",
            source: "heuristic",
            description: "最小可行实现，优先开发速度",
            ratings: { dev_cost: 5, performance: 2, scalability: 2, maintainability: 3 },
            fatal_weakness: "扩展性差，数据量/用户量增长后需重构",
            best_for: "MVP 阶段、快速验证",
            worst_for: "生产环境高负载场景",
        }, {
            name: "行业标准方案（推荐调研方向）",
            source: "heuristic",
            description: "该领域的标准解决方案，需进一步调研具体技术选型",
            ratings: { dev_cost: 3, performance: 4, scalability: 4, maintainability: 4 },
            fatal_weakness: "需要领域知识确认具体方案，当前为通用模板",
            best_for: "大多数标准场景",
            worst_for: "极端特殊需求",
        }, {
            name: "重量级方案（企业级）",
            source: "heuristic",
            description: "企业级全功能方案，含完整监控、容错、扩展能力",
            ratings: { dev_cost: 1, performance: 5, scalability: 5, maintainability: 2 },
            fatal_weakness: "开发周期长，初期投入大，过度工程风险",
            best_for: "明确的高并发/高可用需求",
            worst_for: "时间紧迫、需求不确定",
        });
        debug("探索模块", "未匹配到行业基准，使用启发式兜底方案");
    }
    return solutions;
}
// ── 对比矩阵 ──
const DIMENSIONS = ["开发成本", "运行性能", "扩展上限", "维护性"];
const RATING_KEYS = ["dev_cost", "performance", "scalability", "maintainability"];
/**
 * 构建选型权重对比矩阵。
 * @param solutions - 候选方案列表
 * @returns 对比矩阵，包含维度、各方案得分和总分
 */
function buildComparisonMatrix(solutions) {
    return {
        dimensions: DIMENSIONS,
        rows: solutions.map((sol) => ({
            solution_name: sol.name,
            scores: RATING_KEYS.map((key) => sol.ratings[key]),
            total: RATING_KEYS.reduce((sum, key) => sum + sol.ratings[key], 0),
        })),
    };
}
// ── 最优解宣誓 ──
/**
 * 基于项目上下文和方案评分，生成架构师推荐。
 * @param solutions - 候选方案列表
 * @param config - 项目配置
 * @returns 架构师推荐结果
 */
function declareArchitectRecommendation(solutions, config) {
    if (solutions.length === 0) {
        throw new Error("declareArchitectRecommendation: 至少需要 1 个候选方案");
    }
    // 按总分排序
    const sorted = [...solutions].sort((a, b) => RATING_KEYS.reduce((s, k) => s + b.ratings[k], 0) -
        RATING_KEYS.reduce((s, k) => s + a.ratings[k], 0));
    const recommended = sorted[0];
    const others = sorted.slice(1);
    // 基于项目上下文调整推荐理由
    const techContext = `${config.tech_stack.backend.framework} ${config.tech_stack.backend.version} + ${config.tech_stack.frontend.framework} ${config.tech_stack.frontend.version}`;
    const mitigation = others
        .map((o) => `规避了「${o.name}」的致命缺点: ${o.fatal_weakness}`)
        .join("；");
    return {
        recommended: recommended.name,
        reason: `基于 ${techContext} 技术栈，综合评分最高（${RATING_KEYS.reduce((s, k) => s + recommended.ratings[k], 0)}/20）`,
        fatal_weakness_mitigation: mitigation,
        prerequisites: [
            `团队已具备 ${recommended.name.split(/[/(]/)[0].trim()} 的基本使用能力`,
            `项目部署环境满足 ${recommended.best_for.split("、")[0]} 的基础设施要求`,
        ],
    };
}
// ── 方案证伪 ──
/**
 * 对单个方案执行证伪分析，生成自毁场景和边界声明。
 * @param solution - 待证伪的技术方案
 * @returns 证伪结果
 */
function performFalsification(solution) {
    // 根据方案特性筛选相关的自毁场景
    const scenarios = [];
    // 基于评分推断脆弱点
    if (solution.ratings.scalability <= 2) {
        scenarios.push(`数据量级激增: ${solution.name} 在数据量从 GB 跃迁到 TB 级时性能断崖式下降（扩展性评分: ${solution.ratings.scalability}/5）`);
        scenarios.push(`高并发热点: 并发量超过设计上限时，${solution.name} 成为系统瓶颈`);
    }
    if (solution.ratings.performance <= 2) {
        scenarios.push(`响应延迟: ${solution.name} 在高频调用场景下延迟不可接受（性能评分: ${solution.ratings.performance}/5）`);
    }
    if (solution.ratings.maintainability <= 2) {
        scenarios.push(`运维灾难: ${solution.name} 故障排查时间 > 2 小时，SRE 团队难以维护（维护性评分: ${solution.ratings.maintainability}/5）`);
    }
    // 基于致命缺点推导额外场景
    if (/Redis|缓存/.test(solution.fatal_weakness)) {
        scenarios.push("依赖服务宕机: Redis 故障时缓存全部失效，数据库被流量打穿");
    }
    if (/单机|单实例|单点/.test(solution.fatal_weakness)) {
        scenarios.push("多活部署: 多实例部署时功能冲突或重复执行");
    }
    if (/数据库|DB|BLOB/.test(solution.fatal_weakness)) {
        scenarios.push("存储膨胀: 文件/数据持续增长导致数据库备份恢复超时");
    }
    // 兜底: 至少保证 1 个场景
    if (scenarios.length === 0) {
        scenarios.push(`极端负载: 在 10 倍于设计容量的负载下，${solution.name} 的行为未经验证`);
    }
    const ceiling = solution.worst_for;
    return {
        solution_name: solution.name,
        self_destruct_scenarios: scenarios,
        boundary_declaration: `【${solution.name}】天花板: ${ceiling}。超出此范围必须切换方案。`,
        ceiling_description: ceiling,
    };
}
// ── A/B 决策诱导 ──
/**
 * 基于推荐方案和候选方案生成 A/B 决策选项。
 * 方案 A 为架构师推荐（平衡性最优），方案 B 为有差异化优势的备选。
 * @param solutions - 候选方案列表
 * @param recommendation - 架构师推荐结果
 * @returns 两个决策选项
 */
function generateDecisionOptions(solutions, recommendation) {
    if (solutions.length === 0) {
        throw new Error("generateDecisionOptions: 至少需要 1 个候选方案");
    }
    // 方案 A: 架构师推荐（平衡性最优）
    const recommended = solutions.find((s) => s.name === recommendation.recommended) || solutions[0];
    // 方案 B: 另选一个有差异化优势的方案
    const alternative = solutions.find((s) => s.name !== recommended.name &&
        s.ratings.performance > recommended.ratings.performance) || solutions.find((s) => s.name !== recommended.name) || solutions[0];
    return [
        {
            label: "方案 A（最优选型）",
            solution_name: recommended.name,
            reason: `平衡性最好，综合评分 ${RATING_KEYS.reduce((s, k) => s + recommended.ratings[k], 0)}/20`,
            suitable_for: recommended.best_for,
        },
        {
            label: "方案 B（极致性能）",
            solution_name: alternative.name,
            reason: `性能评分 ${alternative.ratings.performance}/5，适合未来高负载演进`,
            suitable_for: alternative.best_for,
        },
    ];
}
// ── 时效性检查 ──
/** 基准数据最后审核日期 */
const BENCHMARK_REVIEW_DATE = "2025-05-17";
/**
 * 计算基准数据的时效性信息。
 * @param benchmarks - 候选方案列表
 * @returns 时效性信息
 */
function computeTimeliness(benchmarks) {
    const reviewDate = new Date(BENCHMARK_REVIEW_DATE);
    const now = new Date();
    const daysSince = Math.floor((now.getTime() - reviewDate.getTime()) / (1000 * 60 * 60 * 24));
    const stale = daysSince > 180;
    const industryCount = benchmarks.filter((b) => b.source === "industry").length;
    let message;
    if (stale) {
        message = `⚠ 基准数据已 ${daysSince} 天未更新（上次审核: ${BENCHMARK_REVIEW_DATE}）。行业方案可能已有新版本或替代品，建议人工复核`;
    }
    else if (daysSince > 90) {
        message = `基准数据审核于 ${daysSince} 天前。方案仍然有效，但建议关注相关技术的新版本发布`;
    }
    else {
        message = `基准数据较新（${daysSince} 天前审核），${industryCount} 个行业标准方案可用`;
    }
    return {
        last_reviewed: BENCHMARK_REVIEW_DATE,
        days_since_review: daysSince,
        stale_warning: stale,
        message,
    };
}
// ── 环境感知 ──
/**
 * 基于项目技术栈和方案特性，生成环境兼容性提示。
 * @param config - 项目配置
 * @param benchmarks - 候选方案列表
 * @returns 环境提示文本，无兼容性问题时返回 null
 */
function computeEnvironmentHints(config, benchmarks) {
    const hints = [];
    const backend = config.tech_stack.backend;
    const frontend = config.tech_stack.frontend;
    // 检查方案是否与当前技术栈兼容
    for (const sol of benchmarks) {
        if (sol.source !== "industry")
            continue;
        // Java 后端相关提示
        if (/Spring|Java|JVM/.test(sol.description) && backend.lang !== "java") {
            hints.push(`「${sol.name}」需要 Java/JVM 环境，当前后端为 ${backend.lang || backend.framework}，需评估兼容性`);
        }
        // React 前端相关提示
        if (/React|Next\.?js|Zustand|Formily/.test(sol.description) && frontend.framework !== "react") {
            hints.push(`「${sol.name}」依赖 React 生态，当前前端为 ${frontend.framework}，需评估适配成本`);
        }
        // Redis 依赖提示
        if (/Redis|redis/i.test(sol.description) && !hints.some((h) => h.includes("Redis"))) {
            hints.push(`「${sol.name}」依赖 Redis，请确认部署环境已包含 Redis 服务`);
        }
    }
    if (hints.length > 0) {
        const lines = hints.map((h) => "- " + h).join("\n");
        return "\n## 环境感知提示\n" + lines;
    }
    return null;
}
// ── 契约字段构建 ──
/**
 * 构建本地约束描述。
 * @param config - 项目配置
 * @returns 约束描述文本
 */
function buildLocalConstraints(config) {
    const b = config.tech_stack.backend;
    const f = config.tech_stack.frontend;
    const parts = [];
    if (b.framework && b.framework !== "unknown") {
        parts.push(`后端: ${b.lang}/${b.framework} ${b.version}`);
    }
    if (f.framework && f.framework !== "unknown") {
        parts.push(`前端: ${f.lang}/${f.framework} ${f.version}`);
    }
    if (config.scope?.backend?.length) {
        parts.push(`后端 scope: ${config.scope.backend.join(", ")}`);
    }
    if (config.scope?.frontend?.length) {
        parts.push(`前端 scope: ${config.scope.frontend.join(", ")}`);
    }
    return parts.length > 0 ? parts.join("；") : "未检测到技术栈约束";
}
/**
 * 构建证据来源列表。
 * @param benchmarks - 候选方案列表
 * @param _knowledgeIndex - 知识索引管理器（未直接使用，预留参数）
 * @returns 证据来源列表
 */
function buildEvidenceSources(benchmarks, _knowledgeIndex) {
    const sources = [];
    sources.push({
        name: "项目配置",
        tier: "local_code",
        credibility: "high",
        description: "当前项目的技术栈、scope 和构建命令配置",
    });
    for (const b of benchmarks) {
        if (b.source === "industry") {
            sources.push({
                name: b.name,
                tier: "community_practice",
                credibility: "medium",
                description: `行业基准方案: ${b.description}`,
            });
        }
    }
    if (_knowledgeIndex) {
        sources.push({
            name: "项目知识库",
            tier: "local_code",
            credibility: "high",
            description: "项目积累的知识模板和决策规则",
        });
    }
    return sources;
}
/**
 * 构建被拒绝方案列表及拒绝原因。
 * @param benchmarks - 候选方案列表
 * @param recommendation - 架构师推荐结果
 * @returns 被拒绝方案列表
 */
function buildRejectedOptions(benchmarks, recommendation) {
    const rejected = benchmarks.filter((b) => b.name !== recommendation.recommended);
    return rejected.map((b) => ({
        name: b.name,
        reason: `致命缺点: ${b.fatal_weakness}`,
        steelman: `适用场景: ${b.best_for}（评分: ${RATING_KEYS.reduce((s, k) => s + b.ratings[k], 0)}/20）`,
    }));
}
/**
 * 构建知识新鲜度风险描述。
 * @param timeliness - 时效性信息
 * @param benchmarks - 候选方案列表
 * @returns 新鲜度风险描述文本
 */
function buildFreshnessRisk(timeliness, benchmarks) {
    const parts = [];
    if (timeliness.stale_warning) {
        parts.push(`基准数据已 ${timeliness.days_since_review} 天未更新，行业方案可能已有新版本`);
    }
    const industryCount = benchmarks.filter((b) => b.source === "industry").length;
    if (industryCount === 0) {
        parts.push("未匹配到行业标准方案，使用启发式兜底");
    }
    if (timeliness.days_since_review > 90 && !timeliness.stale_warning) {
        parts.push(`基准数据 ${timeliness.days_since_review} 天未更新，建议关注新版本发布`);
    }
    return parts.length > 0 ? parts.join("；") : "基准数据较新，知识过时风险低";
}
/**
 * 构建方案采用风险描述。
 * @param recommendation - 架构师推荐结果
 * @param benchmarks - 候选方案列表
 * @returns 采用风险描述文本
 */
function buildAdoptionRisk(recommendation, benchmarks) {
    const recommended = benchmarks.find((b) => b.name === recommendation.recommended);
    if (!recommended)
        return "无法评估采用风险";
    const parts = [];
    parts.push(`推荐方案「${recommended.name}」最差场景: ${recommended.worst_for}`);
    if (recommended.fatal_weakness) {
        parts.push(`致命弱点: ${recommended.fatal_weakness}`);
    }
    if (recommendation.prerequisites.length > 0) {
        parts.push(`前提条件: ${recommendation.prerequisites.join("；")}`);
    }
    return parts.join("；");
}
/**
 * 构建方案验证计划。
 * @param recommendation - 架构师推荐结果
 * @param benchmarks - 候选方案列表
 * @returns 验证计划文本
 */
function buildValidationPlan(recommendation, benchmarks) {
    const recommended = benchmarks.find((b) => b.name === recommendation.recommended);
    const parts = [];
    parts.push("1. 确认项目环境满足推荐方案的前提条件");
    if (recommended) {
        parts.push(`2. 在非关键路径上做最小 spike 验证「${recommended.name}」`);
        parts.push(`3. 验证推荐方案不触发致命弱点: ${recommended?.fatal_weakness ?? "无"}`);
    }
    parts.push("4. 执行构建和测试验证");
    parts.push("5. 回滚路径: 移除新增代码和配置即可恢复原状");
    return parts.join("\n");
}
/**
 * 构建决策有效期描述。
 * @param timeliness - 时效性信息
 * @returns 决策有效期描述文本
 */
function buildDecisionExpiry(timeliness) {
    const days = timeliness.days_since_review;
    if (days > 180)
        return "基准数据已过期，决策结论需立即重新验证";
    if (days > 90)
        return `建议 ${180 - days} 天内重新验证（基准数据 ${days} 天前审核）`;
    return `决策结论有效期至 ${new Date(Date.now() + (180 - days) * 86400000).toISOString().slice(0, 10)}`;
}
//# sourceMappingURL=exploration.js.map