# API Documentation

This document provides detailed API documentation for AI Developer Assistant's core components.

## Table of Contents

- [Domain Entities](#domain-entities)
- [Ports (Interfaces)](#ports-interfaces)
- [Use Cases](#use-cases)
- [Adapters](#adapters)
- [Configuration](#configuration)
- [Error Handling](#error-handling)

## Domain Entities

### Diff

Represents a code difference between two versions.

```typescript
interface Diff {
  readonly filePath: string;
  readonly oldContent: string;
  readonly newContent: string;
  readonly hunks: DiffHunk[];
  readonly language: string;
  readonly isNewFile: boolean;
  readonly isDeletedFile: boolean;
  readonly isBinary: boolean;
}

interface DiffHunk {
  readonly oldStart: number;
  readonly oldLines: number;
  readonly newStart: number;
  readonly newLines: number;
  readonly content: string;
  readonly lines: DiffLine[];
}

interface DiffLine {
  readonly type: 'added' | 'removed' | 'context';
  readonly content: string;
  readonly lineNumber: number;
}
```

### ReviewComment

Represents a code review comment with severity and category.

```typescript
interface ReviewComment {
  readonly id: string;
  readonly filePath: string;
  readonly lineNumber?: number;
  readonly message: string;
  readonly severity: ReviewSeverity;
  readonly category: ReviewCategory;
  readonly suggestion?: string;
  readonly codeSnippet?: string;
  readonly metadata?: Record<string, unknown>;
}

enum ReviewSeverity {
  ERROR = 'error',
  WARNING = 'warning',
  INFO = 'info',
  SUGGESTION = 'suggestion'
}

enum ReviewCategory {
  BUG = 'bug',
  STYLE = 'style',
  PERFORMANCE = 'performance',
  SECURITY = 'security',
  MAINTAINABILITY = 'maintainability',
  ACCESSIBILITY = 'accessibility',
  DOCUMENTATION = 'documentation'
}
```

### ReviewReport

Aggregated review results with metrics and recommendations.

```typescript
interface ReviewReport {
  readonly id: string;
  readonly timestamp: Date;
  readonly summary: string;
  readonly overallScore: number;
  readonly comments: ReviewComment[];
  readonly metrics: {
    readonly totalComments: number;
    readonly errorCount: number;
    readonly warningCount: number;
    readonly infoCount: number;
    readonly suggestionCount: number;
    readonly filesReviewed: number;
    readonly linesAdded: number;
    readonly linesRemoved: number;
  };
  readonly recommendations: string[];
}
```

### CodeBlock

Represents a block of code for analysis.

```typescript
interface CodeBlock {
  readonly content: string;
  readonly language: string;
  readonly startLine: number;
  readonly endLine: number;
  readonly filePath: string;
  readonly metadata?: Record<string, unknown>;
}
```

### SecurityIssue

Represents a security vulnerability or concern.

```typescript
interface SecurityIssue {
  readonly id: string;
  readonly severity: SecuritySeverity;
  readonly category: SecurityCategory;
  readonly title: string;
  readonly description: string;
  readonly filePath: string;
  readonly lineNumber?: number;
  readonly codeSnippet?: string;
  readonly cweId?: string;
  readonly remediation: string;
  readonly references: string[];
  readonly falsePositive: boolean;
  readonly metadata?: Record<string, unknown>;
}

enum SecuritySeverity {
  LOW = 'low',
  MEDIUM = 'medium',
  HIGH = 'high',
  CRITICAL = 'critical'
}

enum SecurityCategory {
  INJECTION = 'injection',
  AUTHENTICATION = 'authentication',
  AUTHORIZATION = 'authorization',
  CRYPTOGRAPHY = 'cryptography',
  DATA_EXPOSURE = 'data_exposure',
  INPUT_VALIDATION = 'input_validation',
  DEPENDENCY = 'dependency',
  CONFIGURATION = 'configuration',
  LOGGING = 'logging',
  OTHER = 'other'
}
```

### TestSuggestion

Represents a test case suggestion.

```typescript
interface TestSuggestion {
  readonly id: string;
  readonly testType: TestType;
  readonly framework: TestFramework;
  readonly description: string;
  readonly testCode: string;
  readonly setupCode?: string;
  readonly targetFunction?: string;
  readonly targetFile?: string;
  readonly testCases: TestCase[];
  readonly coverage?: TestCoverage;
}

enum TestType {
  UNIT = 'unit',
  INTEGRATION = 'integration',
  E2E = 'e2e',
  PERFORMANCE = 'performance',
  SECURITY = 'security'
}

enum TestFramework {
  JEST = 'jest',
  MOCHA = 'mocha',
  VITEST = 'vitest',
  CYPRESS = 'cypress',
  PLAYWRIGHT = 'playwright'
}
```

### DocSuggestion

Represents a documentation suggestion.

```typescript
interface DocSuggestion {
  readonly id: string;
  readonly type: DocumentationType;
  readonly format: DocumentationFormat;
  readonly title: string;
  readonly content: string;
  readonly targetFile?: string;
  readonly targetFunction?: string;
  readonly targetClass?: string;
  readonly targetModule?: string;
  readonly language?: string;
  readonly examples?: string[];
  readonly parameters?: DocParameter[];
  readonly returnType?: string;
  readonly seeAlso?: string[];
  readonly metadata?: Record<string, unknown>;
}

enum DocumentationType {
  FUNCTION = 'function',
  CLASS = 'class',
  INTERFACE = 'interface',
  MODULE = 'module',
  API = 'api',
  README = 'readme',
  CHANGELOG = 'changelog',
  ARCHITECTURE = 'architecture',
  TUTORIAL = 'tutorial',
  OTHER = 'other'
}

enum DocumentationFormat {
  MARKDOWN = 'markdown',
  JSDOC = 'jsdoc',
  TSDOC = 'tsdoc',
  ASCIIDOC = 'asciidoc',
  RST = 'rst',
  PLAIN = 'plain'
}
```

## Ports (Interfaces)

### DiffProviderPort

Interface for retrieving code differences.

```typescript
interface DiffProviderPort {
  getDiffs(options?: DiffOptions): Promise<Diff[]>;
  getFileDiff(filePath: string, options?: DiffOptions): Promise<Diff | null>;
  getCommitDiff(baseCommit: string, headCommit: string, options?: DiffOptions): Promise<Diff[]>;
  getStagedDiff(options?: DiffOptions): Promise<Diff[]>;
  getUnstagedDiff(options?: DiffOptions): Promise<Diff[]>;
  hasChanges(filePath: string, options?: DiffOptions): Promise<boolean>;
  getCommitInfo(commitHash: string): Promise<CommitInfo | null>;
}

interface DiffOptions {
  readonly baseRef?: string;
  readonly headRef?: string;
  readonly includeStaged?: boolean;
  readonly includeUnstaged?: boolean;
  readonly filePatterns?: string[];
  readonly excludePatterns?: string[];
}
```

### LLMPort

Interface for AI/LLM interactions.

```typescript
interface LLMPort {
  generateResponse(messages: LLMMessage[], options?: LLMOptions): Promise<LLMResponse>;
  generateStreamingResponse(
    messages: LLMMessage[], 
    options?: LLMOptions, 
    onChunk?: (chunk: string) => void
  ): Promise<LLMResponse>;
  getAvailableModels(): Promise<string[]>;
  isAvailable(): Promise<boolean>;
  getModelInfo(modelName: string): Promise<ModelInfo | null>;
}

interface LLMMessage {
  readonly role: 'system' | 'user' | 'assistant';
  readonly content: string;
}

interface LLMResponse {
  readonly content: string;
  readonly usage?: TokenUsage;
  readonly metadata?: Record<string, unknown>;
}

interface LLMOptions {
  readonly model?: string;
  readonly temperature?: number;
  readonly maxTokens?: number;
  readonly topP?: number;
  readonly frequencyPenalty?: number;
  readonly presencePenalty?: number;
}
```

### OutputPort

Interface for output formatting and display.

```typescript
interface OutputPort {
  displayReviewReport(report: ReviewReport, options?: OutputOptions): Promise<void>;
  displaySecurityIssues(issues: SecurityIssue[], options?: OutputOptions): Promise<void>;
  displayTestSuggestions(suggestions: TestSuggestion[], options?: OutputOptions): Promise<void>;
  displayDocSuggestions(suggestions: DocSuggestion[], options?: OutputOptions): Promise<void>;
  displayMessage(message: string, options?: OutputOptions): Promise<void>;
  displayError(error: string, options?: OutputOptions): Promise<void>;
  displayWarning(warning: string, options?: OutputOptions): Promise<void>;
  displaySuccess(message: string, options?: OutputOptions): Promise<void>;
  displayTable(data: Record<string, unknown>[], options?: OutputOptions): Promise<void>;
}

interface OutputOptions {
  readonly format?: OutputFormat;
  readonly outputPath?: string;
  readonly colorize?: boolean;
  readonly verbose?: boolean;
}

enum OutputFormat {
  CONSOLE = 'console',
  MARKDOWN = 'markdown',
  JSON = 'json',
  HTML = 'html',
  FILE = 'file'
}
```

### GitHubPort

Interface for GitHub API interactions.

```typescript
interface GitHubPort {
  postReviewComment(owner: string, repo: string, pullNumber: number, comment: ReviewComment): Promise<void>;
  postReviewComments(owner: string, repo: string, pullNumber: number, comments: ReviewComment[]): Promise<void>;
  postReviewReport(owner: string, repo: string, pullNumber: number, report: ReviewReport): Promise<void>;
  getPullRequest(owner: string, repo: string, pullNumber: number): Promise<PullRequestInfo | null>;
  getIssue(owner: string, repo: string, issueNumber: number): Promise<IssueInfo | null>;
  getRepository(owner: string, repo: string): Promise<RepositoryInfo | null>;
  isAccessible(): Promise<boolean>;
  getCurrentUser(): Promise<UserInfo | null>;
}
```

## Use Cases

### ReviewCodeUseCase

Handles code review analysis and reporting.

```typescript
class ReviewCodeUseCase {
  constructor(
    private readonly diffProvider: DiffProviderPort,
    private readonly llmPort: LLMPort,
    private readonly outputPort: OutputPort,
    private readonly githubPort?: GitHubPort
  ) {}

  async execute(options: ReviewCodeOptions): Promise<ReviewReport> {
    // Implementation details
  }
}

interface ReviewCodeOptions extends DiffOptions, OutputOptions {
  readonly postToGitHub?: boolean;
  readonly githubOwner?: string;
  readonly githubRepo?: string;
  readonly pullRequestNumber?: number;
}
```

### ExplainCodeUseCase

Provides code explanations in plain English.

```typescript
class ExplainCodeUseCase {
  constructor(
    private readonly diffProvider: DiffProviderPort,
    private readonly llmPort: LLMPort,
    private readonly outputPort: OutputPort
  ) {}

  async execute(options: ExplainCodeOptions): Promise<string> {
    // Implementation details
  }
}

interface ExplainCodeOptions extends DiffOptions, OutputOptions {
  readonly level?: 'basic' | 'detailed' | 'expert';
  readonly includeExamples?: boolean;
  readonly style?: 'formal' | 'casual' | 'technical' | 'beginner';
}
```

### GenerateCommitMessageUseCase

Generates commit messages based on code changes.

```typescript
class GenerateCommitMessageUseCase {
  constructor(
    private readonly diffProvider: DiffProviderPort,
    private readonly llmPort: LLMPort,
    private readonly outputPort: OutputPort
  ) {}

  async execute(options: CommitMessageOptions): Promise<string> {
    // Implementation details
  }
}

interface CommitMessageOptions extends DiffOptions, OutputOptions {
  readonly style?: 'conventional' | 'simple' | 'detailed';
  readonly maxLength?: number;
  readonly includeBody?: boolean;
}
```

### ScanSecurityUseCase

Performs security vulnerability scanning.

```typescript
class ScanSecurityUseCase {
  constructor(
    private readonly diffProvider: DiffProviderPort,
    private readonly securityScanner: SecurityScannerPort,
    private readonly outputPort: OutputPort
  ) {}

  async execute(options: SecurityScanOptions): Promise<SecurityIssue[]> {
    // Implementation details
  }
}

interface SecurityScanOptions extends DiffOptions, OutputOptions {
  readonly severity?: SecuritySeverity[];
  readonly categories?: SecurityCategory[];
  readonly includeDependencies?: boolean;
  readonly packageJsonPath?: string;
  readonly lockFilePath?: string;
}
```

## Configuration

### Configuration Interface

```typescript
interface Configuration {
  readonly llm: LLMConfig;
  readonly openai?: OpenAIConfig;
  readonly ollama?: OllamaConfig;
  readonly github?: GitHubConfig;
  readonly git: GitConfig;
  readonly output: OutputConfig;
  readonly security: SecurityConfig;
  readonly test: TestConfig;
  readonly documentation: DocumentationConfig;
  readonly review: ReviewConfig;
  readonly filePatterns?: string[];
  readonly excludePatterns?: string[];
  readonly verbose?: boolean;
  readonly debug?: boolean;
}

interface LLMConfig {
  readonly provider: 'openai' | 'ollama';
  readonly model: string;
  readonly temperature: number;
  readonly maxTokens: number;
  readonly timeout: number;
}

interface OpenAIConfig {
  readonly apiKey: string;
  readonly baseUrl: string;
  readonly organization?: string;
}

interface OllamaConfig {
  readonly enabled: boolean;
  readonly baseUrl: string;
  readonly model?: string;
}
```

## Error Handling

### Error Types

```typescript
class AIDevError extends Error {
  constructor(message: string, public readonly code: string, public readonly details?: unknown) {
    super(message);
    this.name = 'AIDevError';
  }
}

class ConfigurationError extends AIDevError {
  constructor(message: string, details?: unknown) {
    super(message, 'CONFIG_ERROR', details);
    this.name = 'ConfigurationError';
  }
}

class LLMError extends AIDevError {
  constructor(message: string, details?: unknown) {
    super(message, 'LLM_ERROR', details);
    this.name = 'LLMError';
  }
}

class GitError extends AIDevError {
  constructor(message: string, details?: unknown) {
    super(message, 'GIT_ERROR', details);
    this.name = 'GitError';
  }
}

class GitHubError extends AIDevError {
  constructor(message: string, details?: unknown) {
    super(message, 'GITHUB_ERROR', details);
    this.name = 'GitHubError';
  }
}
```

### Error Handling Patterns

```typescript
// In adapters
try {
  const result = await externalService.call();
  return result;
} catch (error) {
  throw new LLMError(
    `Failed to call LLM service: ${error.message}`,
    { originalError: error, context: 'generateResponse' }
  );
}

// In use cases
try {
  const diffs = await this.diffProvider.getDiffs(options);
  if (diffs.length === 0) {
    throw new AIDevError('No changes found to analyze', 'NO_CHANGES');
  }
  return await this.processDiffs(diffs);
} catch (error) {
  if (error instanceof AIDevError) {
    throw error;
  }
  throw new AIDevError('Unexpected error during code review', 'UNEXPECTED_ERROR', error);
}
```

## Examples

### Basic Usage

```typescript
import { LLMAdapter, GitAdapter, OutputAdapter } from './adapters';
import { ReviewCodeUseCase } from './usecases';
import { Configuration } from './config';

// Initialize adapters
const config = new Configuration();
const gitAdapter = new GitAdapter();
const llmAdapter = new LLMAdapter(config);
const outputAdapter = new OutputAdapter();

// Create use case
const reviewUseCase = new ReviewCodeUseCase(
  gitAdapter,
  llmAdapter,
  outputAdapter
);

// Execute review
const report = await reviewUseCase.execute({
  baseRef: 'main',
  headRef: 'feature-branch',
  format: 'console',
  verbose: true
});

console.log(`Review completed with score: ${report.overallScore}`);
```

### Custom Adapter Implementation

```typescript
class CustomLLMProvider implements LLMProvider {
  async generateResponse(messages: LLMMessage[]): Promise<LLMResponse> {
    // Custom implementation
    return {
      content: 'Custom response',
      metadata: { provider: 'custom' }
    };
  }
}

// Register custom provider
const llmAdapter = new LLMAdapter(config);
llmAdapter.registerProvider('custom', new CustomLLMProvider());
```

---

For more detailed examples and advanced usage patterns, see the [Examples](examples/) directory.
