/**
 * Documentation Generator
 *
 * Generates README.md and AGENTS.md in src/generated/ directory
 * Only writes files if they don't already exist (preserves user modifications)
 */

import { join } from 'node:path';
import { mkdir } from 'node:fs/promises';
import type { Logger } from '../../../types';

const README_CONTENT = `# Generated Files - DO NOT EDIT

This directory contains auto-generated TypeScript files created by the Agentuity build system.

**These files are regenerated on every build.** Any manual changes will be overwritten.

## Generated Files

- \`registry.ts\` - Agent registry from \`src/agent/**\`
- \`app.ts\` - Application entry point
- \`analytics-config.ts\` - Web analytics configuration from \`agentuity.json\`
- \`webanalytics.ts\` - Web analytics injection and route registration
- \`env.d.ts\` - TypeScript types for environment variables from \`.env\` files
- \`state.ts\` - App state type (only generated when \`setup()\` returns state in \`app.ts\`)
- \`router.ts\` - Runtime wrapper with type augmentation (only generated when \`setup()\` returns state in \`app.ts\`)

## Environment Variable Types

The \`env.d.ts\` file provides TypeScript intellisense for your environment variables:

- **ProcessEnv**: All variables from your \`.env\` files are typed as \`string\`
- **ImportMetaEnv**: Only \`VITE_*\`, \`AGENTUITY_PUBLIC_*\`, and \`PUBLIC_*\` prefixed variables (for client-side use)

Files are merged based on build mode:
- **Development**: \`.env.{profile}\` → \`.env.development\` → \`.env\` (later files override)
- **Production**: \`.env.{profile}\` → \`.env\` → \`.env.production\` (later files override)

## For Developers

Do not modify these files. Instead:
- Add/modify agents in \`src/agent/\`
- Add/modify routes in \`src/api/\`
- Configure app in \`app.ts\`
- Add environment variables to \`.env\` files

These files ARE version controlled to enable better tooling and type checking.
`;

const AGENTS_MD_CONTENT = `# AI Agent Instructions

**CRITICAL:** Files in this directory are AUTO-GENERATED by the Agentuity build system.

## Rules for AI Agents

1. ❌ NEVER edit files in \`src/generated/\`
2. ❌ NEVER include \`src/generated/\` files in context when analyzing code
3. ❌ NEVER suggest changes to generated files
4. ✅ Ignore this directory when searching for user code
5. ✅ Direct users to modify source files in \`src/agent/\`, \`src/api/\`, \`app.ts\`, or \`.env\` files

## What Gets Generated

- \`registry.ts\` - Built from agent discovery in \`src/agent/\`
- \`app.ts\` - Entry point assembled from project configuration
- \`analytics-config.ts\` - Web analytics configuration from \`agentuity.json\`
- \`webanalytics.ts\` - Web analytics injection and route registration
- \`env.d.ts\` - TypeScript types for environment variables from \`.env\` files
- \`state.ts\` - App state type (only generated when \`setup()\` returns state in \`app.ts\`)
- \`router.ts\` - Runtime wrapper with type augmentation (only generated when \`setup()\` returns state)

These files are regenerated on every \`bun run build\` or \`bun run dev\`.
`;

/**
 * Generate documentation files in src/generated/ directory
 * Only creates files if they don't already exist
 */
export async function generateDocumentation(srcDir: string, logger: Logger): Promise<void> {
	const generatedDir = join(srcDir, 'generated');

	// Ensure directory exists
	await mkdir(generatedDir, { recursive: true });

	const readmePath = join(generatedDir, 'README.md');
	const agentsMdPath = join(generatedDir, 'AGENTS.md');

	// Generate README.md if it doesn't exist
	if (!(await Bun.file(readmePath).exists())) {
		await Bun.write(readmePath, README_CONTENT);
		logger.debug('Generated src/generated/README.md');
	} else {
		logger.trace('Skipping README.md - file already exists');
	}

	// Generate AGENTS.md if it doesn't exist
	if (!(await Bun.file(agentsMdPath).exists())) {
		await Bun.write(agentsMdPath, AGENTS_MD_CONTENT);
		logger.debug('Generated src/generated/AGENTS.md');
	} else {
		logger.trace('Skipping AGENTS.md - file already exists');
	}
}
