/**
 * nexus-agents setup rules generation
 *
 * Rules file and backup management helpers.
 *
 * @module cli/setup-rules
 * (Source: Issue #363 - Auto-configure Claude CLI integration)
 */

import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { VERSION } from '../version.js';
import { getTimeProvider } from '../core/index.js';
import type { BackupInfo } from './setup-types.js';

/**
 * Generates the nexus-agents rules file content.
 */
export function generateRulesContent(): string {
  return `# Nexus-Agents Integration

This project uses [nexus-agents](https://github.com/nexus-substrate/nexus-agents) v${VERSION} for multi-agent orchestration.

## MCP Tools Available

When running with MCP server mode, these tools are available:

| Tool | Description |
| ---- | ----------- |
| \`orchestrate\` | Task orchestration with Orchestrator coordination |
| \`create_expert\` | Dynamic expert agent creation |
| \`run_workflow\` | Execute workflow templates |
| \`delegate_to_model\` | Route task to optimal model |
| \`list_experts\` | List available expert types (discoverability) |
| \`list_workflows\` | List available workflow templates |

## Quick Commands

\`\`\`bash
# Orchestrate a task with specialized experts
nexus-agents orchestrate "Implement feature X with tests"

# List available experts
nexus-agents expert list

# Run a workflow
nexus-agents workflow list
nexus-agents workflow run code-review --input='{"url": "..."}'

# Check system health
nexus-agents doctor

# Generate config
nexus-agents config init
\`\`\`

## Usage Examples

**Orchestrate a code review:**
\`\`\`
Use nexus-agents to review this PR: https://github.com/owner/repo/pull/123
\`\`\`

**Create a specialized expert:**
\`\`\`
Create a security expert to audit this codebase for vulnerabilities
\`\`\`

**Run a workflow:**
\`\`\`
Run the code-review workflow with the current changes
\`\`\`

## Configuration

- Config file: \`./nexus-agents.yaml\`
- Generate config: \`nexus-agents config init\`
- Check health: \`nexus-agents doctor\`

---
*Generated by nexus-agents setup v${VERSION}*
`;
}

/**
 * Gets the rules file path.
 *
 * As of #2121 rules live at `<root>/.rules/` (harness-neutral location,
 * was `.claude/rules/`). Claude Code finds them via CLAUDE.md references,
 * so the move doesn't break its auto-load. Non-Claude harnesses (OpenCode,
 * Codex, Cursor, etc.) can point at the same directory.
 */
export function getRulesFilePath(projectRoot: string): string {
  return join(projectRoot, '.rules', 'nexus-agents.md');
}

/**
 * Creates the rules file.
 */
export function createRulesFile(projectRoot: string, dryRun: boolean): string {
  const rulesPath = getRulesFilePath(projectRoot);
  const content = generateRulesContent();

  if (!dryRun) {
    const rulesDir = dirname(rulesPath);
    mkdirSync(rulesDir, { recursive: true });
    writeFileSync(rulesPath, content, 'utf-8');
  }

  return rulesPath;
}

/**
 * Creates a backup of a file.
 */
export function backupFile(filePath: string): BackupInfo {
  const content = readFileSync(filePath, 'utf-8');
  const backupPath = `${filePath}.backup.${String(getTimeProvider().now())}`;
  writeFileSync(backupPath, content, 'utf-8');

  return {
    type: 'file',
    originalPath: filePath,
    backupPath,
    content,
  };
}

/**
 * Restores a file from backup.
 */
export function restoreBackup(backup: BackupInfo): void {
  writeFileSync(backup.originalPath, backup.content, 'utf-8');
}
