/**
 * Transform: generate src/services.ts
 *
 * Creates a shared services module that exports singleton client instances
 * for all Agentuity services detected in use across the project.
 *
 * Only includes services that are actually used — no unnecessary dependencies.
 */

import { SERVICE_PACKAGE_MAP } from '../../detect-v3';

export interface ServicesFileResult {
	/** Generated source for src/services.ts, or null if no services used */
	source: string | null;
	/** What was included */
	changes: string[];
}

/**
 * Generate src/services.ts based on detected service usage.
 */
export function generateServicesFile(servicesUsed: string[]): ServicesFileResult {
	if (servicesUsed.length === 0) {
		return { source: null, changes: [] };
	}

	const changes: string[] = [];
	const imports: string[] = [];
	const exports: string[] = [];

	// Header comment
	const header = [
		'/**',
		' * Shared Agentuity service clients.',
		' *',
		' * Auto-generated by @agentuity/migrate (v2 → v3 migration).',
		' * Each client auto-configures from AGENTUITY_* environment variables.',
		' *',
		' * Usage:',
		" *   import { kv, vector } from './services';",
		" *   const data = await kv.get('namespace', 'key');",
		' */',
		'',
	];

	// Logger is special — comes from @agentuity/telemetry
	const hasLogger = servicesUsed.includes('logger');
	const serviceClients = servicesUsed.filter((s) => s !== 'logger');

	// Generate import + export for each service client
	for (const service of serviceClients.sort()) {
		const mapping = SERVICE_PACKAGE_MAP[service];
		if (!mapping) continue;

		imports.push(`import { ${mapping.client} } from '${mapping.pkg}';`);
		exports.push(`export const ${service} = new ${mapping.client}();`);
		changes.push(`Added ${service} client from ${mapping.pkg}`);
	}

	// Logger from telemetry
	if (hasLogger) {
		imports.push("import { register } from '@agentuity/telemetry';");
		exports.push('');
		exports.push('/** Shared logger instance from telemetry */');
		exports.push('const telemetry = register();');
		exports.push('export const logger = telemetry.logger;');
		changes.push('Added logger from @agentuity/telemetry');
	}

	const lines = [...header, ...imports, '', ...exports, ''];

	return {
		source: lines.join('\n'),
		changes,
	};
}
