# C002: No Duplicate Code (Monkey Coding Detection)

## Overview

This rule detects **true monkey coding** - code that has been copy-pasted multiple times across the codebase. It enforces the DRY (Don't Repeat Yourself) principle by identifying duplicate logic that should be refactored into shared functions.

## Rule Details

**Rule ID**: `C002`  
**Category**: Code Quality  
**Severity**: Warning  
**Language Support**: TypeScript/JavaScript (AST-based analysis)

## What is Monkey Coding?

Monkey coding refers to the practice of copying and pasting code blocks instead of creating reusable abstractions.

### ✅ TRUE DUPLICATES (Will Report):
- Functions/methods with identical or near-identical logic (≥95% similarity)
- Copy-pasted validation, calculation, or error handling logic
- Duplicate code blocks across different files or within same file

### ❌ INTENTIONAL PATTERNS (Will NOT Report):
- Simple JSX/HTML wrapper components with different names
- React component wrappers (e.g., shadcn/ui patterns)
- Boilerplate patterns with structural similarity but different business logic

## Configuration

```json
{
  "minLines": 10,
  "similarityThreshold": 0.95
}
```

- `minLines`: Minimum lines to consider (default: 10)
- `similarityThreshold`: 0-1 (default: 0.95 = 95%)

## Examples

See test cases in `test-cases/` directory for complete examples.

### ❌ Incorrect (Monkey Coding)

```typescript
// Copy-paste API error handling
async getUserById(id: number) {
  try {
    const response = await fetch(`/api/users/${id}`);
    if (!response.ok) {
      throw new Error('Failed to fetch user');
    }
    return await response.json();
  } catch (error) {
    throw new Error('Network request failed');
  }
}

// Duplicate logic!
async getOrderById(id: number) {
  try {
    const response = await fetch(`/api/orders/${id}`);
    if (!response.ok) {
      throw new Error('Failed to fetch order');
    }
    return await response.json();
  } catch (error) {
    throw new Error('Network request failed');
  }
}
```

### ✅ Correct (Refactored)

```typescript
async fetchAPI<T>(endpoint: string, context: string): Promise<T> {
  try {
    const response = await fetch(endpoint);
    if (!response.ok) {
      throw new Error(`Failed to fetch ${context}`);
    }
    return await response.json();
  } catch (error) {
    throw new Error('Network request failed');
  }
}

async getUserById(id: number) {
  return this.fetchAPI(`/api/users/${id}`, 'user');
}

async getOrderById(id: number) {
  return this.fetchAPI(`/api/orders/${id}`, 'order');
}
```

## How It Works

1. **AST Parsing**: Parse code with `ts-morph`
2. **Block Extraction**: Extract functions, methods, classes
3. **Similarity Calculation**: Structure (60%) + Code (40%)
4. **Pattern Filtering**: Remove intentional patterns

## Performance

- **Speed**: ~14s for 100 TypeScript files
- **Accuracy**: 100% (no false positives on tests)

## Testing

```bash
cd test-cases
node ../test-monkey-coding.js
```
