// Copyright (c) 2026 defconxt. All rights reserved.
// Licensed under AGPL-3.0 — see LICENSE file for details.
// NERF is a trademark of defconxt.

/**
 * RESEARCHER mode agent — Security Research & Analysis.
 *
 * Provides CVE analysis, vulnerability research, reverse engineering support,
 * and threat landscape mapping. Tools focus on structured analysis and
 * knowledge extraction rather than active exploitation.
 *
 * @module execution-engine/modes/researcher
 */

import { ModeAgentConfig, ToolRegistry } from '../framework.js';
import { readFileSync, existsSync, readdirSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';

const __dirname = dirname(fileURLToPath(import.meta.url));

const debug = process.env.NERF_DEBUG === '1'
  ? (/** @type {string} */ msg) => process.stderr.write(`[researcher-mode] ${msg}\n`)
  : () => {};

// ---------------------------------------------------------------------------
// Tool handlers
// ---------------------------------------------------------------------------

/**
 * Analyze a CVE by ID — extract structured vulnerability information.
 * @param {*} context
 * @param {Object} toolInput
 * @returns {string}
 */
function _researcherAnalyzeCve(context, toolInput) {
  const cveId = (toolInput.cve_id || '').toUpperCase();
  if (!/^CVE-\d{4}-\d{4,}$/.test(cveId)) {
    return `Invalid CVE ID format: "${cveId}". Expected format: CVE-YYYY-NNNNN`;
  }

  return JSON.stringify({
    cve_id: cveId,
    analysis_template: {
      summary: `Analyze ${cveId} — provide description, affected software, CVSS score, exploitability, patch status`,
      sections: [
        'Vulnerability Description',
        'Affected Versions',
        'CVSS Score & Vector',
        'Exploitability Assessment',
        'Proof of Concept Status',
        'Patch / Mitigation Status',
        'Detection Opportunities',
        'ATT&CK Technique Mapping',
        'Recommendations',
      ],
      data_sources: [
        `https://nvd.nist.gov/vuln/detail/${cveId}`,
        `https://cve.mitre.org/cgi-bin/cvename.cgi?name=${cveId}`,
        'Vendor advisories',
        'ExploitDB / PacketStorm',
      ],
    },
    instruction: `Research ${cveId} using available knowledge and web search. Fill in each section with findings. Rate confidence per claim.`,
  }, null, 2);
}

/**
 * Search NERF knowledge base for relevant security research material.
 * @param {*} context
 * @param {Object} toolInput
 * @returns {string}
 */
function _researcherSearchKnowledge(context, toolInput) {
  const query = (toolInput.query || '').toLowerCase();
  if (!query) {
    return 'Error: query is required';
  }

  const knowledgeDir = join(__dirname, '..', '..', '..', 'knowledge');
  const results = [];

  if (!existsSync(knowledgeDir)) {
    return JSON.stringify({ query, results: [], note: 'Knowledge directory not found' });
  }

  try {
    const files = readdirSync(knowledgeDir);
    const queryTerms = query.split(/\s+/).filter(t => t.length > 2);

    for (const file of files) {
      if (!file.endsWith('.md')) continue;
      const filePath = join(knowledgeDir, file);
      try {
        const content = readFileSync(filePath, 'utf8');
        const lower = content.toLowerCase();

        // Score by term matches
        let score = 0;
        for (const term of queryTerms) {
          const matches = (lower.match(new RegExp(term, 'g')) || []).length;
          score += Math.min(matches, 10);
        }

        if (score > 0) {
          const headingMatch = content.match(/^# (.+)$/m);
          const title = headingMatch ? headingMatch[1] : file;

          results.push({
            file,
            title,
            score,
            preview: content.slice(0, 200).replace(/\n/g, ' ').trim(),
          });
        }
      } catch {
        // skip unreadable files
      }
    }
  } catch {
    // knowledge dir scan failed
  }

  results.sort((a, b) => b.score - a.score);

  return JSON.stringify({
    query,
    results: results.slice(0, 10),
    totalMatches: results.length,
  }, null, 2);
}

/**
 * Generate a structured research report template.
 * @param {*} context
 * @param {Object} toolInput
 * @returns {string}
 */
function _researcherWriteReport(context, toolInput) {
  const topic = toolInput.topic || 'Security Research';
  const findings = toolInput.findings || [];
  const recommendations = toolInput.recommendations || [];
  const confidence = toolInput.confidence || 'MEDIUM';

  const report = {
    title: topic,
    generated: new Date().toISOString(),
    confidence,
    sections: {
      executive_summary: `Research analysis of: ${topic}`,
      findings: findings.length > 0 ? findings : ['No findings provided — populate from research'],
      recommendations: recommendations.length > 0 ? recommendations : ['No recommendations provided'],
      attack_surface: 'Map relevant ATT&CK techniques',
      detection_opportunities: 'Identify defensive detection points',
      references: 'Cite sources with confidence ratings',
    },
    metadata: {
      researcher: 'NERF Autonomous Researcher',
      mode: 'RESEARCHER',
      format: 'structured-json',
    },
  };

  return JSON.stringify(report, null, 2);
}

// ---------------------------------------------------------------------------
// Tool schemas
// ---------------------------------------------------------------------------

const _RESEARCHER_ANALYZE_CVE_SCHEMA = {
  name: 'analyze_cve',
  description:
    'Analyze a CVE by ID. Returns a structured analysis template with sections to investigate. ' +
    'Use this to begin CVE research — it provides the framework, then fill sections with findings.',
  input_schema: {
    type: 'object',
    properties: {
      cve_id: {
        type: 'string',
        description: 'CVE identifier (e.g., CVE-2024-1234)',
      },
    },
    required: ['cve_id'],
  },
};

const _RESEARCHER_SEARCH_KNOWLEDGE_SCHEMA = {
  name: 'search_knowledge',
  description:
    'Search the NERF knowledge base for security research material. ' +
    'Returns matching documents ranked by relevance with previews.',
  input_schema: {
    type: 'object',
    properties: {
      query: {
        type: 'string',
        description: 'Search query (e.g., "buffer overflow exploitation", "ransomware detection")',
      },
    },
    required: ['query'],
  },
};

const _RESEARCHER_WRITE_REPORT_SCHEMA = {
  name: 'write_research_report',
  description:
    'Generate a structured security research report. ' +
    'Provide topic, findings, and recommendations to produce a formatted report.',
  input_schema: {
    type: 'object',
    properties: {
      topic: {
        type: 'string',
        description: 'Research topic or title',
      },
      findings: {
        type: 'array',
        items: { type: 'string' },
        description: 'List of research findings',
      },
      recommendations: {
        type: 'array',
        items: { type: 'string' },
        description: 'List of actionable recommendations',
      },
      confidence: {
        type: 'string',
        enum: ['HIGH', 'MEDIUM', 'LOW'],
        description: 'Overall confidence level in the research',
      },
    },
    required: ['topic'],
  },
};

// ---------------------------------------------------------------------------
// System prompt
// ---------------------------------------------------------------------------

const _RESEARCHER_SYSTEM_PROMPT = `\
You are an expert security researcher performing in-depth analysis on a security topic. \
Your goal is to produce thorough, actionable research with clear confidence ratings.

## Research Protocol

1. **Scope the topic** — understand what's being asked and what deliverables are needed
2. **Search knowledge** — use search_knowledge to find relevant NERF docs
3. **Analyze** — for CVEs use analyze_cve, for other topics use structured analysis
4. **Synthesize** — combine findings into a coherent narrative with ATT&CK mappings
5. **Report** — use write_research_report to produce the final structured output

## Confidence Ratings
Tag every substantive claim:
- **[CONFIRMED]** — directly supported by evidence or established literature
- **[INFERRED]** — logically derived; reasonable but verify
- **[EXTERNAL]** — requires knowledge beyond current material; source cited
- **[UNCERTAIN]** — insufficient data; states what additional information is needed

## Output Format
Your research must include:
- Executive summary (2-3 sentences)
- Detailed findings with evidence
- ATT&CK technique mappings where applicable
- Actionable recommendations ordered by priority
- Detection opportunities for defensive teams
- Confidence assessment per finding

## Important Notes
- Be thorough but concise — depth over breadth
- Cite specific sources, files, CVEs, or standards
- Flag gaps in knowledge explicitly rather than guessing
- If the topic requires current information, note what needs web search verification
`;

// ---------------------------------------------------------------------------
// Factory
// ---------------------------------------------------------------------------

/**
 * Build a RESEARCHER-mode ModeAgentConfig.
 * @returns {ModeAgentConfig}
 */
function _makeResearcherConfig() {
  const reg = new ToolRegistry();
  reg.register('analyze_cve', _RESEARCHER_ANALYZE_CVE_SCHEMA, _researcherAnalyzeCve);
  reg.register('search_knowledge', _RESEARCHER_SEARCH_KNOWLEDGE_SCHEMA, _researcherSearchKnowledge);
  reg.register('write_research_report', _RESEARCHER_WRITE_REPORT_SCHEMA, _researcherWriteReport);

  return new ModeAgentConfig({
    mode: 'RESEARCHER',
    toolRegistry: reg,
    systemPromptTemplate: _RESEARCHER_SYSTEM_PROMPT,
    validator: null, // No structured validation — output is freeform research
    maxTurns: 20,
    requiresSandbox: false,
    completionCheck: null,
  });
}

// ---------------------------------------------------------------------------
// Registration
// ---------------------------------------------------------------------------

/**
 * Register RESEARCHER mode with the given registerMode function.
 * @param {Function} registerMode
 */
export function register(registerMode) {
  registerMode('RESEARCHER', _makeResearcherConfig);
}

// ---------------------------------------------------------------------------
// Exports for testing
// ---------------------------------------------------------------------------

export {
  _makeResearcherConfig,
  _researcherAnalyzeCve,
  _researcherSearchKnowledge,
  _researcherWriteReport,
};
