// ISO_PasteClipboardAndReplaceSelectedLayers.jsx
// Artist: https://www.jasonfletcher.info/
// Code generated by ChatGPT-5.5
// Date: July 3, 2026
// Description: This script will paste the clipboard contents and will replace each selected layer (within the opened comp) while preserving the position, in point, out point, and stacking order. This has only been tested with pasting a layer (footage, adjustment layer, or solid layer) since this was the original use-case.

(function () {

    app.beginUndoGroup("Replace Selected Layers With Clipboard");

    try {

        var proj = app.project;

        if (!proj) {
            alert("No project is open.");
            return;
        }

        var comp = proj.activeItem;

        if (!(comp instanceof CompItem)) {
            alert("Please open and activate a composition.");
            return;
        }

        if (comp.selectedLayers.length === 0) {
            alert("Please select one or more layers.");
            return;
        }

        var pasteCommand = app.findMenuCommandId("Paste");

        if (pasteCommand === 0) {
            alert("Unable to locate the Paste command.");
            return;
        }

        // Cache the selected layers because selection changes during execution.
        var selectedLayers = [];
        var i;

        for (i = 0; i < comp.selectedLayers.length; i++) {
            selectedLayers.push(comp.selectedLayers[i]);
        }

        var replacedCount = 0;
        var skippedCount = 0;

        // Process from bottom to top so indices remain predictable.
        for (i = selectedLayers.length - 1; i >= 0; i--) {

            var originalLayer = selectedLayers[i];

            if (!originalLayer) {
                skippedCount++;
                continue;
            }

            var originalIndex = originalLayer.index;
            var originalInPoint = originalLayer.inPoint;
            var originalOutPoint = originalLayer.outPoint;

            var positionValue = null;

            try {
                positionValue = originalLayer.transform.position.value;
            } catch (e) {}

            // Only deselect the previously pasted layer (if any).
            if (comp.selectedLayers.length > 0) {
                comp.selectedLayers[0].selected = false;
            }

            originalLayer.selected = true;

            var beforeCount = comp.numLayers;

            app.executeCommand(pasteCommand);

            if (comp.numLayers <= beforeCount) {
                originalLayer.selected = false;
                skippedCount++;
                continue;
            }

            if (comp.selectedLayers.length === 0) {
                skippedCount++;
                continue;
            }

            var newLayer = comp.selectedLayers[0];

            // Restore transform.
            if (positionValue !== null) {
                try {
                    newLayer.transform.position.setValue(positionValue);
                } catch (e) {}
            }

            // Restore timing.
            newLayer.startTime = originalInPoint;
            newLayer.inPoint = originalInPoint;
            newLayer.outPoint = originalOutPoint;

            // Restore stacking order with one operation.
            newLayer.moveBefore(originalLayer);

            // Remove original layer.
            originalLayer.remove();

            replacedCount++;
        }

        alert(
            "Replace Clipboard Layers Complete\n\n" +
            "Layers replaced: " + replacedCount +
            "\nLayers skipped: " + skippedCount
        );

    } catch (err) {

        alert(
            "An error occurred:\n\n" +
            err.toString()
        );

    } finally {

        app.endUndoGroup();

    }

})();
