// Script to extract layer information from a PSD file

#target photoshop

// Function to export layer info as JSON
function exportLayerInfo() {
    try {
        if (app.documents.length === 0) {
            alert("No document is open!");
            return;
        }
        
        var doc = app.activeDocument;
        var layers = getAllLayers(doc);
        var layerInfo = {
            documentName: doc.name,
            width: doc.width.value,
            height: doc.height.value,
            layers: layers
        };
        
        // Save JSON to desktop
        var file = new File("~/Desktop/layer_info.json");
        file.open('w');
        file.write(JSON.stringify(layerInfo, null, 2));
        file.close();
        
        alert("Layer information saved to desktop as layer_info.json");
    } catch (e) {
        alert("Error: " + e);
    }
}

// Get all layers recursively
function getAllLayers(doc) {
    var layers = [];
    
    function traverse(layerSet, path) {
        for (var i = 0; i < layerSet.layers.length; i++) {
            var layer = layerSet.layers[i];
            var layerPath = path ? path + "/" + layer.name : layer.name;
            
            if (layer.typename === "ArtLayer") {
                var layerInfo = {
                    name: layer.name,
                    id: i + 1, // Custom ID based on index
                    path: layerPath,
                    type: layer.kind.toString(),
                    visible: layer.visible,
                    isTextLayer: layer.kind === LayerKind.TEXT
                };
                
                // Add text content if it's a text layer
                if (layer.kind === LayerKind.TEXT) {
                    layerInfo.text = layer.textItem.contents;
                }
                
                layers.push(layerInfo);
            } else if (layer.typename === "LayerSet") {
                // Handle layer sets (groups)
                layers.push({
                    name: layer.name,
                    id: i + 1, // Custom ID based on index
                    path: layerPath,
                    type: "LayerSet",
                    visible: layer.visible,
                    isGroup: true
                });
                
                // Traverse nested layers
                traverse(layer, layerPath);
            }
        }
    }
    
    traverse(doc, "");
    return layers;
}

// Run the script
exportLayerInfo();