/**
 * Debug Package Packager
 *
 * Creates a zip file containing all debug package contents.
 */

import archiver from 'archiver';
import * as fs from 'fs';
import * as path from 'path';

export interface PackageContents {
	'system-info.json': unknown;
	'settings.json': unknown;
	'agents.json': unknown;
	'external-tools.json': unknown;
	'windows-diagnostics.json': unknown;
	'sessions.json': unknown;
	'groups.json': unknown;
	'processes.json': unknown;
	'logs.json': unknown;
	'errors.json': unknown;
	'web-server.json': unknown;
	'storage-info.json': unknown;
	'group-chats.json': unknown;
	'batch-state.json': unknown;
	'collection-errors.json'?: unknown;
}

/**
 * Generate the README content for the debug package.
 */
function generateReadme(): string {
	return `# Maestro Debug Package

This package was generated by Maestro for debugging purposes.

## Contents

- system-info.json - OS and hardware information
- settings.json - Application settings (sensitive data redacted)
- agents.json - AI agent configurations and availability
- external-tools.json - External dependencies (shells, git, gh CLI, cloudflared)
- sessions.json - Session metadata (no conversation content)
- groups.json - Session group configurations
- processes.json - Active process information
- logs.json - Recent system logs
- errors.json - Error states and recent errors
- web-server.json - Web server and tunnel status
- storage-info.json - Storage paths and sizes
- group-chats.json - Group chat metadata
- batch-state.json - Auto Run state

## Submission

To submit this debug package:
1. Open a GitHub issue at https://github.com/pedramamini/Maestro/issues
2. Describe the problem you encountered
3. Attach this zip file to the issue

## Privacy

This package does NOT contain:
- Your conversations with AI agents
- API keys or tokens
- File contents from your projects
- Passwords or secrets

All file paths have been sanitized to remove your username.
`;
}

/**
 * Create a zip package containing all debug data.
 */
export async function createZipPackage(
	outputDir: string,
	contents: Partial<PackageContents>
): Promise<{ path: string; sizeBytes: number }> {
	// Generate timestamp for filename
	const now = new Date();
	const timestamp = now.toISOString().replace(/[:.]/g, '-').slice(0, 19);
	const filename = `maestro-debug-${timestamp}.zip`;
	const outputPath = path.join(outputDir, filename);

	// Ensure output directory exists
	if (!fs.existsSync(outputDir)) {
		fs.mkdirSync(outputDir, { recursive: true });
	}

	return new Promise((resolve, reject) => {
		const output = fs.createWriteStream(outputPath);
		const archive = archiver('zip', {
			zlib: { level: 9 }, // Maximum compression
		});

		output.on('close', () => {
			resolve({
				path: outputPath,
				sizeBytes: archive.pointer(),
			});
		});

		archive.on('error', (err) => {
			reject(err);
		});

		// Pipe archive data to the file
		archive.pipe(output);

		// Add each JSON file to the archive
		for (const [filename, data] of Object.entries(contents)) {
			if (data !== undefined) {
				const jsonContent = JSON.stringify(data, null, 2);
				archive.append(jsonContent, { name: filename });
			}
		}

		// Add README
		archive.append(generateReadme(), { name: 'README.md' });

		// Finalize the archive
		archive.finalize();
	});
}
