import { routeIntent, shouldEnterSoloForge } from "./intent_router.js";
import { debugLog } from "../core/logger.js";
debugLog("classifier: 任务分类器模块已加载");
/**
 * 任务分类器 — 根据用户意图文本分类任务类型、风险等级和执行策略。
 * 零 AI 依赖，纯关键词 + 规则匹配。
 *
 * 入口裁决权已移至 Intent Router (intent_router.ts)。
 * task_type 保留为辅助描述，不再单独决定是否进入 SoloForge。
 */
// ── 分类规则表 ──
const TYPE_RULES = [
    { keywords: ["新建", "新建模块", "初始化", "脚手架", "scaffold"], type: "scaffold" },
    { keywords: ["紧急修复", "线上问题", "生产环境", "hotfix"], type: "hotfix" },
    { keywords: ["修复", "fix", "bug", "错误", "异常", "NPE", "空指针", "报错"], type: "bugfix" },
    { keywords: ["review", "审查", "看看", "检查代码", "代码质量"], type: "review" },
    { keywords: ["解释", "说明", "什么意思", "怎么理解"], type: "explain" },
    { keywords: ["优化", "性能", "加速", "慢", "提高性能", "加快"], type: "optimize" },
    { keywords: ["文档", "注释", "README"], type: "document" },
    { keywords: ["测试", "test", "补测试", "写测试", "单元测试"], type: "test" },
    { keywords: ["调试", "排障", "为什么报错", "排查"], type: "debug" },
    { keywords: ["重构", "优化结构", "提取", "抽象", "拆分"], type: "refactor" },
    { keywords: ["加功能", "新增", "新功能", "创建", "实现", "开发", "添加", "加一个", "加个", "加上", "增加", "做一个", "写一个", "写个", "做个"], type: "feature" },
];
const HIGH_AMBIGUITY_VERBS = ["优化", "重构", "改进", "提升", "调整", "完善", "梳理"];
const CLEAR_VERBS = ["加", "修", "删", "改", "新建", "创建", "实现"];
const CLEAR_OBJECTS_PATTERNS = [
    /^[A-Z]\w*(Service|Controller|Mapper|Repository|Component|Module)/,
    /\.(ts|tsx|java|py|yaml|json)$/,
    /api\/|\/v\d\//,
];
/**
 * 对用户意图进行分类。
 * 先调用 Intent Router 获取 route_decision，
 * 再用旧规则填充 task_type / risk / complexity / ambiguity。
 * strategy 和 mode 从 route_decision 派生。
 *
 * @param input - 分类输入参数，包含用户意图文本和可选的项目路径/任务 ID
 * @returns 分类结果，包含任务类型、风险等级、复杂度、歧义度和路由决策
 */
export function classify(input) {
    const { intent } = input;
    const normalized = intent.toLowerCase();
    debugLog("classifier: 开始意图分类");
    // 1. 调用 Intent Router（新入口裁决）
    const routeDecision = routeIntent(input);
    // 2. 旧规则填充辅助字段
    const taskType = matchType(normalized);
    const ambiguity = assessAmbiguity(intent, normalized);
    const risk = assessRisk(taskType, normalized);
    const complexity = assessComplexity(normalized);
    // 3. strategy 从 route_decision 派生（不再由 task_type 直接决定）
    const strategy = deriveStrategy(routeDecision);
    const mode = deriveMode(routeDecision, risk);
    const result = {
        task_type: taskType,
        risk,
        complexity,
        ambiguity,
        affected_repos: guessRepos(normalized),
        mode,
        strategy,
        route_decision: routeDecision,
    };
    if (ambiguity === "medium") {
        result.clarification = {
            summary: buildSummary(intent, taskType),
        };
    }
    else if (ambiguity === "high") {
        result.clarification = {
            summary: buildSummary(intent, taskType),
            questions: generateQuestions(intent, taskType),
        };
    }
    debugLog(`classifier: 分类完成 — 类型=${taskType}，路由=${routeDecision.route}，风险=${risk}`);
    return result;
}
/**
 * 从 route_decision 派生 strategy。
 * 只有 skip_chat 和 direct_answer 映射为 skip_soloForge。
 * review 路由为 review 策略（不强塞 sf_expand）。
 *
 * @param decision - 意图路由决策
 * @returns 执行策略
 */
function deriveStrategy(decision) {
    if (!shouldEnterSoloForge(decision))
        return "skip_soloForge";
    // review 路由走 quick_fix（由 sf_review 处理，不强塞 sf_expand）
    if (decision.route === "review")
        return "quick_fix";
    // operation 路由走 quick_fix（sf_verify 直接处理）
    if (decision.route === "operation")
        return "quick_fix";
    // multi_stage_plan 走 full_pipeline
    if (decision.execution_shape === "multi_stage_plan")
        return "full_pipeline";
    // code_execution 走 full_pipeline 或 quick_fix
    if (decision.execution_shape === "code_execution") {
        // 保留旧逻辑兼容: bugfix/hotfix/test → quick_fix
        return "full_pipeline";
    }
    // 其他（single_artifact, read_only_analysis, verification_only）走 full_pipeline
    return "full_pipeline";
}
/**
 * 从 route_decision 和 risk 派生 mode。
 * @param decision - 意图路由决策
 * @param risk - 风险等级
 * @returns 执行模式（passthrough / supervised / autonomous）
 */
function deriveMode(decision, risk) {
    if (!shouldEnterSoloForge(decision))
        return "passthrough";
    if (risk === "high")
        return "supervised";
    return "autonomous";
}
// ── 旧规则函数（保留作为辅助描述） ──
/** 根据关键词匹配任务类型 */
function matchType(normalized) {
    if (/加(?!快|密|载|剧|速|深|重)[^\s]{1,8}(接口|功能|模块|页面|字段|按钮|服务|权限|配置|能力|校验|逻辑|规则|支持|特性)/.test(normalized))
        return "feature";
    if (/优化.*(结构|架构|代码|组织|设计)/i.test(normalized))
        return "refactor";
    if (normalized.includes("新建模块") || normalized.includes("脚手架") || normalized.includes("scaffold"))
        return "scaffold";
    if (normalized.includes("紧急修复") || normalized.includes("线上问题") || normalized.includes("生产环境") || normalized.includes("hotfix"))
        return "hotfix";
    for (const rule of TYPE_RULES) {
        if (rule.keywords.some((kw) => normalized.includes(kw.toLowerCase()))) {
            return rule.type;
        }
    }
    return "passthrough";
}
/** 评估意图歧义度 — 根据动词清晰度和对象明确度判断 */
function assessAmbiguity(intent, normalized) {
    const hasClearVerb = CLEAR_VERBS.some((v) => normalized.includes(v));
    const hasClearObject = CLEAR_OBJECTS_PATTERNS.some((p) => p.test(intent));
    const hasAmbiguousVerb = HIGH_AMBIGUITY_VERBS.some((v) => normalized.includes(v));
    if (hasAmbiguousVerb && !hasClearObject)
        return "high";
    if (hasClearVerb && hasClearObject)
        return "low";
    if (hasClearVerb || hasClearObject)
        return "low";
    return "medium";
}
/** 评估风险等级 — 根据任务类型和涉及领域判断 */
function assessRisk(type, normalized) {
    if (type === "hotfix")
        return "high";
    if (["bugfix", "refactor"].includes(type) && /数据库|migration|ddl|schema/i.test(normalized))
        return "high";
    if (["feature", "scaffold"].includes(type))
        return "medium";
    if (["review", "explain", "document", "passthrough"].includes(type))
        return "low";
    return "medium";
}
/** 评估复杂度 — 根据关键词推断任务复杂程度 */
function assessComplexity(normalized) {
    const complexHints = ["多个", "批量", "跨", "联调", "前后端", "多仓库", "全链路"];
    if (complexHints.some((h) => normalized.includes(h)))
        return "high";
    if (/加.*查询|加.*字段|改.*名称|修.*typo/i.test(normalized))
        return "low";
    return "medium";
}
/** 根据关键词猜测涉及的仓库 */
function guessRepos(normalized) {
    const repos = [];
    if (/后端|backend|java|spring|service|controller|mapper|api/i.test(normalized))
        repos.push("backend");
    if (/前端|frontend|react|vue|页面|组件|ui|tsx?/i.test(normalized))
        repos.push("frontend");
    if (repos.length === 0)
        repos.push("backend", "frontend");
    return repos;
}
/** 构建分类摘要文本 */
function buildSummary(intent, type) {
    return `意图分析: ${type} 类型 — "${intent}"`;
}
/**
 * 生成澄清问题 — 高歧义意图时向用户追问细节。
 * @param intent - 用户意图文本
 * @param _type - 任务类型（预留参数，当前未使用）
 * @returns 澄清问题列表
 */
function generateQuestions(intent, _type) {
    const questions = [];
    if (/优化/.test(intent)) {
        questions.push("性能优化 / 结构优化 / 可维护性优化？");
    }
    if (/重构/.test(intent)) {
        questions.push("涉及哪些模块？是否保持接口兼容？");
    }
    if (/改进|调整|完善/.test(intent) && !questions.length) {
        questions.push("具体要改进哪个方面？");
    }
    if (!questions.length) {
        questions.push("请补充更多细节：具体修改哪些文件/模块？");
    }
    return questions;
}
//# sourceMappingURL=classifier.js.map