// ===================================================================
// Handler Function: checkWithXcode
// Builds Xcode projects with configurable options
// Fixed version - removes problematic shell script generation
// ===================================================================

// Import shared functions
const shared = require('sharedFunctions');

function taskLog(message) {
    console.log(message);
    stdOut.push(message);
}

/**
 * Check and build project with Xcode using xcodebuild
 * @param {Object} params - Command parameters
 * @param {string} params.projectName - Name of the project (without .xcodeproj extension)
 * @param {string} params.projectDir - Absolute path to the project directory
 * @param {string} [params.scheme=""] - Scheme name (defaults to first scheme if empty)
 * @param {string} [params.configuration="Debug"] - Build configuration (Debug/Release/Profile)
 * @param {string} [params.platform="macosx"] - Target platform (macosx/iphoneos/iphonesimulator)
 * @param {boolean} [params.clean=false] - Clean build before building
 * @param {boolean} [params.showOperationLogs=false] - Show verbose operation logs
 */

function checkWithXcode(params) {
    var projectName = params.projectName || "";
    var projectDir = params.projectDir || "";
    
    taskLog("=== Xcode Build Task ===");
    taskLog("Project: " + projectName);
    taskLog("Directory: " + projectDir);

    // Validate input parameters
    if (!projectDir) {
        return shared.createErrorResult("Missing required parameter: projectDir");
    }
    
    if (!MCPStudio.fileExists(projectDir)) {
        return shared.createErrorResult("Project directory not found: " + projectDir);
    }

    // Normalize project name (remove .xcodeproj extension if present)
    projectName = projectName.replace(/\.xcodeproj$/i, "");
    
    // Set default values from params
    var scheme = params.scheme || "";
    var configuration = params.configuration || "Debug";
    var platform = params.platform || "macosx";
    var codesign = params.codesign || params.codeSigningIdentity || "";
    var cleanBuild = (params.clean === true);
    var showOperationLogs = (params.showOperationLogs === true);
    var alltargets = (params.alltargets === true);

    taskLog("[Script] Scheme: " + scheme);
    taskLog("[Script] Configuration: " + configuration);
    taskLog("[Script] Platform: " + platform);
    taskLog("[Script] Clean Build: " + cleanBuild);
    taskLog("[Script] Show Operation Logs: " + showOperationLogs);
    taskLog("[Script] Team Identifier: " + codesign);

    var shellScript = '#!/bin/bash\n';
    var success = false;
    
    // get notified
    shellScript += 'set -euo pipefail\n';

    // Clean build artifacts if requested
    if (cleanBuild) {
        shellScript += '# Clean previous build artifacts\n';
        shellScript += 'rm -rf DerivedData/ || true\n\n';
        shellScript += 'rm -rf build/DerivedData/ || true\n\n';
        shellScript += 'rm -rf Build/DerivedData/ || true\n\n';
        taskLog("[Script] Cleaning previous builds...");
        success = MCPStudio.shell(shellScript);
        if (!success) {
            return shared.createErrorResult("Failed to clean build directory");
        }
    }
    
    shellScript += 'PROJECT_NAME="' + projectName + '"\n';
    shellScript += 'PROJECT_DIR="' + projectDir + '"\n';
    shellScript += 'ARCH=`uname -m`\n';
    shellScript += 'cd "${PROJECT_DIR}" || exit 1\n';
    shellScript += 'xcodebuild';
    // Use only valid xcodebuild parameters
    shellScript += ' -project "${PROJECT_NAME}.xcodeproj"';
    
    /* additional xcodebuild params */
    shellScript += ' -arch ${ARCH}';

    if (alltargets === true) {
        shellScript += ' -alltargets ';
    }
    
    if (codesign.length > 0) {
        shellScript += ' --codeSigningIdentity="' + codesign + '"';
    }
    if (scheme.length > 0) {
        shellScript += ' -scheme ' + scheme;
    }
    if (platform.length > 0) {
        shellScript += ' -sdk ' + platform;
    }
    // Fixed: check if configuration is not empty string instead of numeric comparison
    if (configuration && configuration.length > 0) {
        shellScript += ' -configuration ' + configuration;
    }
    /* end */
    if (codesign && codesign.length === 0) {
    	shellScript += ' CODE_SIGNING_ALLOWED=NO build || exit 1\n';
    } else {
    	shellScript += ' build || exit 1\n';
    }
    shellScript += 'exit 0\n';

    taskLog("[Script] Run: " + shellScript);
    
    success = MCPStudio.shell(shellScript);
    
    if (!success) {
        MCPStudio.setToolResult(JSON.stringify({
            text: "[Script] Build FAILED for " + projectName + "\n" + 
               (stdOut && stdOut.length > 0 ? stdOut.join("\n") : "") +  
               (stdErr && stdErr.length > 0 ? "\nErrors and Warnings:\n" + stdErr.join("\n") : ""),
            metadata: {
                path: projectDir,
                projectName: projectName,
                configuration: configuration,
                platform: platform,
                operation: "checkWithXcode",
                codesign: codesign,
                success: false,
                stdout: stdOut,
                stderr: stdErr,
            }
        }));
        taskLog("[Script] Build failed!"+ 
               (stdOut && stdOut.length > 0 ? stdOut.join("\n") : "") +  
               (stdErr && stdErr.length > 0 ? "\nErrors and Warnings:\n" + stdErr.join("\n") : ""));
    }
    else {
        MCPStudio.setToolResult(JSON.stringify({
            text: "Build completed successfully for " + projectName + "\n" + 
               (stdOut && stdOut.length > 0 ? stdOut.join("\n") : "") +  
               (stdErr && stdErr.length > 0 ? "\nErrors and Warnings:\n" + stdErr.join("\n") : ""),
            metadata: {
                path: projectDir,
                projectName: projectName,
                configuration: configuration,
                platform: platform,
                operation: "checkWithXcode",
                codesign: codesign,
                success: true,
                stdout: stdOut,
                stderr: stdErr,
            }
        }));
        taskLog("[Script] Build successful!");
    }

    return null; // Result already set via MCPStudio.setToolResult
}

module.exports = {
    checkWithXcode
};
