export type TaskType = 'fix' | 'extend' | 'refactor' | 'understand' | 'review' | 'plan';

export interface ContextWeights {
  blastRadius: number;
  directDeps: number;
  history: number;
  governance: number;
  community: number;
}

export const TASK_WEIGHTS: Record<TaskType, ContextWeights> = {
  fix:        { blastRadius: 0.3, directDeps: 0.3, history: 0.2, governance: 0.1, community: 0.1 },
  extend:     { blastRadius: 0.1, directDeps: 0.4, history: 0.1, governance: 0.1, community: 0.3 },
  refactor:   { blastRadius: 0.5, directDeps: 0.2, history: 0.1, governance: 0.1, community: 0.1 },
  understand: { blastRadius: 0.1, directDeps: 0.5, history: 0.2, governance: 0.0, community: 0.2 },
  review:     { blastRadius: 0.4, directDeps: 0.2, history: 0.2, governance: 0.2, community: 0.0 },
  plan:       { blastRadius: 0.2, directDeps: 0.2, history: 0.1, governance: 0.1, community: 0.4 },
};

export function classifyTaskType(taskText: string, agentRole: string): TaskType {
  if (agentRole === 'reviewer') return 'review';
  if (agentRole === 'planner') return 'plan';
  if (/fix|bug|error|crash|broken|fail/i.test(taskText)) return 'fix';
  if (/refactor|rename|move|restructure|clean/i.test(taskText)) return 'refactor';
  if (/add|implement|create|build|feature|extend/i.test(taskText)) return 'extend';
  return 'understand';
}

export function getWeightsForTask(taskText: string, agentRole: string): ContextWeights {
  const taskType = classifyTaskType(taskText, agentRole);
  
  // Quantum path evaluator: boost governance weight when stuck patterns are recent
  // This causes the retrieval pipeline to pull more governance/lesson context
  // when the agent is likely to repeat a stuck pattern
  try {
    const { shannonEntropy } = require('../lib/graph/analytics/quantum-entropy-detector.js');
    // If task text itself contains error-like keywords, boost governance context
    const hasErrorContext = /error|fail|not found|timed out|retry|again|still/i.test(taskText);
    if (hasErrorContext) {
      const base = TASK_WEIGHTS[taskType];
      return {
        ...base,
        governance: Math.min(0.4, base.governance + 0.15), // boost governance retrieval
        history: Math.min(0.4, base.history + 0.1),        // boost historical context
        blastRadius: Math.max(0, base.blastRadius - 0.1),  // reduce blast radius weight
      };
    }
  } catch (_) { /* fail-open */ }
  return TASK_WEIGHTS[taskType];
}
