import { execAsync } from '../../../utils.js';
import { createModuleLogger } from '../../../logger.js';
import { Platform } from '../../../types.js';
import { PlatformHandler } from '../../../platformHandler.js';
import { existsSync } from 'fs';
const logger = createModuleLogger('XcodeBuilder');
/**
 * Handles building Xcode projects (Single Responsibility: Building)
 */
export class XcodeBuilder {
    /**
     * Build an Xcode project or workspace
     */
    async build(projectPath, isWorkspace, options = {}) {
        const { scheme, configuration = 'Debug', platform = Platform.iOS, deviceId, derivedDataPath = './DerivedData' } = options;
        const projectFlag = isWorkspace ? '-workspace' : '-project';
        let command = `xcodebuild ${projectFlag} "${projectPath}"`;
        if (scheme) {
            command += ` -scheme "${scheme}"`;
        }
        command += ` -configuration "${configuration}"`;
        // Determine destination
        let destination;
        if (deviceId) {
            destination = PlatformHandler.getDestination(platform, deviceId);
        }
        else {
            destination = PlatformHandler.getGenericDestination(platform);
        }
        command += ` -destination '${destination}'`;
        command += ` -derivedDataPath "${derivedDataPath}" build`;
        logger.debug({ command }, 'Build command');
        try {
            const { stdout, stderr } = await execAsync(command, {
                maxBuffer: 50 * 1024 * 1024
            });
            const output = stdout + (stderr ? `\n${stderr}` : '');
            // Try to find the built app
            let appPath;
            try {
                const { stdout: findOutput } = await execAsync(`find "${derivedDataPath}" -name "*.app" -type d | head -1`);
                appPath = findOutput.trim() || undefined;
                if (appPath && !existsSync(appPath)) {
                    appPath = undefined;
                }
            }
            catch {
                // Ignore errors finding app path
            }
            logger.info({ projectPath, scheme, configuration, platform }, 'Build succeeded');
            return {
                success: true,
                output,
                appPath
            };
        }
        catch (error) {
            logger.error({ error: error.message, projectPath }, 'Build failed');
            const stdout = error.stdout || '';
            const stderr = error.stderr || '';
            const errorMessage = error.message || 'Unknown build error';
            let detailedError;
            if (stderr && stderr.includes('xcodebuild: error')) {
                detailedError = stderr;
            }
            else if (stdout && stdout.includes('xcodebuild')) {
                detailedError = stdout;
            }
            else {
                detailedError = errorMessage;
            }
            throw new Error(detailedError);
        }
    }
}
//# sourceMappingURL=XcodeBuilder.js.map